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

半世苍凉 提交于 2019-12-12 08:46:59

问题


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:

  • Jason's path module (updated for PEP 355)
  • Mike Orr's Unipath, basically a more modern version of the above
  • Noam Raphael's alternative path module that subclasses tuple instead of str

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))

回答1:


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.




回答2:


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))




回答3:


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.



来源:https://stackoverflow.com/questions/1252639/which-path-module-or-class-do-python-folks-use-instead-of-os-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!