PEP on path module for standard library
Peter Hansen
peter at engcorp.com
Sat Jul 30 13:37:25 EDT 2005
Reinhold Birkenfeld wrote:
> Mike Orr wrote:
>>- Who needs .open()? open(myPath) is fine. But it can stay for
>>backward compatibility.
>
> Right. I think it's nice for people who like a more OO approach.
There's one very good reason to use .open() on a Path object, and in
fact it's a (for me) strong justification for the existence of Path in
the standard library (and, even more, for porting everything else in the
standard library to use Path).
A scattered assortment of module-level global function names, and
builtins such as open(), make it extraordinarily difficult to do
effective and efficient automated testing with "mock" objects. Although
one can fairly easily shadow the definition of "open" in any given
module under test, if the code under test instead calls another standard
library routine which internally uses open(), it becomes necessary to
replace the builtin definition of open() and affect all code throughout
the program.
Object-oriented solutions like Path make it near trivial to substitute a
mock or other specialized object which (duck typing) acts like a Path
except perhaps for actually writing the file to disk, or whatever other
difference you like.
I haven't gotten around to doing a mock Path object yet, though given
the work that's gone into my existing mock FileSystem object which lets
you replace open() and test code in a fully controlled and safe
environment, it shouldn't be hard to do.
So, for the PEP, another justification for Path is that its use can
encourage better use of automated testing techniques and thereby improve
the quality of Python software, including in the standard library.
-Peter
More information about the Python-list
mailing list