Problems trying to override __str__ on path class

Mike Krell no at
Sun Oct 22 20:14:41 CEST 2006

I'm running into problems trying to override __str__ on the path class 
from Jason Orendorff's path module 

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"

I suspect that the problem has to do with the base class of the path 
class being unicode because it works when I create dummy classes derived 
off of object.

My next attempt was to try delegation as follows:

class NormPath(object):
    def __init__(self, *a, **k):
        self._path = path(*a, **k)

    def __str__(self):
        return 'overridden __str__: ' + str(self._path.normpath())

    def __getattr__(self, attr):
        print 'delegating %s...' % attr
        return getattr(self._path, attr)

In this case the test program blows up with a TypeError when trying to 
invoke the / operator:

np: "overridden __str__: c:\mbk\test"
str(np): "overridden __str__: c:\mbk\test"
exceptions.TypeError                                 Traceback (most 
recent call last)

      1 from normpath import NormPath
      2 np=NormPath('c:/mbk/test')
      3 print 'np: "%s"' % np
      4 print 'str(np): "%s"' % str(np)
----> 5 print np / 'appendtest'

TypeError: unsupported operand type(s) for /: 'NormPath' and 'str'
WARNING: Failure executing file: <>

Can someone explain these failures to me?  Also, assuming I don't want to 
modify itself, is there any way to do what I'm trying to 
accomplish?  BTW, I'm running 2.4.2 under Windows.

Thanks in advance,

More information about the Python-list mailing list