473,387 Members | 1,504 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Problems trying to override __str__ on path class

I'm running into problems trying to override __str__ on the path class
from Jason Orendorff's path module
(http://www.jorendorff.com/articles/p...h/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
'''

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)

e:\projects\Python\vc\nptest.py
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: <nptest.py>
'''

Can someone explain these failures to me? Also, assuming I don't want to
modify path.py 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,
Mike
Oct 22 '06 #1
5 2451
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/p...h/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

Oct 22 '06 #2
Peter Otten <__*******@web.dewrote in
news:eh*************@news.t-online.com:
I get

np: "overridden __str__: c:/mbk/test"
str(np): "overridden __str__: c:/mbk/test"
overridden __str__: overridden __str__: c:/mbk/test/appendtest
Hmmm. I guess you're not running under windows, since normpath()
converts / to \ on windows. I wonder if that's part of the problem.

Are you using the latest version of the path module?
My path.py says it's 2.1, which is the latest according to the site.

Older versions
implied a Path() call in the __div__() operator which would explain at
least the output you get for

print np / 'appendtest'
You've lost me here. What do you mean about "implied a Path() call"?
Here is the definition of __div__ from path.py:

'''
# The / operator joins paths.
def __div__(self, rel):
""" fp.__div__(rel) == fp / rel == fp.joinpath(rel)

Join two path components, adding a separator character if
needed.
"""
return self.__class__(os.path.join(self, rel))
'''

I still don't understand the TypeError in the delegation case.

Mike
Oct 23 '06 #3
Mike Krell wrote:
Peter Otten <__*******@web.dewrote in
news:eh*************@news.t-online.com:
>I get

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

Hmmm. I guess you're not running under windows, since normpath()
converts / to \ on windows. I wonder if that's part of the problem.

>Are you using the latest version of the path module?

My path.py says it's 2.1, which is the latest according to the site.

Older versions
>implied a Path() call in the __div__() operator which would explain at
least the output you get for

print np / 'appendtest'

You've lost me here. What do you mean about "implied a Path() call"?
Here is the definition of __div__ from path.py:

'''
# The / operator joins paths.
def __div__(self, rel):
""" fp.__div__(rel) == fp / rel == fp.joinpath(rel)

Join two path components, adding a separator character if
needed.
"""
return self.__class__(os.path.join(self, rel))
'''
From http://www.jorendorff.com/articles/p.../changes.html:

"""
This page describes recent changes to the Python path module.

2.1

[...]

Better support for subclassing path. All methods that returned path objects
now respect subclassing.

Before: type(PathSubclass(s).parent) is path

Now: type(PathSubclass(s).parent) is PathSubclass
"""

So my assumption was that you are using a pre-2.1 version of path.
I suggest that you double-check that by inserting a

print path.__version__

into the code showing the odd behaviour before you start looking for more
exotic causes.
I still don't understand the TypeError in the delegation case.
For newstyle classes

a = A()
a / 42 # or any other operation implemented via __xxx__()

(unlike a.__div__) will only look into the class for a __div__() special
method and ignore methods defined in the instance or via the __getattr__()
mechanism.

For delegation to work you need (untested)

class NormPath(object):
def __div__(self, other):
return self.__class__(self._path / other)
# ...

Peter
Oct 23 '06 #4
Peter Otten <__*******@web.dewrote in
news:eh*************@news.t-online.com:
>
So my assumption was that you are using a pre-2.1 version of path.
I suggest that you double-check that by inserting a

print path.__version__

into the code showing the odd behaviour before you start looking for
more exotic causes.
Alas, the print statement says "2.1". So there's a definite platform /
environment difference here, but that isn't it.
For delegation to work you need (untested)

class NormPath(object):
def __div__(self, other):
return self.__class__(self._path / other)
# ...
I see. The base class implementation is throwing up its hands at the
unknown type NormPath. One needs to substitute the parameter in every
case where the base class implementation is called. That kind of kills
the attractiveness of the technique for new style classes, unless a way
could be done to do it programatically instead of explicitly for each
method. Of course, if I could get the simple override to work, the need
to do this would disappear.

Mike
Oct 23 '06 #5
Mike Krell wrote:
Alas, the print statement says "2.1".**So*there's*a*definite*platform*/
environment difference here, but that isn't it.
It turns out the observed difference is only indirectly triggered by the
differing platforms. On my machine the path baseclass is str. If I change
it to unicode (by patching path.py), I get the same output that you had.
The problem can be reduced to
>>class A(str):
.... def __str__(self): return "yadda"
....
>>"%s" % A(), str(A())
('yadda', 'yadda')
>>class B(unicode):
.... def __str__(self): return "yadda"
....
>>"%s" % B(), str(B())
(u'', 'yadda')

So Python itself doesn't honor an overridden __str__() method for the "%s"
format. Implementing __unicode__() doesn't help, either:
>>class C(unicode):
.... def __unicode__(self): return u"YADDA"
.... def __str__(self): return "yadda"
....
>>"%s" % C(), unicode(C())
(u'', u'')

Somewhere there is an isinstance() test where there should be a test for the
exact class. Seems like a bug to me.

Peter

Oct 23 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: Jim Newton | last post by:
hi all, does anyone know what print does if there is no __str__ method? i'm trying ot override the __repr__. If anyone can give me some advice it would be great to have. I have defined a...
7
by: Jeffrey E. Forcier | last post by:
I am attempting to write a class whose string representation changes in response to external stimuli. While that effect is obviously possible via other means, I attempted this method first and was...
10
by: BBFrost | last post by:
We just recently moved one of our major c# apps from VS Net 2002 to VS Net 2003. At first things were looking ok, now problems are starting to appear. So far ... (1) ...
19
by: Dales | last post by:
I have a custom control that builds what we refer to as "Formlets" around some content in a page. These are basically content "wrapper" sections that are tables that have a colored header and...
2
by: John Mullin | last post by:
We are having a problem which appears similar to a previous posting: http://groups.google.com/groups?hl=en&lr=&frame=right&th=d97f552e10f8c94c&seekm=OZw33z9EDHA.2312%40TK2MSFTNGP10.phx.gbl#link1 ...
0
by: Rick Hein | last post by:
I've got a problem with an app I've been working on, the Caching object and events not firing correctly. In a nutshell: When I'm debugging, and I set a breakpoint in the removed item call back, the...
1
by: Edward C. Jones | last post by:
#! /usr/bin/env python class A(list): def __init__(self, alist, n): list.__init__(self, alist) self.n = n def __str__(self): return 'AS(%s, %i)' % (list.__str__(self), self.n)
6
by: ahart | last post by:
I'm pretty new to python and am trying to write a fairly small application to learn more about the language. I'm noticing some unexpected behavior in using lists in some classes to hold child...
7
by: netimen | last post by:
I couldn't substitute __str__ method of an instance. Though I managed to substitute ordinary method of an instance: from types import MethodType class Foo(object): pass class...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.