Search code examples
pythonpython-2.7python-3.xpep8pep

Python PEP8 conventions


I'm a Python beginner, I read pep standards which must follow while programming in python http://legacy.python.org/dev/peps/pep-0008

Now I have a doubt. As they have mentioned that you should not put spaces around the equal sign while using keyword argument or a default parameter value in functions or Dict.

For example

YES

def myfunc(key1=val1, key2=val2, key3=val3)

NO

def myfunc(key1 = val1, key2 = val2, key3 = val3)

Thats fine but what if I break down these in multiple lines. something like this(when we have many parameters or long name)

def myfunc(key1=val1, key2=val2, key3=val3)

In this case, I think, we should put space around the equal sign. am I correct. because these all are about readability but I'm just curious if there is standard for this too. Looking for best practices.

Same thing for Dict.

new_dict= Dict(
       key1=val1, 
       key2=val2, 
       key3=val3
)

And should I put a comma after last argument in dict unlike example mentioned above, I didn't put a comma after last value (key3=val3)


Solution

  • PEP8 clearly says:

    Don't use spaces around the = sign when used to indicate a keyword argument or a default parameter value.

    You don't need to put white spaces around the equal sign in both cases.

    If you are not sure whether your code follows PEP8 standard or not, use flake8 static code analysis tool. It would raise warnings in case of code style violations.

    Example:

    Consider you have extra whitespaces around the equal signs:

    def myfunc(key1 = 'val1',
               key2 = 'val2',
               key3 = 'val3'):
        return key1, key2, key3
    

    flake8 outputs a warning for every unexpected whitespace:

    $ flake8 test.py
    test.py:3:16: E251 unexpected spaces around keyword / parameter equals
    test.py:3:18: E251 unexpected spaces around keyword / parameter equals
    test.py:4:16: E251 unexpected spaces around keyword / parameter equals
    test.py:4:18: E251 unexpected spaces around keyword / parameter equals
    test.py:5:16: E251 unexpected spaces around keyword / parameter equals
    test.py:5:18: E251 unexpected spaces around keyword / parameter equals