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

Georg Brandl g.brandl at gmx.net
Sat Oct 6 19:51:40 CEST 2012


Am 06.10.2012 19:32, schrieb Massimo DiPierro:
> How about something along this lines:
> 
> import os
> 
> class Path(str):
>     def __add__(self,other):
>         return Path(self+os.path.sep+other)
>     def __getitem__(self,i):
>         return self.split(os.path.sep)[i]
>     def __setitem__(self,i,v):
>         items = self.split(os.path.sep)
>         items[i]=v
>         return Path(os.path.sep.join(items))
>     def append(self,v):
>         self += os.path.sep+v
>     @property
>     def filename(self):
>         return self.split(os.path.sep)[-1]
>     @property
>     def folder(self):
>         items =self.split(os.path.sep)
>         return Path(os.path.sep.join(items[:-1]))
> 
> path = Path('/this/is/an/example.png')
> print isinstance(path,str) # True
> print path[-1] # example.png
> print path.filename # example.png
> print path.folder # /this/is/an

If you inherit from str, you cannot override any of the operations that
str already has (i.e. __add__, __getitem__).  And obviously you also
can't make it mutable, i.e. __setitem__.

Georg




More information about the Python-ideas mailing list