[flake8-use-pathlib] Recommend Path.iterdir() over os.listdir() (PTH208)#14509
[flake8-use-pathlib] Recommend Path.iterdir() over os.listdir() (PTH208)#14509MichaReiser merged 5 commits intoastral-sh:mainfrom
flake8-use-pathlib] Recommend Path.iterdir() over os.listdir() (PTH208)#14509Conversation
|
| code | total | + violation | - violation | + fix | - fix |
|---|---|---|---|---|---|
| PTH208 | 52 | 52 | 0 | 0 | 0 |
|
I noticed two common patterns when reviewing the ecosystem checks: The first requires using The second mainly becomes more verbose. I'm interested in more opinions if we should exclude them. Wdyt @sbrugman https://github.com/bokeh/bokeh/blob/829b2a75c402d0d0abd7e37ff201fbdfd949d857/examples/server/app/simple_hdf5/main.py#L19 |
To be pedantic, |
|
The pathlib rules should flag all It could be good to already include these cases in the tests to make sure they are covered when autofix is implemented later. The complexity here is in the fix, not in the detection of the violation. Going over the ecosystem results I realise that Using 'demo_data.hdf5' not in os.listdir(app_dir)Idiomatic not os.path.exists(os.path.join(app_dir), 'demo_data.hdf5')Pathlib equivalent: not (app_dir / "demo_data.hdf5").exists()Checking if a directory is empty with not os.listdir(api_dir)Users should probably write something like: next(os.scandir(api_dir), None) is NonePathlib equivalent: next(api_dir.iterdir(), None) is None |
Got it. I'll get to that the day after tomorrow. |
|
@sbrugman On second thought... should |
|
No, adding a separate rule is consistent with other rules: https://docs.astral.sh/ruff/rules/os-remove/ The distinction could be useful for users who would like to fix |
MichaReiser
left a comment
There was a problem hiding this comment.
Thanks @sbrugman. That makes sense to me. @InSyncWithFoo happy to merge this rule once we added tests demonstrating the patterns linked in #14509 (comment)
|
@MichaReiser Done. I added them to the rule's documentation as well. |
Summary
Resolves #14490.
Test Plan
cargo nextest runandcargo insta test.