'How to write a long os.path.join chain while complying to PEP8
I am using a long chain of os.path.join() to generate a path (it ensures the path will work on any OS).
"metadata": os.path.join(BASE_DIR, os.path.join('ServiceProvider',os.path.join('config', os.path.join('metadata',os.path.join('gmail_metadata.xml'))))),
I would like to break it down into multiple lines the PEP8 way but I can't seem to make this happen.
I tried several things:
"metadata": os.path.join(BASE_DIR,
os.path.join('ServiceProvider',
os.path.join('config',
os.path.join('metadata',
os.path.join('gmail_metadata.xml'))))),
will get me the PEP8 error continuation line under-indented for visual indentpep8(E128)
and
"metadata": os.path.join(BASE_DIR, os.path.join('ServiceProvider',
os.path.join('config', os.path.join('metadata',
os.path.join('gmail_metadata.xml'))))),
which is actually what PEP8 autofix did, I'm getting the line too long error.
If it is not possible to fix the PEP8 errors in this case I would still like to know how you would do it !
Solution 1:[1]
The pathlib module will allow you to chain things in an interesting and flexible way. Lovely tutorial here
import pathlib
# use / operator
path = pathlib.Path("BASE_DIR")
path /= "ServiceProvider" / "config" / "metadata" / "gmail_metadata.xml"
# or
path = pathlib.Path("BASE_DIR") / "ServiceProvider" / "config" / "metadata" / "gmail_metadata.xml"
# or
path = pathlib.Path("BASE_DIR") /
"ServiceProvider" /
"config" /
"metadata" /
"gmail_metadata.xml"
If you want to use joinpath from os.path module or pathlib then you doint have to nest the joins, one is enough.
path = os.path.join(*[BASE_DIR, "ServiceProvider", "config", "metadata", "gmail_metadata.xml"])
# or
path = pathlib.Path("BASE_DIR").joinpath(*["ServiceProvider", "config", "metadata", "gmail_metadata.xml"])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | run_the_race |
