Search code examples
pythonpep8

Breaking a long function in Python according to PEP 8


I read the docs, but it does not really deal with the type of functions I come across in the projects I manage. Something like this:

class ReallyLongChildClassName(Parent):
    def complex_function_name(self, obj=None):
        if self.condition:
            return 'bar'
        else:
            return super(ReallyLongChildClassName, self).complex_function_name(request, obj)

The last line clearly exceeds the 79 characters length which is specified. What is the correct way to break these type of functions? I am talking about the ones that use the . operator to call more functions.

I have a few different ideas, but don't really know which one is the standard way. For example:

class ReallyLongChildClassName(Parent):
    def complex_function_name(self, obj=None):
        if self.condition:
            return 'bar'
        else:
            return super(
                ReallyLongChildClassName,
                self
            ).complex_function_name(request, obj)

Solution

  • As long as you keep proper indentations and line length everything is ok. There is no single, best style, you can choose it according to your taste :)

    There are tools for formatting code and one I would recommend for you is Black (https://github.com/ambv/black).