[Python-ideas] PEP 428 - object-oriented filesystem paths

Devin Jeanpierre jeanpierreda at gmail.com
Sat Oct 6 19:53:55 CEST 2012


On Sat, Oct 6, 2012 at 12:14 PM, Calvin Spealman <ironfroggy at gmail.com> wrote:
> The stat operations and other file-facilities tacked on feel out of
> place, and limited. Why does it make sense to add these facilities to
> path and not other file operations? Why not give me a read method on
> paths? or maybe a copy? Putting lots of file facilities on a path
> object feels wrong because you can't extend it easily. This is one
> place that function(thing) works better than thing.function()

The only reason to have objects for anything is to let people have
other implementations that do something else with the same method.

I remember one of the advantages to having an object-oriented path
API, that I always wanted, is that the actual filesystem doesn't have
to be what the paths access. They could be names for web resources, or
files within a zip archive, or virtual files on a pretend hard drive
in your demo application. That's fantastic to have, imo, and it's
something function calls (like you suggest) can't possibly support,
because functions aren't extensibly polymorphic.

If we don't get this sort of polymorphism of functionality, there's
very little point to an object oriented path API. It is syntax sugar
for function calls with slightly better type safety (NTPath(...) /
UnixPath(...) == TypeError -- I hope.)

So I'd assume the reason that these methods exist is to enable polymorphism.

As for why your suggested methods don't exist, they are better written
as functions because they don't need to be ad-hoc polymorphic, they
work just fine as regular functions that call methods on path objects.
e.g.

def read(path):
    return path.open().read()

def copy(path1, path2):
    path2.open('w').write(path1.read()) # won't work for very large
files, blah blah blah

Whereas the open method cannot work this way, because the path should
define how file opening works. (It might return an io.StringIO for
example.) And the return value of .open() might not be a real file
with a real fd, so you can't implement a stat function in terms of
open and f.fileno() and such. And so on.

-- Devin



More information about the Python-ideas mailing list