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.
Answer from Harley Holcombe on Stack OverflowWhat 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.
From PEP 8 -- Style Guide for Python Code:
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:
with open('/path/to/some/file/you/want/to/read') as file_1, \ open('/path/to/some/file/being/written', 'w') as file_2: file_2.write(file_1.read())Another such case is with assert statements.
Make sure to indent the continued line appropriately.
The preferred place to break around a binary operator is after the operator, not before it. Some examples:
class Rectangle(Blob): def __init__(self, width, height, color='black', emphasis=None, highlight=0): if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100): raise ValueError("sorry, you lose") if width == 0 and height == 0 and (color == 'red' or emphasis is None): raise ValueError("I don't think so -- values are %s, %s" % (width, height)) Blob.__init__(self, width, height, color, emphasis, highlight)file_2.write(file_1.read())
Update
PEP8 now recommends the opposite convention (for breaking at binary operations) used by mathematicians and their publishers to improve readability.
Donald Knuth's style of breaking before a binary operator aligns operators vertically, thus reducing the eye's workload when determining which items are added and subtracted.
From PEP8: Should a line break before or after a binary operator?:
Donald Knuth explains the traditional rule in his Computers and Typesetting series: "Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations"[3].
Following the tradition from mathematics usually results in more readable code:
# Yes: easy to match operators with operands income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest)In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style is suggested.
[3]: Donald Knuth's The TeXBook, pages 195 and 196
Line continuation issue (new to python)
Pythonic way of printing multi-line strings
How to break line lines of code into multiple lines?
Is there a way to continue a single variable reference in an f-String on a new line of code?
Videos
I have a weird issue; not sure if I'm being incompetent or missing something...
I am running Python 3.8, using the Spyder IDE and Anaconda 1.10. It's a work laptop, so I'm limited on what I can change.
I'm trying to set up a dictionary. I understood that python continues lines that are between parentheses, but but that doesn't seem to be happening.
So this statement works fine:
Fruits_Dict = {1: 'apple', 2: 'pear'}
But when I break it across multiple lines...
Fruits_Dict = {
1: 'apple',
2: 'pear'}
...I get an "unexpected EOF" error at the first '{'.
I'd like to break a longer dictionary across several lines for readability, so this is a problem. Is this an IDE issue or am I missing something basic?
Add a trailing backslash (\)
The trick is โ similar to what you would do in bash, for example โ to add a trailing backslash. For example, if I want to print a 1:
charon:~ werner$ python
>>> print 1
1
>>> print \
... 1
1
>>>
If you write a \, Python will prompt you with ... (continuation lines) to enter code in the next line, so to say.
Side note: This is what automatically happens when you create a function or class definition, i.e. the times when you really need a new line, so there's never a really good use for that, or at least none that I know of. In other words, Python is smart enough to be aware that you need continuation lines when you are entering a new function definition or other similar constructs (e.g. if:). In these automatic cases, do note that you need to enter an empty line using \ to tell Python that you are done.
For everything else, you need to write one line after another. The way an interpreter works is that it, well, interprets every line that you feed it. Not more, not less. It will only "act" when it sees a newline, therefore telling the interpreter to execute what you gave it. The single backslash will prevent the interpreter from ever receiving a newline character (i.e. it won't know that you actually pressed Enter), but it will eventually receive one.
Python's interpreter has advanced capabilities when you use GNU readline, such as Emacs or vi-style keybindings to navigate within a line (e.g. Ctrl-A). Those however work only in the one current line. History is there as well, just try and press โ.
What if I want to run complicated lines over and over?
You probably want to use proper source files if you want to execute more than one line of code at a time.
Or, use Jupyter notebooks, which offer a great, interactive way to create Python code with a built-in interpreter. You can write code as you would in a source code editor, but you can choose which lines are interpreted together. You can then run only parts of the code selectively. The best way is to just try and see if that fits your workflow.
How about using ;\? The semicolon signals the end of a command and the backslash signals that we are continuing on the next line. For example, type python at command line to get into Python interpreter, then
>>> x=0 ;\
... print(x) ;\
... x=4 ;\
... print(x)
should give an output of
0
4
Hello! I'm a novice when it comes to working with python, so I apologize for the extremely basic question. The IDE I am using (pyCharm) is giving me a PEP 8 error (line too long). For a lot of the code I am working on. I understand that this isn't a hard constraint of python. Just something to improve readability, which I would like to do. Currently I have a line (below) that shoots way off the screen, and it is just annoying to make changes to it. I can't figure out how to spread the line of code across multiple lines while still getting python to parse it correctly. I hope this make sense. Can anyone provide any pointers? Thanks for your help!
The current monstrosity:
arcpy.DefineProjection_management(photoKeyFC, "PROJCS['NAD_1983_StatePlane_Georgia_West_FIPS_1002_Feet',GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',2296583.333333333],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-84.16666666666667],PARAMETER['Scale_Factor',0.9999],PARAMETER['Latitude_Of_Origin',30.0],UNIT['Foot_US',0.3048006096012192]]")
More or less what I'd like to see:
"PROJCS['NAD_1983_StatePlane_Georgia_West_FIPS_1002_Feet',GEOGCS['GCS_North_American_1983',DATUM['D_North_
American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.017453292
5199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',2296583.333333333],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-84.16666666666667],PARAMETER['Scale_Factor',0.9999],PARAMETER['Latitude_Of _Origin',30.0],UNIT['Foot_US',0.3048006096012192]]")