Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment with line continuation - Python

What is the preferred style for assigning values to variables when the variables are nested several levels deep, have fairly long names, and are being assigned fairly long values/expressions.

For example:

if this:
    if that:
        if here:
            if there:
                 big_variable['big_key']['big_value'] = another_big_variable_that_pushes_line_over_79_characters
                 other_thing = something

The character-limit breaches are only in the single digits, but I want to clean up my code so that it follows PEP 8 as faithfully as possible. I've done the following, but I am still fairly new to python, and I'm not sure if it's the sort of thing that would make an experienced python programmer cringe:

if this:
    if that:
        if here:
            if there:
                big_variable['big_key']['big_value'] = \
                    another_big_variable_that_pushes_line_over_79_characters
                other_thing = something

I get the impression that the line continuation character is somewhat taboo; but I can't really think of a cleaner solution than the one I have if I'm working with these big dictionaries and I can't make a clean break in the middle of the variable name.

like image 560
SheffDoinWork Avatar asked Mar 26 '14 22:03

SheffDoinWork


People also ask

How do you do line continuation in Python?

Use a backslash ( \ ) as a line continuation character In Python, a backslash ( \ ) is a line continuation character. If a backslash is placed at the end of a line, it is considered that the line is continued on the next line.

How can long assignments be carried over to another line?

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."

What is in line assignment in Python?

The assignment operator, denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”. After executing this line, this number will be stored into this variable.


1 Answers

I don't think there is any problem with line continuation in Python. But sometimes I prefer this:

big_variable['big_key']['big_value'] =(
    another_big_variable_that_pushes_line_over_79_characters
)

It is useful in long expressions, too.

like image 55
swstephe Avatar answered Oct 19 '22 23:10

swstephe