Python code style: is there a way to configure linters to split parameters into multiple lines?

853 Views Asked by At

Currently I am working on a Python 3.8 project with Django 3.1.4 where I would like the code style to be enforced in the following manner:

Split iterables into multiple lines, keeping brackets in separate lines from their contents. For example:

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": os.getenv("DATABASE_NAME", "my_db"),
        ...
        "PORT": os.getenv("DATABASE_PORT", "5432"),
    }
}

...

CHOICES = (
    (LOCATION, "Location"),
    (INTEREST, "Interest"),
    (CULTURE, "Culture"),
)

Split function signature parameters into multiple lines where they don't fit the same one, with one parameter per line, for readability. Example:

def test_user_can_filter_all_communities(
    self,
    filter_field: str,
    filter_value: JSONSerializable,
    include_results: list,
):
    # my code here
    ...

The most important to me at the moment being the latter.

I have tried to use autopep8, pylint, yapf and black, but despite trying different configurations for each, I am currently unable to achieve this with an automatic code formatter.

When I use black, parameters look like this:

def test_user_can_filter_all_communities(
    self, filter_field: str, filter_value: JSONSerializable, include_results: list
):

which drives me crazy because I like to "enumerate" how many parameters my function/method takes immediately.

And when I use yapf this is what happens:

def test_user_can_filter_all_communities(self,
                                         filter_field: str,
                                         filter_value: JSONSerializable,
                                         include_results: list):

Which unfortunately it's still not ideal because I am verbose with variable names, so continuing indentation from parameter above is at many times impossible whilst also enforcing a line length limit.

I am used to writing code this way and this style makes me productive, besides helping me spot code smells and potential bugs. But at the present moment I am working on a medium-sized codebase by myself and it's taking up too much of my time to enforce this style by manually formatting it.

Is there any automatic code formatter out there which can help me achieve this? Or would anyone know how this can be achieved with one of the mentioned ones?

(I do recall working on a project 3 years ago where we enforced this code style with either pylint or black, so it should be feasible somehow but I cannot find out how.)

Thank you in advance.

1

There are 1 best solutions below

0
On

Add a comma after your last parameter, black will do what you want then.

def test_user_can_filter_all_communities(
    self, filter_field: str, filter_value: JSONSerializable, include_results: list,
):

See : https://github.com/psf/black/issues/1288