pathlib

Barry Scott barry at barrys-emacs.org
Mon Sep 30 05:19:19 EDT 2019



> On 30 Sep 2019, at 09:55, Peter Otten <__peter__ at web.de> wrote:
> 
> DL Neil via Python-list wrote:
> 
>> Should pathlib reflect changes it has made to the file-system?
>> 
>> 
>> Sample code, below, shows pathlib identifying a data-file and then
>> renaming it. Yet, after the rename operation, pathlib doesn't recognise
>> its own change; whereas the file system does/proves the change was
>> actioned.
>> 
>> 
>> $ touch before.file
>> $ python3
>> Python 3.7.4 (default, Jul  9 2019, 16:48:28)
>> [GCC 8.3.1 20190223 (Red Hat 8.3.1-2)] on linux
>> Type "help", "copyright", "credits" or "license" for more information.
>>>>> import pathlib
>>>>> p = pathlib.Path( "before.file" )
>>>>> p
>> PosixPath('before.file')
>>>>> p.name
>> 'before.file'
>>>>> p.rename( "after.file" )
>>>>> p.name
>> 'before.file'
>>>>> exit()
>> $ ls -lah after*
>> -rw-rw-r--. 1 dn dn 0 Sep 30 16:05 after.file
>> $ ls -lah before*
>> ls: cannot access 'before*': No such file or directory
>> 
>> 
>> I would expect pathlib to keep track of changes it has made. Any
>> ideas/good reasons why/why not?
>> NB "name" is a r/o attribute.
> 
> This is certainly not a backwards-compatible change. Consider:
> 
> p = pathlib.Path("data.txt")
> p.rename("data.txt.bak")
> with p.open("w") as f: 
>    f.write("new stuff") # oops, we are overwriting the backup
> 
> Also, it will not necessarily be as obvious as in the above example.
> Everywhere you write 
> 
> p = q
> 
> you produce an occasion to unexpectedly change a file reference. Generally, 
> it's easier to reason about immutable objects.
> 
> What might be helpful would be to return a new Path object
> 
> renamed = original.rename(...)

I do not think this is useful as in my code I will already have a path object to
use as the rename target.

src = pathlib.Path('/source/data.txt')
dst = pathlib.Path('/backup/data.bak')

src.rename( dst )
print( 'Renamed %s to %s' % (src, dst) )

> 
> but as I'm not a pathlib user I have no idea what the use-it to throw-it-
> away ratio would be.

Barry

> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list <https://mail.python.org/mailman/listinfo/python-list>



More information about the Python-list mailing list