[Python-ideas] PEP 428 - object-oriented filesystem paths
Massimo DiPierro
massimo.dipierro at gmail.com
Sat Oct 6 20:22:06 CEST 2012
I was thinking of the api more than the implementation.
The point to me is that it would be nice to have something the behaves as a string and as a list at the same time.
Here is another possible incomplete implementation.
import os
class Path(object):
def __init__(self,s='/',sep=os.path.sep):
self.sep = sep
self.s = s.split(sep)
def __str__(self):
return self.sep.join(self.s)
def __add__(self,other):
if other[0]=='':
return Path(other)
else:
return Path(str(self)+os.sep+str(other))
def __getitem__(self,i):
return self.s[i]
def __setitem__(self,i,v):
self.s[i] = v
def append(self,v):
self.s.append(v)
@property
def filename(self):
return self.s[-1]
@property
def folder(self):
return Path(self.sep.join(self.s[:-1]))
>>> path = Path('/this/is/an/example.png')
>>> print path[-1]
example.png
>>> print path.filename
example.png
>>> print path.folder
/this/is/an
>>> path[1]='that'
/that/is/an/example.png
>>> print path.folder + 'this'
/that/is/an/this
On Oct 6, 2012, at 12:51 PM, Georg Brandl wrote:
> 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
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
More information about the Python-ideas
mailing list