Problems trying to override __str__ on path class

Peter Otten __peter__ at web.de
Sun Oct 22 15:25:51 EDT 2006


Mike Krell wrote:

> I'm running into problems trying to override __str__ on the path class
> from Jason Orendorff's path module
> (http://www.jorendorff.com/articles/python/path/src/path.py).
> 
> My first attempt to do this was as follows:
> 
> '''
> class NormPath(path):
> def __str__(self):
> return 'overridden __str__: ' + path.__str__(self.normpath())
> '''
> 
> The problem is that the override is not invoked unless str() is called
> explictly, as indicated by the test program and its output below:
> 
> '''
> from normpath import NormPath
> np = NormPath('c:/mbk/test')
> print 'np: "%s"' % np
> print 'str(np): "%s"' % str(np)
> print np / 'appendtest'
> 
> 
> np: "c:/mbk/test"
> str(np): "overridden __str__: c:\mbk\test"
> c:/mbk/test\appendtest
> '''

With

from path import path

class NormPath(path):
    def __str__(self):
        return 'overridden __str__: ' + path.__str__(self.normpath())

np = NormPath('c:/mbk/test')
print 'np: "%s"' % np
print 'str(np): "%s"' % str(np)
print np / 'appendtest'

I get

np: "overridden __str__: c:/mbk/test"
str(np): "overridden __str__: c:/mbk/test"
overridden __str__: overridden __str__: c:/mbk/test/appendtest

Are you using the latest version of the path module? Older versions implied
a Path() call in the __div__() operator which would explain at least the
output you get for

print np / 'appendtest'

Peter






More information about the Python-list mailing list