E303 python ошибка

Two blank lines are expected between functions and classes and one blank line is expected between methods of a class.

Anti-pattern

This example has too many blank lines.

def func1():
    pass



def func2():
    pass

Best practice

def func1():
    pass


def func2():
    pass

Additional links

  • https://www.python.org/dev/peps/pep-0008/#blank-lines

Permalink

Cannot retrieve contributors at this time

code message title links

E303

Too many blank lines (3)

Too many blank lines (3) (E303)

https://www.python.org/dev/peps/pep-0008/#blank-lines

Two blank lines are expected between functions and classes and one blank line is expected between methods of a class.

Anti-pattern

This example has too many blank lines.

def func1():
    pass



def func2():
    pass

Best practice

def func1():
    pass


def func2():
    pass

Too many blank lines (3)

Two blank lines are expected between functions and classes and one blank line is expected between methods of a class.

Anti-pattern

This example has too many blank lines.

def func1():
    pass



def func2():
    pass

Best practice

def func1():
    pass


def func2():
    pass

What is PEP 8 ?

Before going into details of PEP 8 the first thing that we need to understand that what exactly is PEP and what is 8 signifies in PEP 8.
PEP contains the index of all Python Enhancement Proposals, known as PEPs. This is an aggregate of documents which explains about information, new features, process and environment settings for python community.
PEP numbers are assigned by the PEP editors, and once assigned are never changed. It signifies the document number.
PEP 8 means Python Enhancement Proposal document number 8 which details about Style Guide for Python Code. This style guide evolves over time as additional conventions are identified and past conventions are rendered obsolete by changes in the language itself.
Although there is no restriction of using all the PEP 8 rule these are good to have as it helps in making code consistency and improve code readability.

You can install, upgrade, uninstall pycodestyle.py (formerly called pep8)with these commands:

$ pip install pycodestyle
$ pip install --upgrade pycodestyle
$ pip uninstall pycodestyle

Enter fullscreen mode

Exit fullscreen mode

Pycodestyle(formerly called pep8) Usage

For demo purpose lets created a test python file with a function to find the max between two numbers find_max.py having content as —

def find_max_number(a:int,b:int)->int:
    return a if a>b else b
if __name__ == "__main__":
    find_max_number(10,15)
Executing pycodestyle for this file
pycodestyle find_max.py
find_max.py:3:22: E231 missing whitespace after ':'
find_max.py:3:26: E231 missing whitespace after ','
find_max.py:3:28: E231 missing whitespace after ':'
find_max.py:3:33: E225 missing whitespace around operator
find_max.py:4:18: E225 missing whitespace around operator
find_max.py:6:1: E305 expected 2 blank lines after class or function definition, found 1
find_max.py:7:23: E231 missing whitespace after ','
find_max.py:7:27: W292 no newline at end of file

Enter fullscreen mode

Exit fullscreen mode

In this case we have 8 violations.
As you see above, it outputs the file name which has violations, location, error code and that content.

In order to get output summary of PEP 8 violations we need run the following command pycodestyle --statistics --qq <file_name>

pycodestyle  --statistics -qq find_max.py
2       E225 missing whitespace around operator
4       E231 missing whitespace after ':'
1       E305 expected 2 blank lines after class or function definition, found 1
1       W292 no newline at end of file

Enter fullscreen mode

Exit fullscreen mode

In order to have more details on the voilation we need to use show-source option as pycodestyle --show-source <file_name>

pycodestyle  --show-source  find_max.py 
find_max.py:3:22: E231 missing whitespace after ':'
def find_max_number(a:int,b:int)->int:
                     ^
find_max.py:3:26: E231 missing whitespace after ','
def find_max_number(a:int,b:int)->int:
                         ^
find_max.py:3:28: E231 missing whitespace after ':'
def find_max_number(a:int,b:int)->int:
                           ^
find_max.py:3:33: E225 missing whitespace around operator
def find_max_number(a:int,b:int)->int:
                                ^
find_max.py:4:18: E225 missing whitespace around operator
    return a if a>b else b
                 ^
find_max.py:6:1: E305 expected 2 blank lines after class or function definition, found 1
if __name__ == "__main__":
^
find_max.py:7:23: E231 missing whitespace after ','
    find_max_number(10,15)
                      ^
find_max.py:7:27: W292 no newline at end of file
    find_max_number(10,15)
                        ^

Enter fullscreen mode

Exit fullscreen mode

Moreover you can see the description of how to fix. This is --show-pep8 option.

pycodestyle --show-pep8 find_max.py
find_max.py:3:22: E231 missing whitespace after ':'
    Each comma, semicolon or colon should be followed by whitespace.
Okay: [a, b]
    Okay: (3,)
    Okay: a[1:4]
    Okay: a[:4]
    Okay: a[1:]
    Okay: a[1:4:2]
    E231: ['a','b']
    E231: foo(bar,baz)
    E231: [{'a':'b'}]
find_max.py:3:26: E231 missing whitespace after ','
    Each comma, semicolon or colon should be followed by whitespace.
Okay: [a, b]
    Okay: (3,)
    Okay: a[1:4]
    Okay: a[:4]
    Okay: a[1:]
    Okay: a[1:4:2]
    E231: ['a','b']
    E231: foo(bar,baz)
    E231: [{'a':'b'}]
find_max.py:3:28: E231 missing whitespace after ':'
    Each comma, semicolon or colon should be followed by whitespace.
Okay: [a, b]
    Okay: (3,)
    Okay: a[1:4]
    Okay: a[:4]
    Okay: a[1:]
    Okay: a[1:4:2]
    E231: ['a','b']
    E231: foo(bar,baz)
    E231: [{'a':'b'}]
find_max.py:3:33: E225 missing whitespace around operator
    Surround operators with a single space on either side.
- Always surround these binary operators with a single space on
      either side: assignment (=), augmented assignment (+=, -= etc.),
      comparisons (==, <, >, !=, <=, >=, in, not in, is, is not),
      Booleans (and, or, not).
- If operators with different priorities are used, consider adding
      whitespace around the operators with the lowest priorities.
Okay: i = i + 1
    Okay: submitted += 1
    Okay: x = x * 2 - 1
    Okay: hypot2 = x * x + y * y
    Okay: c = (a + b) * (a - b)
    Okay: foo(bar, key='word', *args, **kwargs)
    Okay: alpha[:-i]
E225: i=i+1
    E225: submitted +=1
    E225: x = x /2 - 1
    E225: z = x **y
    E225: z = 1and 1
    E226: c = (a+b) * (a-b)
    E226: hypot2 = x*x + y*y
    E227: c = a|b
    E228: msg = fmt%(errno, errmsg)
find_max.py:4:18: E225 missing whitespace around operator
    Surround operators with a single space on either side.
- Always surround these binary operators with a single space on
      either side: assignment (=), augmented assignment (+=, -= etc.),
      comparisons (==, <, >, !=, <=, >=, in, not in, is, is not),
      Booleans (and, or, not).
- If operators with different priorities are used, consider adding
      whitespace around the operators with the lowest priorities.
Okay: i = i + 1
    Okay: submitted += 1
    Okay: x = x * 2 - 1
    Okay: hypot2 = x * x + y * y
    Okay: c = (a + b) * (a - b)
    Okay: foo(bar, key='word', *args, **kwargs)
    Okay: alpha[:-i]
E225: i=i+1
    E225: submitted +=1
    E225: x = x /2 - 1
    E225: z = x **y
    E225: z = 1and 1
    E226: c = (a+b) * (a-b)
    E226: hypot2 = x*x + y*y
    E227: c = a|b
    E228: msg = fmt%(errno, errmsg)
find_max.py:6:1: E305 expected 2 blank lines after class or function definition, found 1
    Separate top-level function and class definitions with two blank
    lines.
Method definitions inside a class are separated by a single blank
    line.
Extra blank lines may be used (sparingly) to separate groups of
    related functions.  Blank lines may be omitted between a bunch of
    related one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical
    sections.
Okay: def a():n    passnnndef b():n    pass
    Okay: def a():n    passnnnasync def b():n    pass
    Okay: def a():n    passnnn# Foon# Barnndef b():n    pass
    Okay: default = 1nfoo = 1
    Okay: classify = 1nfoo = 1
E301: class Foo:n    b = 0n    def bar():n        pass
    E302: def a():n    passnndef b(n):n    pass
    E302: def a():n    passnnasync def b(n):n    pass
    E303: def a():n    passnnnndef b(n):n    pass
    E303: def a():nnnn    pass
    E304: @decoratornndef a():n    pass
    E305: def a():n    passna()
    E306: def a():n    def b():n        passn    def c():n        pass
find_max.py:7:23: E231 missing whitespace after ','
    Each comma, semicolon or colon should be followed by whitespace.
Okay: [a, b]
    Okay: (3,)
    Okay: a[1:4]
    Okay: a[:4]
    Okay: a[1:]
    Okay: a[1:4:2]
    E231: ['a','b']
    E231: foo(bar,baz)
    E231: [{'a':'b'}]
find_max.py:7:27: W292 no newline at end of file
    Trailing blank lines are superfluous.
Okay: spam(1)
    W391: spam(1)n
However the last line should end with a new line (warning W292).

Enter fullscreen mode

Exit fullscreen mode

If we want to exclude specific errors and warning while running pycodestyle we can use the option -ignore and provide the comma separated values of the error codes need to be excluded.

pycodestyle - ignore=E231,E225 find_max.py
find_max.py:6:1: E305 expected 2 blank lines after class or function definition, found 1
find_max.py:7:27: W292 no newline at end of file

Enter fullscreen mode

Exit fullscreen mode

As we have put E231,E225 in the ignore list the PEP 8 violation count reduced to 2 from 8 which is without ignoring these errors.

PEP 8 Error codes

Code can either denote an error or warning in case of error codes the code start with E followed by a 3 digit number for e.g E101 and for warning code it start with E followed by a 3 digit number for e.g W191.

Below is the classification of error code based on series number.
100 series … (E1 and W1) related to indentation.
200 series … (E2 and W2) related to whitespace.
300 series … (E3 and W3) related to blank lines.
400 series … (E4 and W4) related to imports.
500 series … (E5 and W5) related to line length.
600 series … (E6 and W6) related to deprecation.
700 series … (E7) related to statements.
900 series … (E9) related to syntax errors.

You can refer to official document for more detailing on error code link.

Customization of pep8

We can customise the PEP 8 config to meet our requirement as in we might need to ignore certain errors and warning and also we want to alter the max-line-length etc.
Default user configuration file is in ‘~/.config/pycodestyle‘.
You can write the configuration file as below, this is same as option.

[pep8]
ignore = E231,E225
max-line-length = 160

Enter fullscreen mode

Exit fullscreen mode

You can specify the configuration file location by--config=<configration_file_location> .
By storing above configuration file in a certain location in respective projects, you can share it in the projects.
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.

Commonly used PEP 8 guidelines

The PEP 8 guidelines can classified in 7 different categories as

Code Lay-out

  • Use 4 spaces per indentation level.
  • Use spaces not tabs python disallows mixing tabs and spaces for indentation.
  • Limit all lines to a maximum of 79 characters.
  • Should a line break before or after binary operator? In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally.
  • Surround top-level function and class definitions with two blank lines.
  • Code in the core Python distribution should always use UTF-8, and should not have an encoding declaration.

Imports should be grouped in the following order:

  1. Standard library imports.
  2. Related third party imports.
  3. Local application/library specific imports.
    Wildcard imports (from import *) should be avoided.

Naming Conventions

Naming conventions are the most important pillar in maintaining the code consistency and readability there is as such no rule book to define the naming conventions but PEP 8 has recommendation that is good to follow.

  • Never use the characters ‘l’ , ‘O’ , or ‘I’ (uppercase letter eye) as single character variable names. In some fonts, these characters are indistinguishable from the numerals one and zero.
  • Class names should normally use the Cap Words (Camel case) convention.
  • Variables and function names should have all lowercase letters and underscores to separate words.
  • Constant should have all uppercase letters with words separated by underscores
  • Use the suffix «Error» on your exception names (if the exception actually is an error).
  • Use self for the first argument to instance methods or class methods.

String Quotes

  • In Python, single-quoted strings and double-quoted strings are the same. PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.
  • Whitespace in Expression and Statement
  • Avoid trailing whitespace anywhere. Because it’s usually invisible, it can be confusing: e.g. a backslash followed by a space and a newline does not count as a line continuation marker.
  • Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).
  • Use whitespace to communicate order of operations. x = 12*y + 22*z.
  • Avoid excessive whitespace immediately inside of parenthesis, brackets, or braces.

When to use trailing commas

  • Trailing commas are usually optional, except they are mandatory when making a tuple of one element. For clarity, it is recommended to surround the latter in parentheses:
# Correct:
FILES = ('setup.cfg',)
# Wrong:
FILES = 'setup.cfg',

Enter fullscreen mode

Exit fullscreen mode

Programming Recommendations

  • Comparisons to singletons like None should always be done with is or is not, never the equality operators.
  • Use is notoperator rather than not … is for e.g if foo is not None rather than if not foo is None:
  • When implementing ordering operations with rich comparisons, it is best to implement all six operations (eq, ne, lt, le, gt, ge) rather than relying on other code to only exercise a particular comparison.
  • When catching exceptions, mention specific exceptions whenever possible instead of using a bare except.
  • Object type comparisons should always use isinstance() instead of comparing types directly.

Comments

Each line of a block comment starts with a # and a single space.
Use inline comments only if it is unavoidable.
Write docstrings for all public modules, functions, classes, and methods.
Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does.

For more detailing on the PEP 8 guidelines please check out the official documentation PEP 8 Guidelines

Conclusion

Likewise pycodestyle there is flake8 which is also widely used for checking the code style PEP 8 guidelines in python code. It’s always better to have these plugins in the ide and everytime you save or commit it will highlight the violations.
Maintaining the code style guideline helps in better readability and code consistency. Although it’s a good to have but always prefer to have coding guidelines while writing code.

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

E275
missing whitespace after 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

E305
expected 2 blank lines after end of function or class

E306
expected 1 blank line before a nested definition

 
 

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()’

E722
do not use bare except, specify exception instead

E731
do not assign a lambda expression, use a def

E741
do not use variables named ‘l’, ‘O’, or ‘I’

E742
do not define classes named ‘l’, ‘O’, or ‘I’

E743
do not define functions named ‘l’, ‘O’, or ‘I’

 
 

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 before binary operator

W504 (*)
line break after binary operator

W505 (*^)
doc line too long (82 > 79 characters)

 
 

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()’

W605
invalid escape sequence ‘x’

W606
‘async’ and ‘await’ are reserved keywords starting with Python 3.7

What is PEP 8 ?

Before going into details of PEP 8 the first thing that we need to understand that what exactly is PEP and what is 8 signifies in PEP 8.
PEP contains the index of all Python Enhancement Proposals, known as PEPs. This is an aggregate of documents which explains about information, new features, process and environment settings for python community.
PEP numbers are assigned by the PEP editors, and once assigned are never changed. It signifies the document number.
PEP 8 means Python Enhancement Proposal document number 8 which details about Style Guide for Python Code. This style guide evolves over time as additional conventions are identified and past conventions are rendered obsolete by changes in the language itself.
Although there is no restriction of using all the PEP 8 rule these are good to have as it helps in making code consistency and improve code readability.

You can install, upgrade, uninstall pycodestyle.py (formerly called pep8)with these commands:

$ pip install pycodestyle
$ pip install --upgrade pycodestyle
$ pip uninstall pycodestyle

Enter fullscreen mode

Exit fullscreen mode

Pycodestyle(formerly called pep8) Usage

For demo purpose lets created a test python file with a function to find the max between two numbers find_max.py having content as —

def find_max_number(a:int,b:int)->int:
    return a if a>b else b
if __name__ == "__main__":
    find_max_number(10,15)
Executing pycodestyle for this file
pycodestyle find_max.py
find_max.py:3:22: E231 missing whitespace after ':'
find_max.py:3:26: E231 missing whitespace after ','
find_max.py:3:28: E231 missing whitespace after ':'
find_max.py:3:33: E225 missing whitespace around operator
find_max.py:4:18: E225 missing whitespace around operator
find_max.py:6:1: E305 expected 2 blank lines after class or function definition, found 1
find_max.py:7:23: E231 missing whitespace after ','
find_max.py:7:27: W292 no newline at end of file

Enter fullscreen mode

Exit fullscreen mode

In this case we have 8 violations.
As you see above, it outputs the file name which has violations, location, error code and that content.

In order to get output summary of PEP 8 violations we need run the following command pycodestyle --statistics --qq <file_name>

pycodestyle  --statistics -qq find_max.py
2       E225 missing whitespace around operator
4       E231 missing whitespace after ':'
1       E305 expected 2 blank lines after class or function definition, found 1
1       W292 no newline at end of file

Enter fullscreen mode

Exit fullscreen mode

In order to have more details on the voilation we need to use show-source option as pycodestyle --show-source <file_name>

pycodestyle  --show-source  find_max.py 
find_max.py:3:22: E231 missing whitespace after ':'
def find_max_number(a:int,b:int)->int:
                     ^
find_max.py:3:26: E231 missing whitespace after ','
def find_max_number(a:int,b:int)->int:
                         ^
find_max.py:3:28: E231 missing whitespace after ':'
def find_max_number(a:int,b:int)->int:
                           ^
find_max.py:3:33: E225 missing whitespace around operator
def find_max_number(a:int,b:int)->int:
                                ^
find_max.py:4:18: E225 missing whitespace around operator
    return a if a>b else b
                 ^
find_max.py:6:1: E305 expected 2 blank lines after class or function definition, found 1
if __name__ == "__main__":
^
find_max.py:7:23: E231 missing whitespace after ','
    find_max_number(10,15)
                      ^
find_max.py:7:27: W292 no newline at end of file
    find_max_number(10,15)
                        ^

Enter fullscreen mode

Exit fullscreen mode

Moreover you can see the description of how to fix. This is --show-pep8 option.

pycodestyle --show-pep8 find_max.py
find_max.py:3:22: E231 missing whitespace after ':'
    Each comma, semicolon or colon should be followed by whitespace.
Okay: [a, b]
    Okay: (3,)
    Okay: a[1:4]
    Okay: a[:4]
    Okay: a[1:]
    Okay: a[1:4:2]
    E231: ['a','b']
    E231: foo(bar,baz)
    E231: [{'a':'b'}]
find_max.py:3:26: E231 missing whitespace after ','
    Each comma, semicolon or colon should be followed by whitespace.
Okay: [a, b]
    Okay: (3,)
    Okay: a[1:4]
    Okay: a[:4]
    Okay: a[1:]
    Okay: a[1:4:2]
    E231: ['a','b']
    E231: foo(bar,baz)
    E231: [{'a':'b'}]
find_max.py:3:28: E231 missing whitespace after ':'
    Each comma, semicolon or colon should be followed by whitespace.
Okay: [a, b]
    Okay: (3,)
    Okay: a[1:4]
    Okay: a[:4]
    Okay: a[1:]
    Okay: a[1:4:2]
    E231: ['a','b']
    E231: foo(bar,baz)
    E231: [{'a':'b'}]
find_max.py:3:33: E225 missing whitespace around operator
    Surround operators with a single space on either side.
- Always surround these binary operators with a single space on
      either side: assignment (=), augmented assignment (+=, -= etc.),
      comparisons (==, <, >, !=, <=, >=, in, not in, is, is not),
      Booleans (and, or, not).
- If operators with different priorities are used, consider adding
      whitespace around the operators with the lowest priorities.
Okay: i = i + 1
    Okay: submitted += 1
    Okay: x = x * 2 - 1
    Okay: hypot2 = x * x + y * y
    Okay: c = (a + b) * (a - b)
    Okay: foo(bar, key='word', *args, **kwargs)
    Okay: alpha[:-i]
E225: i=i+1
    E225: submitted +=1
    E225: x = x /2 - 1
    E225: z = x **y
    E225: z = 1and 1
    E226: c = (a+b) * (a-b)
    E226: hypot2 = x*x + y*y
    E227: c = a|b
    E228: msg = fmt%(errno, errmsg)
find_max.py:4:18: E225 missing whitespace around operator
    Surround operators with a single space on either side.
- Always surround these binary operators with a single space on
      either side: assignment (=), augmented assignment (+=, -= etc.),
      comparisons (==, <, >, !=, <=, >=, in, not in, is, is not),
      Booleans (and, or, not).
- If operators with different priorities are used, consider adding
      whitespace around the operators with the lowest priorities.
Okay: i = i + 1
    Okay: submitted += 1
    Okay: x = x * 2 - 1
    Okay: hypot2 = x * x + y * y
    Okay: c = (a + b) * (a - b)
    Okay: foo(bar, key='word', *args, **kwargs)
    Okay: alpha[:-i]
E225: i=i+1
    E225: submitted +=1
    E225: x = x /2 - 1
    E225: z = x **y
    E225: z = 1and 1
    E226: c = (a+b) * (a-b)
    E226: hypot2 = x*x + y*y
    E227: c = a|b
    E228: msg = fmt%(errno, errmsg)
find_max.py:6:1: E305 expected 2 blank lines after class or function definition, found 1
    Separate top-level function and class definitions with two blank
    lines.
Method definitions inside a class are separated by a single blank
    line.
Extra blank lines may be used (sparingly) to separate groups of
    related functions.  Blank lines may be omitted between a bunch of
    related one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical
    sections.
Okay: def a():n    passnnndef b():n    pass
    Okay: def a():n    passnnnasync def b():n    pass
    Okay: def a():n    passnnn# Foon# Barnndef b():n    pass
    Okay: default = 1nfoo = 1
    Okay: classify = 1nfoo = 1
E301: class Foo:n    b = 0n    def bar():n        pass
    E302: def a():n    passnndef b(n):n    pass
    E302: def a():n    passnnasync def b(n):n    pass
    E303: def a():n    passnnnndef b(n):n    pass
    E303: def a():nnnn    pass
    E304: @decoratornndef a():n    pass
    E305: def a():n    passna()
    E306: def a():n    def b():n        passn    def c():n        pass
find_max.py:7:23: E231 missing whitespace after ','
    Each comma, semicolon or colon should be followed by whitespace.
Okay: [a, b]
    Okay: (3,)
    Okay: a[1:4]
    Okay: a[:4]
    Okay: a[1:]
    Okay: a[1:4:2]
    E231: ['a','b']
    E231: foo(bar,baz)
    E231: [{'a':'b'}]
find_max.py:7:27: W292 no newline at end of file
    Trailing blank lines are superfluous.
Okay: spam(1)
    W391: spam(1)n
However the last line should end with a new line (warning W292).

Enter fullscreen mode

Exit fullscreen mode

If we want to exclude specific errors and warning while running pycodestyle we can use the option -ignore and provide the comma separated values of the error codes need to be excluded.

pycodestyle - ignore=E231,E225 find_max.py
find_max.py:6:1: E305 expected 2 blank lines after class or function definition, found 1
find_max.py:7:27: W292 no newline at end of file

Enter fullscreen mode

Exit fullscreen mode

As we have put E231,E225 in the ignore list the PEP 8 violation count reduced to 2 from 8 which is without ignoring these errors.

PEP 8 Error codes

Code can either denote an error or warning in case of error codes the code start with E followed by a 3 digit number for e.g E101 and for warning code it start with E followed by a 3 digit number for e.g W191.

Below is the classification of error code based on series number.
100 series … (E1 and W1) related to indentation.
200 series … (E2 and W2) related to whitespace.
300 series … (E3 and W3) related to blank lines.
400 series … (E4 and W4) related to imports.
500 series … (E5 and W5) related to line length.
600 series … (E6 and W6) related to deprecation.
700 series … (E7) related to statements.
900 series … (E9) related to syntax errors.

You can refer to official document for more detailing on error code link.

Customization of pep8

We can customise the PEP 8 config to meet our requirement as in we might need to ignore certain errors and warning and also we want to alter the max-line-length etc.
Default user configuration file is in ‘~/.config/pycodestyle‘.
You can write the configuration file as below, this is same as option.

[pep8]
ignore = E231,E225
max-line-length = 160

Enter fullscreen mode

Exit fullscreen mode

You can specify the configuration file location by--config=<configration_file_location> .
By storing above configuration file in a certain location in respective projects, you can share it in the projects.
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.

Commonly used PEP 8 guidelines

The PEP 8 guidelines can classified in 7 different categories as

Code Lay-out

  • Use 4 spaces per indentation level.
  • Use spaces not tabs python disallows mixing tabs and spaces for indentation.
  • Limit all lines to a maximum of 79 characters.
  • Should a line break before or after binary operator? In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally.
  • Surround top-level function and class definitions with two blank lines.
  • Code in the core Python distribution should always use UTF-8, and should not have an encoding declaration.

Imports should be grouped in the following order:

  1. Standard library imports.
  2. Related third party imports.
  3. Local application/library specific imports.
    Wildcard imports (from import *) should be avoided.

Naming Conventions

Naming conventions are the most important pillar in maintaining the code consistency and readability there is as such no rule book to define the naming conventions but PEP 8 has recommendation that is good to follow.

  • Never use the characters ‘l’ , ‘O’ , or ‘I’ (uppercase letter eye) as single character variable names. In some fonts, these characters are indistinguishable from the numerals one and zero.
  • Class names should normally use the Cap Words (Camel case) convention.
  • Variables and function names should have all lowercase letters and underscores to separate words.
  • Constant should have all uppercase letters with words separated by underscores
  • Use the suffix «Error» on your exception names (if the exception actually is an error).
  • Use self for the first argument to instance methods or class methods.

String Quotes

  • In Python, single-quoted strings and double-quoted strings are the same. PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.
  • Whitespace in Expression and Statement
  • Avoid trailing whitespace anywhere. Because it’s usually invisible, it can be confusing: e.g. a backslash followed by a space and a newline does not count as a line continuation marker.
  • Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).
  • Use whitespace to communicate order of operations. x = 12*y + 22*z.
  • Avoid excessive whitespace immediately inside of parenthesis, brackets, or braces.

When to use trailing commas

  • Trailing commas are usually optional, except they are mandatory when making a tuple of one element. For clarity, it is recommended to surround the latter in parentheses:
# Correct:
FILES = ('setup.cfg',)
# Wrong:
FILES = 'setup.cfg',

Enter fullscreen mode

Exit fullscreen mode

Programming Recommendations

  • Comparisons to singletons like None should always be done with is or is not, never the equality operators.
  • Use is notoperator rather than not … is for e.g if foo is not None rather than if not foo is None:
  • When implementing ordering operations with rich comparisons, it is best to implement all six operations (eq, ne, lt, le, gt, ge) rather than relying on other code to only exercise a particular comparison.
  • When catching exceptions, mention specific exceptions whenever possible instead of using a bare except.
  • Object type comparisons should always use isinstance() instead of comparing types directly.

Comments

Each line of a block comment starts with a # and a single space.
Use inline comments only if it is unavoidable.
Write docstrings for all public modules, functions, classes, and methods.
Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does.

For more detailing on the PEP 8 guidelines please check out the official documentation PEP 8 Guidelines

Conclusion

Likewise pycodestyle there is flake8 which is also widely used for checking the code style PEP 8 guidelines in python code. It’s always better to have these plugins in the ide and everytime you save or commit it will highlight the violations.
Maintaining the code style guideline helps in better readability and code consistency. Although it’s a good to have but always prefer to have coding guidelines while writing code.

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?

enter image description here

renatodamas's user avatar

renatodamas

14.3k6 gold badges33 silver badges47 bronze badges

asked Nov 1, 2015 at 20:30

Amit Upadhyay's user avatar

Amit UpadhyayAmit Upadhyay

7,0114 gold badges43 silver badges56 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

Leb's user avatar

You need to give two blank lines between meaningful code blocks.

These include (for example):

  • The import block
  • Each function

8bitjunkie's user avatar

8bitjunkie

12.6k9 gold badges54 silver badges70 bronze badges

answered Aug 9, 2017 at 9:59

Balaji Wanole's user avatar

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

Lakshmikant Deshpande's user avatar

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

Balaji Wanole's user avatar

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-inc's user avatar

serv-incserv-inc

34.6k9 gold badges161 silver badges182 bronze badges

Я использую редактор vim в качестве Python IDE. Ниже приведена простая программа python для вычисления квадратного корня числа:

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()

и предупреждения :

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]

можете ли вы сказать, почему эти предупреждения приходят?

enter image description here

5 ответов


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 to complex_num для предотвращения путаницы с builtin complex.

в конце концов, они только предупреждение, их можно игнорировать, если это необходимо.


вот ссылка на документацию:
руководство по стилю PEP8 для Python
Вы должны добавить два пробела между функциями, как показано ниже:

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()

1

автор: Lakshmikant Deshpande


поскольку python строго следует языку .Вы должны дать два пробела после каждого импорта, а также блок кода.


with warnings:-  
import math  
def my():  
    print("hello world")  
my()

Without warnings:-  
import math 


def my():  
    print("hello world")  
my()

здесь, Если вы видите пространство двух строк после инструкции import для второго фрагмента кода, который не будет давать никаких предупреждений.
Опять же, если вы пишете определение двух методов, у вас есть две строки в качестве пространства между вашим блоком кода.


все ответы кажутся правильными. Чтобы избежать этого вручную, вы также можете использовать autopep8 пакета (pip установить autopep8). Результат вызова autopep8 filename.py так же:

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:посмотреть at if __name__ == "__main__":


Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • E37 ошибка на котле baxi
  • E1c447 ошибка бмв
  • E302 0001 ошибка canon 732
  • E36 ошибка сименс

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии