MartinThoma / flake8-simplify

❄ A flake8 plugin that helps you to simplify code
MIT License
186 stars 19 forks source link

[SIM906] Merge nested os.path.join calls #101

Closed Skylion007 closed 2 years ago

Skylion007 commented 2 years ago

Explanation

Explain briefly why you think this makes the code simpler.

Example

a = "/a"
b = "b"
c = "c"
# Bad
os.path.join(a,os.path.join(b,c))

# Good
os.path.join(a,b,c)
MartinThoma commented 2 years ago

I didn't know that this was possible! I'll add this when I have more time for sure - this should also be easy / have little potential for false-positives. Very nice suggestion!

MartinThoma commented 2 years ago

Side-note: pathlib.Path should be used more often. If a, b, and c were Path objects, you could simply do:

d = a / b / c
MartinThoma commented 2 years ago

Many usages of os.path can be replaced by pathlib.

Skylion007 commented 2 years ago

@MartinThoma True, but there can be performance issues with using Pathlib. For instance, I think the black formatter removed / reworked a lot of their Pathlib usage back to os.path in their library due to performance issues.

MartinThoma commented 2 years ago
$ astpretty --no-show-offsets /dev/stdin <<< `cat example.txt`
Module(
    body=[
        Expr(
            value=Call(
                func=Attribute(
                    value=Attribute(
                        value=Name(id='os', ctx=Load()),
                        attr='path',
                        ctx=Load(),
                    ),
                    attr='join',
                    ctx=Load(),
                ),
                args=[
                    Name(id='a', ctx=Load()),
                    Call(
                        func=Attribute(
                            value=Attribute(
                                value=Name(id='os', ctx=Load()),
                                attr='path',
                                ctx=Load(),
                            ),
                            attr='join',
                            ctx=Load(),
                        ),
                        args=[
                            Name(id='b', ctx=Load()),
                            Name(id='c', ctx=Load()),
                        ],
                        keywords=[],
                    ),
                ],
                keywords=[],
            ),
        ),
    ],
    type_ignores=[],
)