I’m using vim editor as python IDE. Below is a simple python program to calculate square root of a number:
import cmath
def sqrt():
try:
num = int(input("Enter the number : "))
if num >= 0:
main(num)
else:
complex(num)
except:
print("OOPS..!!Something went wrong, try again")
sqrt()
return
def main(num):
squareRoot = num**(1/2)
print("The square Root of ", num, " is ", squareRoot)
return
def complex(num):
ans = cmath.sqrt(num)
print("The Square root if ", num, " is ", ans)
return
sqrt()
And the warnings are :
1-square-root.py|2 col 1 C| E302 expected 2 blank lines, found 0 [pep8]
1-square-root.py|15 col 1 C| E302 expected 2 blank lines, found 1 [pep8]
1-square-root.py|21 col 1 C| E302 expected 2 blank lines, found 0 [pep8]
Can you please tell why these warnings are coming?
renatodamas
16.7k8 gold badges31 silver badges51 bronze badges
asked Nov 1, 2015 at 20:30
Amit UpadhyayAmit Upadhyay
7,1994 gold badges43 silver badges57 bronze badges
2
import cmath
def sqrt():
try:
num = int(input("Enter the number : "))
if num >= 0:
main(num)
else:
complex_num(num)
except:
print("OOPS..!!Something went wrong, try again")
sqrt()
return
def main(num):
square_root = num**(1/2)
print("The square Root of ", num, " is ", square_root)
return
def complex_num(num):
ans = cmath.sqrt(num)
print("The Square root if ", num, " is ", ans)
return
sqrt()
The previous will fix your PEP8 problems. After your import you need to have 2 new lines before starting your code. Also, between each def foo()
you need to have 2 as well.
In your case you had 0 after import, and you had 1 newline between each function. Part of PEP8 you need to have a newline after the end of your code. Unfortunately I don’t know how to show it when I paste your code in here.
Pay attention to the naming, it’s part of PEP8 as well. I changed complex
to complex_num
to prevent confusion with builtin complex
.
In the end, they’re only warning, they can be ignored if needed.
answered Nov 1, 2015 at 21:06
You need to give two blank lines between meaningful code blocks.
These include (for example):
- The import block
- Each function
8bitjunkie
12.8k9 gold badges57 silver badges70 bronze badges
answered Aug 9, 2017 at 9:59
1
Here is the link to the documentation:
PEP8 Style Guide for Python
You should add two spaces between the functions, as shown below:
import cmath
def sqrt():
try:
num = int(input("Enter the number : "))
if num >= 0:
main(num)
else:
complex_num(num)
except:
print("OOPS..!!Something went wrong, try again")
sqrt()
return
def main(num):
square_root = num ** (1 / 2)
print("The square Root of ", num, " is ", square_root)
return
def complex_num(num):
ans = cmath.sqrt(num)
print("The Square root if ", num, " is ", ans)
return
sqrt()
answered Aug 9, 2017 at 10:06
1
with warnings:-
import math
def my():
print("hello world")
my()
Without warnings:-
import math
def my():
print("hello world")
my()
Here if you see the two lines space after import statement for second code snippet which will not give any warnings.
Again if you are writing two methods definition you have two give two lines as space between your code block.
answered Aug 9, 2017 at 11:24
All answers seem to be correct. To avoid doing this by hand, you can also use the autopep8
package (pip install autopep8). The result of calling autopep8 filename.py
is the same:
import cmath
def sqrt():
try:
num = int(input("Enter the number : "))
if num >= 0:
main(num)
else:
complex(num)
except:
print("OOPS..!!Something went wrong, try again")
sqrt()
return
def main(num):
squareRoot = num**(1/2)
print("The square Root of ", num, " is ", squareRoot)
return
def complex(num):
ans = cmath.sqrt(num)
print("The Square root if ", num, " is ", ans)
return
sqrt()
PS: have a look at if __name__ == "__main__":
answered Mar 8, 2018 at 9:48
serv-incserv-inc
35.9k9 gold badges166 silver badges190 bronze badges
Search code, repositories, users, issues, pull requests…
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
import cmath
def sqrt():
try:
num = int(input("Enter the number : "))
if num >= 0:
main(num)
else:
complex_num(num)
except:
print("OOPS..!!Something went wrong, try again")
sqrt()
return
def main(num):
square_root = num**(1/2)
print("The square Root of ", num, " is ", square_root)
return
def complex_num(num):
ans = cmath.sqrt(num)
print("The Square root if ", num, " is ", ans)
return
sqrt()
Предыдущие исправят проблемы PEP8. После вашего импорта вам нужно иметь 2 новые строки перед началом кода. Кроме того, между каждым def foo()
вам также должно быть 2.
В вашем случае у вас было 0 после импорта, и у вас была 1 новая линия между каждой функцией. Часть PEP8 вам нужно иметь новую строку после окончания вашего кода. К сожалению, я не знаю, как это показать, когда я вставляю код здесь.
Обратите внимание на именование, это часть PEP8. Я изменил complex
на complex_num
, чтобы предотвратить путаницу со встроенным complex
.
В конце концов, они только предупреждают, их можно игнорировать при необходимости.
Содержание
- ожидается две пустые строки pep8 предупреждение в Python
- 4 ответа
- ожидается, что две пустые строки в Python pep8 предупреждение
- 5 ответов
- ожидается две пустые строки pep8 предупреждение в Python
- 5 ответов
- Форматирование Python-кода
- Введение
- Проблемы форматирования
- Стандарты и рекомендации к оформлению
- Автоматизируем форматирование
- autopep8
- autoflake
- unify
- docformatter
- А все вместе можно?
- Выводы
- Introduction¶
- Features¶
- Disclaimer¶
- Installation¶
- Example usage and output¶
- Configuration¶
- Error codes¶
ожидается две пустые строки pep8 предупреждение в Python
Я использую vim editor в Python IDE. Ниже приведена простая программа на Python для вычисления квадратного корня числа:
Подскажите, пожалуйста, почему появляются эти предупреждения?
4 ответа
Предыдущее исправит ваши PEP8 проблемы. После импорта вам нужно иметь 2 новые строки перед запуском кода. Кроме того, между каждым def foo() также должно быть 2.
В вашем случае после импорта у вас было 0, и между каждой функцией была 1 новая строка. Часть PEP8, вам нужно иметь новую строку после конца вашего кода. К сожалению, я не знаю, как показать это, когда я вставляю ваш код сюда.
Обратите внимание на именование, оно также является частью PEP8. Я изменил complex на complex_num , чтобы избежать путаницы со встроенным complex .
В конце концов, они только предупреждают, их можно игнорировать при необходимости.
Вот ссылка на документацию: Руководство по стилю PEP8 для Python
Вы должны добавить два пробела между функциями, как показано ниже:
Поскольку python строго следует за языком. Вы должны давать два пробела после каждого импорта, а также блок кода.
Здесь, если вы видите две строчки после оператора import для второго фрагмента кода, который не будет выдавать никаких предупреждений. Опять же, если вы пишете определение двух методов, у вас есть два, которые дают две строки как пробел между вашим блоком кода.
Источник
ожидается, что две пустые строки в Python pep8 предупреждение
Я использую редактор vim в качестве Python IDE. Ниже приведена простая программа python для вычисления квадратного корня числа:
можете ли вы сказать, почему эти предупреждения приходят?
5 ответов
предыдущий исправит ваш PEP8 проблемы. После импорта необходимо иметь 2 новые строки перед запуском кода. Кроме того, между def foo() вам также нужно иметь 2.
в вашем случае у вас было 0 после импорта, и у вас была 1 новая строка между каждой функцией. Часть PEP8 вам нужно иметь новую строку после окончания кода. К сожалению, я не знаю, как показать это, когда я вставляю ваш код здесь.
обратите внимание на именования, это также часть PEP8. Я изменился complex to complex_num для предотвращения путаницы с builtin complex .
в конце концов, они только предупреждение, их можно игнорировать, если это необходимо.
вот ссылка на документацию: руководство по стилю PEP8 для Python
Вы должны добавить два пробела между функциями, как показано ниже:
поскольку python строго следует языку .Вы должны дать два пробела после каждого импорта, а также блок кода.
здесь, Если вы видите пространство двух строк после инструкции import для второго фрагмента кода, который не будет давать никаких предупреждений. Опять же, если вы пишете определение двух методов, у вас есть две строки в качестве пространства между вашим блоком кода.
Источник
ожидается две пустые строки pep8 предупреждение в Python
Я использую Vim Editor в качестве Python IDE. Ниже приведена простая программа на Python для вычисления квадратного корня числа:
Можете ли вы сказать, почему эти предупреждения приходят?
5 ответов
Предыдущее исправит ваши PEP8 проблемы. После импорта вам нужно иметь 2 новые строки перед запуском кода. Кроме того, между каждым def foo() также должно быть 2.
В вашем случае у вас было 0 после импорта, и у вас была 1 новая строка между каждой функцией. Часть PEP8, вам нужно иметь новую строку после конца вашего кода. К сожалению, я не знаю, как показать это, когда я вставляю ваш код сюда.
Обратите внимание на именование, это тоже часть PEP8. Я изменил complex на complex_num , чтобы избежать путаницы со встроенным complex .
В конце концов, они только предупреждают, их можно игнорировать при необходимости.
Здесь, если вы видите две строчки после оператора import для второго фрагмента кода, который не будет выдавать никаких предупреждений. Опять же, если вы пишете определение двух методов, у вас есть два, которые дают две строки как пробел между вашим блоком кода.
Вот ссылка на документацию: Руководство по стилю PEP8 для Python
Вы должны добавить два пробела между функциями, как показано ниже:
Вам нужно дать две пустые строки между значимыми блоками кода.
Источник
Форматирование Python-кода
Введение
Python, точнее его самый известный представитель CPython, не очень предназначен для каких-либо быстрых расчетов. Иначе говоря, производительность у него не такая уж хорошая. А вот скорость разработки и читаемости отличная.
О читаемости и пойдет речь, а точнее как ее увеличить.
Проблемы форматирования
Идеального форматирования кода не существует. Для каждого языка стоит подстраиваться под общепринятые правила оформления кода. Да что говорить, если среди новичков С++ еще до сих пор войны по поводу ставить скобки на следующей строке или нет.
Для python’а основными проблемами форматирования является «C стиль». Не редко в рассматриваемый язык приходят из С-подобных языков, а для них свойственно писать с символами «)(;».
Символы не единственная проблема, есть еще и проблема избыточности написания конструкций. Питон, в отличие от Java, менее многословен и чтобы к этому привыкнуть у новичков уходит большое количество времени.
Это две основные проблемы, которые встречаются чаще всего.
Стандарты и рекомендации к оформлению
Если для повышения скорости исполнения кода можно использовать разные подходы, хотя эти подходы очень индивидуальны, то для форматирования текста существует прям slyle guide — это pep8. Далее его буду называть «стандарт».
Почитать про стандарт можно здесь, на русском языке можно здесь
Pep8 весьма обширный и позволяет программисту писать РЕАЛЬНО читаемый код.
Он включает:
- максимальную длину строк кода и документации
- кодировки файлов с исходным кодом
- рекомендации как правильно оформлять комментарии
- соглашения именования функций/классов, аргументов
- и многое другое
В целом, покрывает множество правил форматирования кода. Однако, стоит заметить, что не все python-программисты соблюдают данные правила.
Большие компании, такие как Google, имеют свои рекомендации к написанию python-кода, их можно почитать здесь и здесь.
Весьма интересное чтиво, рекомендую.
Автоматизируем форматирование
Если посмотреть сколько всяких правил в pep8, то можно сесть за рефакторинг надолго. Вот только это лениво, да и при написании нового кода сиравно будут какие-то ошибки правил. Для этого рассмотрим как же себе можно упростить жизнь.
Дабы иметь представление сколько ошибок оформления в коде, стоит использовать утилиту pep8.
У нее достаточный список параметров, который позволяет рекурсивно просмотреть все файлы в папках на предмет соответствия стандарту pep8.
Вывод утилиты примерно такой:
По нему можно однозначно понять: где ошибка и что случилось.
autopep8
Ошибки стандарта часто повторяются от файла в файлу. И возникает сильное желание исправление автоматизировать. В этом случае на арену выходит autopep8.
Как и pep8, он умеет самостоятельно определять ошибки, а также исправлять их. Список исправляемых ошибок форматирования можно найти здесь
Само использование autopep8 крайне простое и может выглядеть так:
После выполнения данной команды, утилита рекурсивно пойдет по подпапкам и начнет в самих же файлах исправлять ошибки.
autoflake
Можно пойти дальше и в качестве оружия взять autoflake. Эта утилита помогает удалить не используемые импорты и переменные.
Используется примерно так:
Тем самым будут рекурсивно почищены файлы в директории.
unify
Крайний, заключительный момент в редактировании кода — это строки. Кто-то любит их писать в одиночных апострофах, кто-то в двойных. Вот только и для этого существует рекомендации, а также и утилита, которая позволяет автоматически приводить в соответствие — unify
Использование:
Как и везде, утилита выполнит свое грязное дело рекурсивно для файлов в папке.
docformatter
Все время говорим о самом коде, а о комментариях еще ни разу не шло речи. Настало время — docformatter. Эта утилита помогает привести ваши docstring по соглашению PEP 257. Соглашение предписывает как следует оформлять документацию.
Использование утилиты ничуть не сложнее предыдущих:
А все вместе можно?
Выше описаны утилиты, их запуск можно добавить какой-нибудь bash скрипт под магическим названием clean.bash и запускать. А можно пойти и по другому пути и использовать wrapper над этими утилитами — pyformat
Выводы
Python-код легко читается, однако, есть способы сделать лапшу и из читаемого кода.
В данной статье были озвучены некоторые проблемы оформления кода, а также способы поиска этих проблем. Были рассмотрены несколько утилит, которые позволяют в автоматическом режиме убрать некоторые изъяны оформления кода.
Стоит озвучить вслух следующую рекомендацию при написании кода, которая универсальна для любого языка: более важным правилом оформлением, чем подобные pep8-документы — это постоянство стиля. Выбрали в каком стиле будете писать программу, в этом же и пишите весь код.
Если читателям будет интересно, то в следующей статье я опишу как в автоматическом режиме искать ошибки в коде.
Источник
Introduction¶
pep8 is a tool to check your Python code against some of the style conventions in PEP 8.
Features¶
- Plugin architecture: Adding new checks is easy.
- Parseable output: Jump to error location in your editor.
- Small: Just one Python file, requires only stdlib. You can use just the pep8.py file for this purpose.
- Comes with a comprehensive test suite.
Disclaimer¶
This utility does not enforce every single rule of PEP 8. It helps to verify that some coding conventions are applied but it does not intend to be exhaustive. Some rules cannot be expressed with a simple algorithm, and other rules are only guidelines which you could circumvent when you need to.
Always remember this statement from PEP 8:
Among other things, these features are currently not in the scope of the pep8 library:
- naming conventions: this kind of feature is supported through plugins. Install flake8 and the pep8-naming extension to use this feature.
- docstring conventions: they are not in the scope of this library; see the pep257 project.
- automatic fixing: see the section PEP8 Fixers in the related tools page.
Installation¶
You can install, upgrade, uninstall pep8.py with these commands:
There’s also a package for Debian/Ubuntu, but it’s not always the latest version:
Example usage and output¶
You can also make pep8.py show the source code for each error, and even the relevant text from PEP 8:
Or you can display how often each error was found:
You can also make pep8.py show the error text in different formats by using –format having options default/pylint/custom:
Variables in the custom format option
Variable | Significance |
---|---|
path | File name |
row | Row number |
col | Column number |
code | Error code |
text | Error text |
Quick help is available on the command line:
Configuration¶
The behaviour may be configured at two levels, the user and project levels.
At the user level, settings are read from the following locations:
\.pep8 Otherwise, if the XDG_CONFIG_HOME environment variable is defined: XDG_CONFIG_HOME/pep8 Else if XDG_CONFIG_HOME is not defined:
At the project level, a setup.cfg file or a tox.ini file is read if present ( .pep8 file is also supported, but it is deprecated). If none of these files have a [pep8] section, no project specific configuration is loaded.
Error codes¶
This is the current list of error and warning codes:
code | sample message |
---|---|
E1 | Indentation |
E101 | indentation contains mixed spaces and tabs |
E111 | indentation is not a multiple of four |
E112 | expected an indented block |
E113 | unexpected indentation |
E114 | indentation is not a multiple of four (comment) |
E115 | expected an indented block (comment) |
E116 | unexpected indentation (comment) |
E121 (*^) | continuation line under-indented for hanging indent |
E122 (^) | continuation line missing indentation or outdented |
E123 (*) | closing bracket does not match indentation of opening bracket’s line |
E124 (^) | closing bracket does not match visual indentation |
E125 (^) | continuation line with same indent as next logical line |
E126 (*^) | continuation line over-indented for hanging indent |
E127 (^) | continuation line over-indented for visual indent |
E128 (^) | continuation line under-indented for visual indent |
E129 (^) | visually indented line with same indent as next logical line |
E131 (^) | continuation line unaligned for hanging indent |
E133 (*) | closing bracket is missing indentation |
E2 | Whitespace |
E201 | whitespace after ‘(‘ |
E202 | whitespace before ‘)’ |
E203 | whitespace before ‘:’ |
E211 | whitespace before ‘(‘ |
E221 | multiple spaces before operator |
E222 | multiple spaces after operator |
E223 | tab before operator |
E224 | tab after operator |
E225 | missing whitespace around operator |
E226 (*) | missing whitespace around arithmetic operator |
E227 | missing whitespace around bitwise or shift operator |
E228 | missing whitespace around modulo operator |
E231 | missing whitespace after ‘,’, ‘;’, or ‘:’ |
E241 (*) | multiple spaces after ‘,’ |
E242 (*) | tab after ‘,’ |
E251 | unexpected spaces around keyword / parameter equals |
E261 | at least two spaces before inline comment |
E262 | inline comment should start with ‘# ‘ |
E265 | block comment should start with ‘# ‘ |
E266 | too many leading ‘#’ for block comment |
E271 | multiple spaces after keyword |
E272 | multiple spaces before keyword |
E273 | tab after keyword |
E274 | tab before keyword |
E3 | Blank line |
E301 | expected 1 blank line, found 0 |
E302 | expected 2 blank lines, found 0 |
E303 | too many blank lines (3) |
E304 | blank lines found after function decorator |
E4 | Import |
E401 | multiple imports on one line |
E402 | module level import not at top of file |
E5 | Line length |
E501 (^) | line too long (82 > 79 characters) |
E502 | the backslash is redundant between brackets |
E7 | Statement |
E701 | multiple statements on one line (colon) |
E702 | multiple statements on one line (semicolon) |
E703 | statement ends with a semicolon |
E704 (*) | multiple statements on one line (def) |
E711 (^) | comparison to None should be ‘if cond is None:’ |
E712 (^) | comparison to True should be ‘if cond is True:’ or ‘if cond:’ |
E713 | test for membership should be ‘not in’ |
E714 | test for object identity should be ‘is not’ |
E721 (^) | do not compare types, use ‘isinstance()’ |
E731 | do not assign a lambda expression, use a def |
E9 | Runtime |
E901 | SyntaxError or IndentationError |
E902 | IOError |
W1 | Indentation warning |
W191 | indentation contains tabs |
W2 | Whitespace warning |
W291 | trailing whitespace |
W292 | no newline at end of file |
W293 | blank line contains whitespace |
W3 | Blank line warning |
W391 | blank line at end of file |
W5 | Line break warning |
W503 | line break occurred before a binary operator |
W6 | Deprecation warning |
W601 | .has_key() is deprecated, use ‘in’ |
W602 | deprecated form of raising exception |
W603 | ‘<>’ is deprecated, use ‘!=’ |
W604 | backticks are deprecated, use ‘repr()’ |
(*) In the default configuration, the checks E121, E123, E126, E133, E226, E241, E242 and E704 are ignored because they are not rules unanimously accepted, and PEP 8 does not enforce them. The check E133 is mutually exclusive with check E123. Use switch —hang- closing to report E133 instead of E123.
(^) These checks can be disabled at the line level using the # noqa special comment. This possibility should be reserved for special cases.
Note: most errors can be listed with such one-liner:
Источник