PEP on path module for standard library

Andrew Dalke dalke at dalkescientific.com
Sun Jul 31 03:28:13 EDT 2005


Peter Hansen wrote:
> 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.

I have been able to do this by inserting my own module-scope function
that intercepts the lookup before it gets to builtins.  A problem
though is that a future (Python 3K?) Python may not allow that.

For example,

module.open = mock_open
try:
  ...
finally:
  module.open = open

By looking at the call stack it is possible to replace the built-in
open to have new behavior only when called from specific modules or
functions, but that gets to be rather hairy.

> 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.

By analogy to the other builtins, another solution is to have a
protocol by which open() dispatches to an instance defined method.

> 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.

But then what does the constructor for the file object take?

I've also heard mention that a future (Py3K era) 'open' may allow
URLs and not just a path string.

				Andrew
				dalke at dalkescientific.com




More information about the Python-list mailing list