For lines that are too long (e.g. > 79 characters), you can use parentheses to group your conditions:
if (first_index < 0
or second_index > self._number_of_plates - 1
or condition2
and candition3):
raise ValueError
Note that any boolean conditions (or
, and
) should go at the start of the line before the condition.
In your case, there is a special rule because of the if (...)
construct:
When the conditional part of an if-statement is long enough to require
that it be written across multiple lines, it’s worth noting that the
combination of a two character keyword (i.e. if), plus a single space,
plus an opening parenthesis creates a natural 4-space indent for the
subsequent lines of the multiline conditional. This can produce a
visual conflict with the indented suite of code nested inside the
if-statement, which would also naturally be indented to 4 spaces. This
PEP takes no explicit position on how (or whether) to further visually
distinguish such conditional lines from the nested suite inside the
if-statement. Acceptable options in this situation include, but are
not limited to:
# No extra indentation.
if (this_is_one_thing and
that_is_another_thing):
do_something()
# Add a comment, which will provide some distinction in editors
# supporting syntax highlighting.
if (this_is_one_thing and
that_is_another_thing):
# Since both conditions are true, we can frobnicate.
do_something()
# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
and that_is_another_thing):
do_something()
(Also see the discussion of whether to break before or after binary
operators below.)
Source: PEP 8 Style Guide
elpy
(or rather flake8
I suppose) complains about a line over-indented on the line 52 (see below image)
I tried to change this line’s begin but no change.
I always use TAB to have the correct indentation (and this position is where TAB leads).
Here’s my elpy
config:
Emacs.............: 26.3
Elpy..............: 1.33.0
Virtualenv........: None
Interactive Python: python3 3.8.3 (/usr/bin/python3)
RPC virtualenv....: rpc-venv (/home/david/.emacs.d/elpy/rpc-venv)
Python...........: /usr/bin/python3 3.8.3 (/usr/bin/python3)
Jedi.............: 0.17.0
Rope.............: 0.17.0
Autopep8.........: 1.5.2
Yapf.............: 0.30.0
Black............: 19.10b0
Syntax checker....: flake8 (/home/david/.local/bin/flake8)
asked May 22, 2020 at 13:49
You should create in your home folder a .flake8rc
file, and add some content to ignore that error — documented here and below is a small template:
[flake8]
# it's not a bug that we aren't using all of hacking
ignore =
# F812: list comprehension redefines ...
F812,
# H101: Use TODO(NAME)
H101,
# H202: assertRaises Exception too broad
H202,
# E127: continuation line over-indented for visual indent
E127
The full error code listing is here
answered May 24, 2020 at 6:53
IanIan
1,2469 silver badges10 bronze badges
1
how do you understand the E127:continuation line over-indented for visual indent in the PEP8 that pops up when editing with sublime?
code style problem.
python.org/dev/peps/pep-0008/» rel=» nofollow noreferrer «> PEP8 points out:
Continuation lines should align wrapped elements either vertically using Python’s implicit line joining inside parentheses, brackets and braces, or using a hanging indent [7]. When using a hanging indent the following should be considered; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line.
that is to say, when there are a lot of parameters in parentheses, in order to satisfy that each line contains no more than 79 characters, you need to wrap the parameters. At this time, the parameters of the new line should be aligned with the parentheses of the previous line.
or all the parameters should be wrapped. At this time, the first line cannot have parameters, that is, the last character of the first line must be (
, which needs to be indented after the line break. Similar rules are also used on []
, {}
.
example:
-sharp Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
var_three, var_four)
-sharp Hanging indents should add a level.
foo = long_function_name(
var_one, var_two,
var_three, var_four)
-
Use python to convert dict1 to dict2, in the example. I tried for a long time but couldn’t find a solution.
dict1 = {
«system.cpu.user.pct»: {
«value»: 12.83
},
«system.load.1»: {
«value»: 0.33
}
}
dict2 = {
«system»: {
«… -
On the problem of regular matching
description: a regular match is given to the content of an input box, and the matching content is the product activation code. looks like this: «0C31-0B81-BB32-3094-0C31-0B81-BB32-3094 »
Code:
$( -sharplicenseCode ).keyup(function () {
le… -
Python two-dimensional list, each sublist (with different number of elements) takes one element to combine, listing all possible situations
for example, the known two-dimensional list [[aformab], [dpene], [f]] requires an element from each sublist to be added and lists all the combinations. The output of this question is adf,aef,bdf,bef,cdf,cef. There are many such lists, and the number of s…
-
What should I do if I want to randomly pick out five different colors and numbers of playing cards?
I want the program to randomly issue five cards with different colors and numbers (it doesn t matter if there are occasional cards with the same number), but I find that five cards are always the same.
import random suites = [ «Hearts «, «Diamonds … -
How to solve the problem of (Python) SyntaxError: Non-ASCII character once and for all
this problem works fine after I add code to the first line, but do I have to pay attention to this every time? Python novice asks
… -
Forbidden (403) CSRF verification failed. Request aborted.
{% csrf_token%}, is added to the form form of html in the template.
MIDDLEWARE = [
django.middleware.security.SecurityMiddleware ,
django.contrib.sessions.middleware.SessionMiddleware ,
django.middleware.common.CommonMiddleware ,
… -
How to use python to bulk distribute native ssh public keys?
when we use the ansible tool, the default is to use ssh for remote control. you need to generate key pairs in a way similar to ssh-keygen-t rsa , and then use the ssh-copy-id command to distribute the public key file to a remote host and enter the pas…
-
Python has been unsuccessful in replacing the content in front of the vertical bar symbol in the title.
python replaces the content in front of the vertical bar symbol in the title, but it has been unsuccessful, for example: Chen Ning column (Chinese football fight to correct the name of Wales Uruguay for the championship, replace Chen Ning column for oth…
-
It is invalid to change the data-src of the video to src by crawling Wechat’s official account article.
the article on Wechat s official account crawled through python at the backend found that the video in the article could not be played, and the video was nested in iframe, as shown in
<iframe class=»video_iframe» data-vidtype=»2″… -
Python3 creates a new BeautifulSoup object in a child thread for a specific web page, but there is no exception in the encoding error, main thread.
as in the title, write a simple function test to generate a soup object from the URL using Python requests and BeautifulSoup, (see the example below). If you call this function directly in the main thread, everything will be fine, but if you call this f…
-
Session problem of Django
blog s article like function, like once + 1, use session to record the current user problem point is: if you like article 1, article 2 will indicate that it has been supported. The reason is to judge that session how to realize that articles cannot b…
-
How pandas groups and merges by alias alias
1. Condition: according to whether the alias in the two lines intersect, and if so, Then merge separated by-sharp sign, where: alias 2 in alias separated by-sharp sign, data name alias 0 potato potato-sharp egg-sharp potato-sharp potato 1 potato p…
-
Centos7shell postgres login failed
Baidu said that there is a problem with the verification method in the file var lib pgsql 9.5 data pg_hba.conf, but the reason for changing the verification method is to use the command psql-U postgres-d mydjango-p 5432-h 127.0.0.1 to log in directl…
-
How to set callback for web direct pass of Tencent Cloud COS?
I ve been looking for it for a long time, but I can t find it.
1. After the direct upload of web is completed, the server cannot know whether the file was uploaded successfully, who uploaded it, and the information of the file
2. Using web to dire… -
Pandas’s dataframe condition Filter performance Optimization?
currently I have a piece of code that spends most of its time on the above two sentences of data filtering in dataframe. temp_df = df [df [ «data_date «] .isin (date_list)] temp = temp_df [rule [2]] [temp_df [ «data_date «] = = d]
at present, it tak… -
In pycharm, how does the chart displayed by matplotlib.pyplot.show () pop up when output to sciview,?
< H2 > 1. Question: < H2 >
like the title, how does the chart displayed by matplotlib.pyplot.show () in pycharm pop up to sciview,?
< H2 > 2. Code: < H2 >
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib impo… -
There is a problem with pip when switching the version of python.
I need to install both python 2.6 and python 3.6 on my machine. Based on my query, I found that I could use pyenv to do this
things, but according to an article I read, python 2 series didn t come with package management tools until python 2.7.9. The… -
The thread pool of futuers in python3 is very efficient, but sometimes I wonder if it can be realized if it is a little slower, such as an interval of 0.5 between tasks.
The question is written on the title, is there any way to be spaced by BAN, when it is applied too fast in crawlers? Or is it that there is no interval in this kind of concurrency? …
-
Selenium uses Chrome to fill in the form.
Open a chrome browser using selenium, and open a Baidu web page. Using the send_keys () method to fill in the content in the search box, there are the following problems
-sharpcoding:utf-8
from selenium import webdriver
from selenium.webdriver.chrom… -
Python installation error, update machine required
the newly installed win7 system, Ann python is, the installation package setup comes out of this, which I have encountered before. I forgot how to solve it. …
Просто открыл файл с помощью Sublime Text (с помощью Sublime Linter) и заметил ошибку форматирования PEP8, которую я никогда раньше не видел. Вот текст:
urlpatterns = patterns('',
url(r'^$', listing, name='investment-listing'),
)
Он помечает второй аргумент, строку, которая начинается url(...)
Я собирался отключить эту проверку в ST2, но я хотел бы знать, что я делаю неправильно, прежде чем я проигнорирую это. Вы никогда не знаете, если это кажется важным, я мог бы даже изменить свои пути
Ответы:
PEP-8 рекомендует использовать отступы для открывающих скобок, если вы помещаете что-либо в первую строку, поэтому он должен иметь отступ для открывающей скобки:
urlpatterns = patterns('',
url(r'^$', listing, name='investment-listing'))
или не ставить какие-либо аргументы в стартовой строке, а затем делать отступы до единого уровня:
urlpatterns = patterns(
'',
url(r'^$', listing, name='investment-listing'),
)
urlpatterns = patterns(
'', url(r'^$', listing, name='investment-listing'))
Я предлагаю прочитать PEP-8 — вы можете пролистать многие из них, и это довольно легко понять, в отличие от некоторых более технических PEP.
Это также относится к таким утверждениям (автоматически отформатированным PyCharm):
return combine_sample_generators(sample_generators['train']),
combine_sample_generators(sample_generators['dev']),
combine_sample_generators(sample_generators['test'])
Который даст такое же стиль-предупреждение. Чтобы избавиться от него, мне пришлось переписать его так:
return
combine_sample_generators(sample_generators['train']),
combine_sample_generators(sample_generators['dev']),
combine_sample_generators(sample_generators['test'])