This case is covered in PEP-8. In summary, to fix this you need to ensure that when you indent lines that are inside parentheses that you align the next line with the character that is after the opening parenthesis. For example, you should do this when you continue code in parentheses.
foo(a, b, c,
d, e)
You are currently doing it like this.
foo(a, b, c,
d, e)
To fix your indentation you should do it like this.
command = 'ffmpeg -i downloaded.mp4 -codec:v libx264 -codec:a
aac -map 0 -f ssegment -segment_format mpegts
-segment_list %s/%skbps.m3u8 -segment_time 10
%s/%skbps_%%03d.ts' % (path, options['video_bitrate'],
path, options['video_bitrate'])
From Stephen Rauch’s answer you may have noticed that there is a little more to this as well. instead of using slashes to do line continuation you may surround the entire line in parenthesis and then break the lines into strings, python automatically joins adjacent string literals. For example if you had a string and you did this before.
greeting = 'Hello,
World!'
You should do this instead.
greet = ('Hello, '
'World!')
This way is a lot more readable and a lot nicer for you to work with. Also do note, there is another PEP-8 approved way to continue parenthesis lines. Instead of doing.
foo(a, b, c,
d, e)
You may also do this.
foo(
a, b, c,
d, e)
To do this you must leave the first line blank after the opening parentheses and then you MUST indent in from the current block to start your continuation. I hope this edit furthers your understanding more. If you want to learn more about python style, then just give the PEP guides a quick read through (they are the standard for python code).
I have this statement as a few lines:
return render_to_response('foo/page.html',
{
'situations': situations,
'active': active_req,
},
context_instance=RequestContext(request))
As it stands, using the PEP8 script, it gives me an “E128: continuation line under-indented for visual indent” error on the second line.
I’ve tried a whole bunch of different ways of formatting, and the only way I can get PEP8 to stop complaining is:
return render_to_response('foo/page.html', {
'situations': situations,
'active': active_req,
},
context_instance=RequestContext(request))
But this looks like garbage.
Suggestions? E124, E126, and E128 seem to be a huge pain!
I don’t mind solutions which have the {
on the first line (or on it’s own), but I hope there’s a solution where the },
and context_instance...
are at the same indentation level.
Просто открыл файл с помощью 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'])
У меня есть скрипт на python, и flake8 обнаружил некоторые ошибки для моего скрипта:
231 flake8
E128 continuation line under-indented for visual indent
232 flake8
E128 continuation line under-indented for visual indent
234 flake8
E128 continuation line under-indented for visual indent
235 flake8
E122 continuation line missing indentation or outdented
236 flake8
E122 continuation line missing indentation or outdented
Вот мой код:
t = someFunction (
data, title=so, Rows=1,
Widths=[1.2 * inch, 0.3 * inch,
0.1 * inch, 0.3 * inch, 2 * inch, 3 * inch,
5.00 * inch],
style=[("sth1", (0, 0), (-1, -1), "CENTER"),
("sth2", (0, 0), (-1, -1), "CENTER"),
('sth3', (0, 0), (-1, -1), 0.5, colors.grey),
('sth4', (0, 0), (-1, 0), colors.orange),
('sth5', (0, 1), (0, -1), colors.orange),
])
Я пробовал разные перестановки, и ни одна из них не работала. Может кто-нибудь сказать мне, как отформатировать эту функцию?
1 ответ
Лучший ответ
E122: Когда вы используете строку продолжения для нескольких аргументов функции, они должны использовать обычный отступ в 4 столбца.
E128: Когда вы распределяете элементы списка, dict, tuple и т. Д. По нескольким строкам, вам нужно выровнять их слева.
t = someFunction (
Widths=[1.2 * inch, 0.3 * inch,
0.1 * inch, 0.3 * inch, 2 * inch, 3 * inch,
5.00 * inch],
style=[("sth1", (0, 0), (-1, -1), "CENTER"),
("sth2", (0, 0), (-1, -1), "CENTER"),
('sth3', (0, 0), (-1, -1), 0.5, colors.grey),
('sth4', (0, 0), (-1, 0), colors.orange),
('sth5', (0, 1), (0, -1), colors.orange)]
)
Вот документация:
В строке продолжения отсутствует отступ или отступ (E122)
Строка продолжения с отступом для визуального отступа (E128)
0
Barmar
12 Сен 2019 в 23:43
The *args
and **kwargs
is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation.
The *args
will give you all function parameters as a tuple:
def foo(*args):
for a in args:
print(a)
foo(1)
# 1
foo(1,2,3)
# 1
# 2
# 3
The **kwargs
will give you all
keyword arguments except for those corresponding to a formal parameter as a dictionary.
def bar(**kwargs):
for a in kwargs:
print(a, kwargs[a])
bar(name='one', age=27)
# name one
# age 27
Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:
def foo(kind, *args, **kwargs):
pass
It is also possible to use this the other way around:
def foo(a, b, c):
print(a, b, c)
obj = {'b':10, 'c':'lee'}
foo(100,**obj)
# 100 10 lee
Another usage of the *l
idiom is to unpack argument lists when calling a function.
def foo(bar, lee):
print(bar, lee)
l = [1,2]
foo(*l)
# 1 2
In Python 3 it is possible to use *l
on the left side of an assignment (Extended Iterable Unpacking), though it gives a list instead of a tuple in this context:
first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]
Also Python 3 adds new semantic (refer PEP 3102):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass
Such function accepts only 3 positional arguments, and everything after *
can only be passed as keyword arguments.
Note:
- A Python
dict
, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order. - “The order of elements in
**kwargs
now corresponds to the order in which keyword arguments were passed to the function.” – What’s New In Python 3.6 - In fact, all dicts in CPython 3.6 will remember insertion order as an implementation detail, this becomes standard in Python 3.7.
What is the line? You can just have arguments on the next line without any problems:
a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5,
blahblah6, blahblah7)
Otherwise you can do something like this:
if (a == True and
b == False):
or with explicit line break:
if a == True and
b == False:
Check the style guide for more information.
Using parentheses, your example can be written over multiple lines:
a = ('1' + '2' + '3' +
'4' + '5')
The same effect can be obtained using explicit line break:
a = '1' + '2' + '3' +
'4' + '5'
Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go.