pythonpython-3.xpandas

Breaking long method chains into multiple lines in Python


I'm learning Python and pandas and I very often end up with long chains of method calls. I know how to break lists and chains of operators in a way that compiles, but I can't find a way to break method chains in a way that doesn't feel like cheating.

There's plenty of examples of breaking up operator chains and lists in the googles, but I can't find anything decent for method chains.

What would be the best way in Python 3 to break a long chain of method calls into multiple lines?

Say a line like this one:

t_values = df_grouped_by_day.sort_values('day_of_week').groupby(['day_of_week', 'day_of_week_name'])['Show_up'].apply(lambda sample: ttest_ind(population, sample)).reset_index()

Solution

  • Python Black wraps lines for call chaining as:

    t_values = (
        df_grouped_by_day.sort_values('day_of_week')
        .groupby(
            [
                'day_of_week',
                'day_of_week_name',
                "foo",
                "bar",
                "buzz",
                "foobar",
                "foobarbuz",
            ]
        )['Show_up']
        .apply(
            lambda sample: ttest_ind(
                population,
                sample,
                foo,
                bar,
                buzz,
                foobar,
                foobarbuz,
            )
        )
        .reset_index()
    )
    

    I added a few more arguments to stretch the above example but reduced them to make my point in the below one.

    Personally, I used to prefer more like the following, but that can get weird when making some calls without arguments, as well as mixing square-brace accessory syntax, like the above example.

    t_values = df_grouped_by_day.sort_values(
        'day_of_week',
    ).groupby(
        [
            'day_of_week',
            'day_of_week_name',
        ]
    ).apply(
        lambda sample: ttest_ind(population, sample)
    )