PEP8 recommends that Python code indentation be a multiple of four.
Anti-pattern
class User(object):
def __init__(self, name):
self.name = name
Best practice
class User(object):
def __init__(self, name):
self.name = name
Additional links
- https://www.python.org/dev/peps/pep-0008/#indentation
Consider the example:
def foo(): a = True # this is a properly indented comment # isn't it?
And here’s what pep8 reports.
$ pep8 /tmp/test.py
/tmp/test.py:3:15: E111 indentation is not a multiple of four
/tmp/test.py:3:15: E113 unexpected indentation
I personally consider both an error in «judgement»
Shouldn’t we only be getting E113?
@s0undt3ch please review the document PEP 8, specifically the inline comment section. It says «Use inline comments sparingly» and the examples it gives contain the comment to the same line. If your comment will take more than a line it should be placed before the line you’re commenting. There is no error in judgment here.
I’m not sure which error you should be getting (if in fact you should only be receiving one) because the 3rd line in your example is indeed not indented with a multiple of 4 spaces and it is in fact unexpected indentation.
I agree with @sigmavirus24 analysis. 👍
In addition, if you want to circumvent this check, it will be easier in the next release.
I’ve accepted enhancement #274 which is similar to your report: indentation of comments will report E114/E115/E116
instead of E111/E112/E113
.
On 8 de Junho de 2014 8:36:00 WEST, Florent Xicluna notifications@github.com wrote:
I agree with @sigmavirus24 analysis. 👍
In addition, if you want to circumvent this check, it will be easier in
the next release.
I’ve accepted enhancement #274 which is similar to your report:
indentation of comments will reportE114/E115/E116
instead of
E111/E112/E113
.
Reply to this email directly or view it on GitHub:
#300 (comment)
That ticket was created by me 😄
OK, as long as I’m able to ignore these IDs…
Pedro Algarvio @ Phone
Ooh! Maybe we could add a check for inline comments!
@sigmavirus24 Nevermind, I thought I was commenting in a different window 👍
Looks like this was probably resolved with the the referenced release.
This bit of code:
def foo():
print("hello")
violates PEP 0008, which states
Use 4 spaces per indentation level.
But neither the pep8
, pyflakes
, or flake8
commands warn about it.
How can I get one of them to complain about this unpythonic code?
asked Mar 23, 2016 at 16:51
andrewdotnandrewdotn
32.5k9 gold badges100 silver badges129 bronze badges
pylint
would warn about this violation:
$ pylint test.py
No config file found, using default configuration
************* Module test
W: 2, 0: Bad indentation. Found 8 spaces, expected 4 (bad-indentation)
Note that pep8
would warn you only if indentation is not a multiple of four (E111 error code).
answered Mar 23, 2016 at 17:37
alecxealecxe
461k120 gold badges1078 silver badges1186 bronze badges
Preface
As a loyal user of Pycharm, in the usual development process, have you ever paid attention to the highlight reminder on the left side of the editing interface? Did you open a file of the company’s project code in the dead of a night, and you saw that it was overwhelming Yellow strips ,feelScalp tinglingWhat?
The solution is here! ! ! ! !
Click on the villain in the lower left corner (the latest version of this function seems to be changed to the upper left corner and is no longer a villain, I quite like this villain. )
The world is quiet (fog)!
But can you really rest assured? The villain in the hat smiled back.Is it the annihilation of human nature, or the loss of morality! ! ?
Let’s talk about the code today, let’s take you to find out (no, smile)
Closer to home, what kind of code has been written that will make Pycharm reluctant to go and highlight it again and again to remind you?
This starts with the Python language specification PEP8 (plus a bunch of other syntax checks).
Python coding standards
PEP8 It is a general style guide for the Python community. At the beginning, Guido van Rossum, the father of Python, wrote his own coding style. It has gradually evolved to this day, and gradually formed a set of more mature coding standards. Its purpose is to help developers write code that is highly readable and consistent in style. Many open source projects, such as Django 、 OpenStack And so on PEP8 Add your own style suggestions as the basis.
Pycharm has implanted this set of specifications into itself and monitors the developer’s code syntax to encourage developers to write Python code that meets the specifications.
Here, the author lists some of my usual developmentoftenThe specification problems encountered can be (will) can (definitely) enumerated incompletely, so this blog post will be continuously updated, 2333
Named class
Class names should use CamelCase convention
(The name is really a big problem in the programming world)
The prompt says that when we define python classes, we should use camel case naming—— CamelCase , That is, the first letter of the word combination needs to be capitalized. Therefore, when we are naming, the name on the map should be changed to SeriesSquareCompeted
Variable in function should be lowercase
Corresponding to the above item, we recommend using the underline naming method for the naming of variables in functions or methods. The name of the variable on the corresponding figure should be changed to org_id
Shadows name ‘use_a’ from outer scope
If this prompt appears, it means that the same variable name is repeatedly used in different scopes of the current code. The most common situation is the function variable in the method and __main__ The following variables have duplicate names. Under normal circumstances, this will not cause any problems, but in fact this approach will bring potential risks.
Let’s take a look at the following code:
Run this code, what will be printed?
Obviously, the function method smaple The assignment of is obviously invalid. And Pycharm also gave tips very intimate Local variable ‘smaple’ value is not used
Typesetting
The typesetting tips are basically to standardize the code files. Following its specifications will help us write cleaner code.
PEP 8: W292 no newline at end of file
This is easy to say, PEP8 requires us to leave a line at the end of the code, a carriage return and a line to get it done
PEP 8: E303 too many blank lines (2)
This specification defines the interval between each line of code, in simple terms:
- Between functions, between classes are generally empty2 rows
- Generally empty between class methods1 row
- Interval between each line of function/method codeNo more than 1 line
PEP 8: E501 line too long (166 > 150 characters)
PEP8 limits the length of a single line of code. In fact, this length can be set in Pycharm
PEP 8: E111 indentation is not a multiple of four
This belongs to the basic specification of python, and python requires our code to be indented4 spacesorA multiple of 4, Run this code on the diagram, and there will be no error (but if the indentation of the code behind is inconsistent with the previous one, a syntax error will occur). If there is an irregular indentation in the project, it should be fixed in time.
PEP 8: E225 missing whitespace around operator
Aha, another format problem, in short, we need to reserve a space on each side of the operator.
But when passing keyword parameters, you don’t need to do this, such as
At this moment = Add spaces on both sides will report PEP 8: E251 unexpected spaces around keyword / parameter equals Warning
Encoding
This list creation could be rewritten as a list literal
Here Pycharm reminds us that we should relocate a as an instance of a list, as the author did before
In fact, we can change
We directly fill in the values when defining lists and dictionaries. This is also a more common practice, and it has less code and better performance than the former.
Of course, if you need to use the first way of writing for readability or other reasons in your project, just ignore the Pycharm prompt.
Remove redundant parentheses
In python3, the defined class is inherited by default object You can show inheritance in brackets object , But if we don’t need to inherit from other classes, let’s drop the extra brackets 🙂
Unused import statement ‘import xxx’
I imported this library, but I don’t need it. I’ll delete it for you. It’s okay.
Cannot find reference ‘xxx’ in __init__.py
Literally, no reference was found. This is a bug in Pycharm. Pycharm hopes that all modules are included in __init__.py. __all__ = [] Among them, actually not doing this, it will not affect the call. (Of course, I can’t find it, so Pycharm just gave a verbal warning
Instance attribute a defined outside __init__
This warning indicates that the code violates the SRP (Single Pesponsibility Principle, SRP) principle. We can understand that the initialization of member variables should be done in a separate method ( def __init__() ), other methods should not be initialized.
Despite the specification, we can still see that many projects will __init__ In addition to initializing member variables, some people think that these variables are only used by a certain method and should not be placed __init__ To do the initialization, this is a matter of opinion.
Write at the end
More important than general specifications
Most of the time, you have to tolerate a coding style that is different from the general specification, because compared to the general specification,More important is the style consistency of the project itself. Stylistic consistency in a module or function is the most important.
In order to maintain a strong consistency with the general specification, it is not advisable to modify the original code extensively, and this is a very frustrating behavior.Because you can’t change itAt this time, the recommendations of the coding standards are not applicable.
At this time, we can ignore some specifications through Pycharm’s ignore function (pretend not to see. ), the specific settings are
Preference —> Editor —> Inspections
We can alsoDirectly where the warning appearsClick the prompt to ignore it.
There are a few good reasons to ignore certain rules:
- When following this guide, the readability of the code becomes poor, even people who follow the PEP specification feel that the readability is poor.
- Be consistent with the surrounding code (and possibly for historical reasons), although this is also an opportunity to clean up other people’s confusion (real Xtreme Programming style).
- The problematic code appeared before the coding standards were discovered, and there was no good reason to modify them.
- When the code needs to be compatible with an older version of Python that does not support the coding standard recommendations.
Another purpose
Another purpose of this article is to tell readers that although Pycharm’s code specifications and grammar checks are not applicable to all scenarios, when they appear, we still need to maintain aAwe, Fully understand the real reason behind the warning, this will help us to establish a code specification suitable for our project.
indentation is not a multiple of four on comments #300
The text was updated successfully, but these errors were encountered:
@s0undt3ch please review the document PEP 8, specifically the inline comment section. It says «Use inline comments sparingly» and the examples it gives contain the comment to the same line. If your comment will take more than a line it should be placed before the line you’re commenting. There is no error in judgment here.
I’m not sure which error you should be getting (if in fact you should only be receiving one) because the 3rd line in your example is indeed not indented with a multiple of 4 spaces and it is in fact unexpected indentation.
I agree with @sigmavirus24 analysis. ��
In addition, if you want to circumvent this check, it will be easier in the next release.
I’ve accepted enhancement #274 which is similar to your report: indentation of comments will report E114/E115/E116 instead of E111/E112/E113 .
On 8 de Junho de 2014 8:36:00 WEST, Florent Xicluna notifications@github.com wrote:
I agree with @sigmavirus24 analysis. ��
In addition, if you want to circumvent this check, it will be easier in
the next release.
I’ve accepted enhancement #274 which is similar to your report:
indentation of comments will report E114/E115/E116 instead of
E111/E112/E113 .Reply to this email directly or view it on GitHub:
#300 (comment)
That ticket was created by me ��
OK, as long as I’m able to ignore these IDs.
Pedro Algarvio @ Phone
Ooh! Maybe we could add a check for inline comments!
@sigmavirus24 Nevermind, I thought I was commenting in a different window ��
Looks like this was probably resolved with the the referenced release.
Footer
© 2023 GitHub, Inc.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
The text was updated successfully, but these errors were encountered:
sigmavirus24 commented Jun 7, 2014
@s0undt3ch please review the document PEP 8, specifically the inline comment section. It says «Use inline comments sparingly» and the examples it gives contain the comment to the same line. If your comment will take more than a line it should be placed before the line you’re commenting. There is no error in judgment here.
I’m not sure which error you should be getting (if in fact you should only be receiving one) because the 3rd line in your example is indeed not indented with a multiple of 4 spaces and it is in fact unexpected indentation.
florentx commented Jun 8, 2014
I agree with @sigmavirus24 analysis.
In addition, if you want to circumvent this check, it will be easier in the next release.
I’ve accepted enhancement #274 which is similar to your report: indentation of comments will report E114/E115/E116 instead of E111/E112/E113 .
s0undt3ch commented Jun 8, 2014
On 8 de Junho de 2014 8:36:00 WEST, Florent Xicluna notifications@github.com wrote:
I agree with @sigmavirus24 analysis.
In addition, if you want to circumvent this check, it will be easier in
the next release.
I’ve accepted enhancement #274 which is similar to your report:
indentation of comments will report E114/E115/E116 instead of
E111/E112/E113 .Reply to this email directly or view it on GitHub:
#300 (comment)
That ticket was created by me
OK, as long as I’m able to ignore these IDs.
Pedro Algarvio @ Phone
ghost commented Jun 11, 2014
Ooh! Maybe we could add a check for inline comments!
sigmavirus24 commented Jun 11, 2014
ghost commented Jun 11, 2014
@sigmavirus24 Nevermind, I thought I was commenting in a different window
IanLee1521 commented Feb 25, 2016
Looks like this was probably resolved with the the referenced release.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Python: надежная защита от потери запятой в вертикальном списке строк
Списки строк в программах встречаются часто. Для удобства чтения их не менее часто форматируют вертикально, по одной строке. И есть в такой конструкции уязвимость — если при изменении списка потерять запятую между элементами, то многие языки просто склеют строки слева и справа от пропущенной запятой — в результате получится валидный с точки зрения языка список, в котором на один элемент меньше чем ожидается и один элемент имеет некорректное значение. Есть много способов профилактики этой проблемы, но недавно на stackoverflow мне показали настолько простой и надежный способ, что я просто не могу им не поделиться.
pep8 warn about 8-space indent
Use 4 spaces per indentation level.
But neither the pep8 , pyflakes , or flake8 commands warn about it.
How can I get one of them to complain about this unpythonic code?
1 Answer 1
pylint would warn about this violation:
Note that pep8 would warn you only if indentation is not a multiple of four (E111 error code).
-
The Overflow Blog
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.11.43300
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.