Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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:

  • 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))
like image 713
Ben Hoyt Avatar asked Aug 10 '09 00:08

Ben Hoyt


2 Answers

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.

like image 124
Matthew Iselin Avatar answered Sep 20 '22 03:09

Matthew Iselin


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

like image 36
Steve Ferg Avatar answered Sep 24 '22 03:09

Steve Ferg