简体   繁体   中英

Which path module or class do Python folks use instead of os.path?

Just wondering how many people use a path module in Python such as Jason Orendorff's one, instead of using os.path for joining and splitting paths? Have you used:

I know Jason's path module was made into PEP 355 and rejected by the BDFL. This seems like it was mainly because it tried to do everything in one class.

Our use case is mainly to simplify joining and splitting components of paths, so we'd be quite happy if such a path class only implemented the split/join type of operations. Who wouldn't want to do this:

path(build_dir, path(source_file).name)

or this:

build_dir / path(source_file).name

instead of this:

os.path.join(build_dir, os.path.basename(source_file))

I can pick up a Python program and interpret the current standard method without hesitation - it's explicit and there's no ambiguity:

os.path.join(build_dir, os.path.basename(source_file))

Python's dynamic typing makes the first method rather difficult to comprehend when reading:

build_dir / path(source_file).name

Plus it's not common to divide strings, which brings up more confusion. How do I know that those two aren't integers? Or floats? You won't get a TypeError at runtime if both end up as non-string types.

Finally,

path(build_dir, path(source_file).name)

How is that any better than the os.path method?

While they may "simplify" coding (ie, make it easier to write), you're going to run into strife if someone else who is unfamiliar with the alternative modules needs to maintain the code.

So I guess my answer is: I don't use an alternative path module. os.path has everything I need already, and it's interface isn't half bad.

A simple but useful trick is this:

import os

Path = os.path.join

Then, instead of this:

os.path.join(build_dir, os.path.basename(source_file))

You can do this:

Path(build_dir, Path(source_file))

Dividing strings to join paths may seem like a "neat trick" but it's precisely that kind of thing that Python programmers like to avoid (and btw, programmers in most other langauges.) The os.path module is widely used and easily understood by all. Doing funky things with overloaded operators on the other hand is confusing, it impairs the readability of your code, which is meant to be one of Python's strong points.

C++ programmers, on the other hand, love that kind of thing. Perhaps that's one of the reasons C++ code can be so difficult to read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM