Python, PEP-8, E122 continuation line missing indentation or outdented - python

I get this error but however I choose to indent it, I still get it, do you know why?
if len(argmaxcomp) == 1:
print "The complex with the greatest mean abundance is: {0}"\
.format(argmaxcomp[0])

Generally pep8 suggests you prefer parenthesis over continuation lines.
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
That is:
if len(argmaxcomp) == 1:
print("The complex with the greatest mean abundance is: {0}"
.format(argmaxcomp[0]))
Another option, is to use python 3's print:
from __future__ import print_function
if len(argmaxcomp) == 1:
print("The complex with the greatest mean abundance is:", argmaxcomp[0])
Note: print_function may break/require updating the rest of the code... anywhere you've used print.

The problem in this case is that there is no indentation at all
and obviously the error occurs in the last line.
In case parentheses are not an option just add indentation as below:
if len(argmaxcomp) == 1:
print "The complex with the greatest mean abundance is: {0}" \
.format(argmaxcomp[0])
Any amount of spaces works but I don't know what is preferred.

I did't get the above error, But i have tried below types,
Please post with error, so that we can check
In [6]: argmaxcomp = [100]
In [7]: if len(argmaxcomp) == 1:
...: print 'val: {0}'\
...: .format(argmaxcomp[0])
...:
val: 100
In [8]: if len(argmaxcomp) == 1:
...: print 'val: {0}'.format(argmaxcomp[0])
...:
val: 100
In [9]: if len(argmaxcomp) == 1:
...: print 'val: {0}'.format(
...: argmaxcomp[0])
...:
val: 100

There is one section in the PEP8 that reads:
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
Backslashes may still be appropriate at times. For example, long, multiple with -statements cannot use implicit continuation, so backslashes are acceptable
This means (even though this has nothing to do with PEP8-E122) that you should wrap it in paranthesis instead of using the backslash and then the implicit line continuation (indentation) is the opening bracket:
if len(argmaxcomp) == 1:
print("The complex with the greatest mean abundance is: {0}"
.format(argmaxcomp[0]))
# ^--------- The bracket opens here
There are only 2 exceptions mentioned where the backslash is acceptable because paranthesis are impossible (because they have another meaning in these contexts):
multi-with
asserts
However if you really want that backslash (only possible with python2) it should have the same indentation as the first expression:
if len(argmaxcomp) == 1:
print "The complex with the greatest mean abundance is: {0}" \
.format(argmaxcomp[0])
# ^--------- The first expression starts here

Just had a similar issue and resolved it. I think the problem with the OP's code is that there may be whitespace between the continuation lines. There should be nothing there but the \n.

Related

PEP 8: E128 sometimes requires spaces and sometimes does not

This post's answer suggests PEP 8: E128 requires spaces on the lines following the first one when they're all wrapped inside parentheses. However, with an if statement this doesn't seem to be the case. You can see that the first three lines do not have a warning and the following do because they do have a space:
Am I missing something? I am using Pycharm Community edition if that helps.
Code used:
def main(user_input):
if (";" not in user_input
and "DROP " not in user_input
and "SELECT " not in user_input
and "FROM " not in user_input
and "DELETE " not in user_input
and '"' not in user_input
and ";" not in user_input
and "=" not in user_input
and ">" not in user_input
and "<" not in user_input):
pass
else:
exit()
EDIT: as there is a bit of confusion, this should be the correct indentation: https://i.imgur.com/FqsJjkc.png and this is the one Pycharm thinks is the correct one https://i.imgur.com/6DmejGi.png. Unless I'm mistaken (could be the case!).
PEP-8 notes that if ( provides a natural 4-space indentation which allows a continuation to begin after the parenthesis:
if (";" not in user_input
and "DROP " not in user_input
...
Your checker apparently does not care if you write
if (";" not in user_input
and "DROP " not in user_input
...
instead, but, if you do use that indentation, you have to continue to use the same indentation. Your FROM line is the first line to deviate from that indentation.
This is common enough that the PEP even provides an anchor to link to this paragraph:
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.)
The line with "FROM" is indented 1 space more than the line before. That's what's triggering the warning.

Why can expressions be carried across multiple lines in function calls but not assignments?

I just realized that it's possible to stretch a statement across multiple lines when it's passed as a parameter to a function:
print(1 ==
1)
However, doing the same thing during a variable assignment raises a SyntaxError:
x = 1 ==
1
Why does the first example work but the second one yields a SyntaxError?
Python recognizes open brackets, braces, and parentheses as indicating that the statement is not finished. Thus, the function call "naturally" is allowed to span lines.
This parser convention doesn't apply to expressions in which there is not a required balanced enclosing punctuation.
Note that strings also cannot cross line boundaries.
One other way to do this is with the continuation character (\) as in...
x = 1 == \
1

Learning Python else syntax error

Hi I am learning python by doing the practice problems for Open course at MIT 6.00 Intro to Computer Science.
I am Trying to do practice problem 1 part 2 create a recursive function to count the instance of key in target. My code so far...
from string import *
def countSubStringMatchRecursive (target, key,x,s):
if (find(target,key)==find(target,key,s)) and (find(target,key)==find(target,key,(find(target,key)))):#if first and last
return (1)
elif (find(target,key)==find(target,key,s))and (find(target,key)!=find(target,key,(find(target,key)))):#if first but not last
x=1
s= find(target,key)
return (countSubStringMatchRecursive(target,key,s,x)
elif (find(target,key,s))==-1 and (find(target,key)!=find(target,key,s)):#if last but not first
return (x+1)
elif:(find(target,key,s))!=-1 and (find(target,key)!=find(target,key,s)):#if not last and not first
x=x+1
s= find(target,key,s)
return (countSubStringMatchRecursive(target,key,s,x)
I getting a syntax error at line 8. I would just like to know what I did wrong there. Dont worry about the other mistakes I should be able to get those sorted out. I just Stuck on this. Thanks.
You're missing a closing parenthesis in line 8 and in the last line. Actually, the corresponding opening parenthesis is unnecessary, you might as well rewrite those line as this:
return countSubStringMatchRecursive(target,key,s,x)
Also, as pointed by #rodion in the comments, the last elif has a misplaced :, remove the one right before the opening parenthesis.
And talking about parenthesis: in Python you don't have to place the conditions of an if ... elif ... else statement inside parenthesis, you should drop them.
You have an unmatched paren on line 8. Add another close paren at the end
return (countSubStringMatchRecursive(target,key,s,x))
Same thing applies to your final return statement.
You have a mismatched parenthesis. Remove the ( near the beginning of the line or add a ) to the end.
return (countSubStringMatchRecursive(target,key,s,x)
You're missing a closing ). But you didn't need the opening one either; the syntax of a return statement is return <expr>, so anything that's a valid expression can directly follow return. Anything that's a valid expression is still a valid expression meaning exactly the same thing if you surround it with parentheses, but mostly that just adds noise when it's not needed.
There are several problems:
You are missing a closing paren on line 8
the body of your function needs to be indented. (update: has been fixed)
Also, your last elif has a : right after it, that needs to be
deleted. I.e.,
elif: expression:
should be
elif expression:
Your last statement is also missing a closing paren
return (countSubStringMatchRecursive(target,key,s,x)
should be
return (countSubStringMatchRecursive(target,key,s,x))
Finally #drewk's recommendation about taking a look at the PEP 8 is a good one. I periodically go back and review it myself.
Also, you have a number of unnecessary ()s .. they don't do any harm, but they are not needed and may reduce the readability of your code.

Why not python implicit line continuation on period?

Is there any reason Python does not allow implicit line continuations after (or before) periods? That is
data.where(lambda d: e.name == 'Obama').
count()
data.where(lambda d: e.name == 'Obama')
.count()
Does this conflict with some feature of Python? With the rise of method chaining APIs this seems like a nice feature.
Both of those situations can lead to valid, complete constructs, so continuing on them would complicate the parser.
print 3.
1415926
print 'Hello, world'
.lower()
Python allow line continuations within parentheticals (), so you might try:
(data.where(lambda d: e.name == 'Obama').
count())
I know that's not answering your question ("why?"), but maybe it's helpful.
Use a '\' at the end. (looks ugly though)
data.where(lambda d: e.name == 'Obama').\
count()
Not sure about after periods, but in your example the newline before a period leads to the first line being a valid statement on its own. Then Python would have to look ahead to the second line to know whether the first line was a statement or not.
One of the goals when defining the language syntax was to be able to parse it without having ambiguities that require looking ahead like that.
It'd get annoying in the interactive interpreter if you had to press enter twice after every single line just so Python knew you'd finished your statement and weren't going to put a .foo() after it.
In the cases where a period could be leading in to a method call, it will always(?) be a syntax error for it to just occur at the end of a line by itself. So it would be unambiguous to read it as starting a continuation.
However, Python generally speaking doesn't continue a line just because there's an incomplete binary operator there. For instance, the following is not valid:
2 +
4
In the second example, the first line is valid by itself and it would be really inconsistent for Python to look for a following line "just in case" there is one.
I would just break after the opening paren of the method call.
{Because python uses line breaks to end statements, not depending on braces or semi-colins;}

How to detect if a file path is wrapped in " .. " with Python?

I read the ini file to open a file in python.
The thing is that the file info is sometimes inside the "..", but sometimes it's not.
For example,
fileA = "/a/b/c.txt"
fileB = /a/b/d.txt
Is there easy way to detect if a string is wrapped in "..", and return the string inside the quotation?
The simple detection would involve checking s[:1] == s[-1:] == '"' (carefully phrasing it with slicing rather than indexing to avoid exceptions if s is an empty string), and the conditional removal of exactly one quote from each end if one is present at both ends is
if s[:1] == s[-1:] == '"':
s = s[1:-1]
Alternatively, the approach in #Magnus's answer, as he says, removes all leading and trailing quote, and does so unconditionally; so, for example, if s starts with three quotes but doesn't end with any (and in all sort of other weird cases, outside of your specs as stated), the snippet in my answer won't alter s, #Magnus's will strip the three leading quotes.
"You pay your money and you take your choice"... if you don't care one way or another (i.e. you're sure that the situation where the two answers differ is "totally and utterly impossible"...), then I think #Magnus's higher-abstraction-level approach is neater (but, it's a matter of style -- both his approach and mine are correct Python solutions when you don't care about unmatched or unbalanced quotes;-).
To remove all leading and trailing quotes:
fileA = fileA.strip('"')

Categories