os.path and Path

Ethan Furman ethan at stoneleaf.us
Wed Jun 15 22:00:07 EDT 2011


In my continuing quest for Python Mastery (and because I felt like it ;) 
I decided to code a Path object so I could dispense with all the 
os.path.join and os.path.split and os.path.splitext, etc., etc., and so 
forth.

While so endeavoring a couple threads came back and had a friendly 
little chat in my head:

Thread 1: "objects of different types compare unequal"
self:     "nonsense!  we have the power to say what happens in __eq__!"

Thread 2: "objects that __hash__ the same *must* compare __eq__!"
self:     "um, what? ... wait, only immutable objects hash..."

Thread 2: "you're Path object is immutable..."
self:     "argh!"

Here's the rub:  I'm on Windows (yes, pity me...) but I prefer the 
unices, so I'd like to have / seperate my paths.  But I'm on Windows...

So I thought, "Hey!  I'll just do some conversions in __eq__ and life 
will be great!"

--> some_path = Path('/source/python/some_project')
--> some_path == '/source/python/some_project'
True
--> some_path == r'\source\python\some_project'
True
--> # if on a Mac
--> some_path == ':source:python:some_project'
True
--> # oh, and because I'm on Windows with case-insensitive file names...
--> some_path == '/source/Python/some_PROJECT'
True

And then, of course, the ghosts of threads past came and visited.  For 
those that don't know, the __hash__ must be the same if __eq__ is the 
same because __hash__ is primarily a shortcut for __eq__ -- this is 
important when you have containers that are relying on this behavior, 
such as set() and dict().

So, I suppose I shall have to let go of my dreams of

--> Path('/some/path/and/file') == '\\some\\path\\and\\file'

and settle for

--> Path('...') == Path('...')

but I don't have to like it.  :(

</whine>

~Ethan~

What, you didn't see the opening 'whine' tag?  Oh, well, my xml isn't 
very good... ;)



More information about the Python-list mailing list