473,726 Members | 2,142 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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__(se lf.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__(sel f, attr):
print 'delegating %s...' % attr
return getattr(self._p ath, 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.Type Error Traceback (most
recent call last)

e:\projects\Pyt hon\vc\nptest.p y
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 2466
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__(sel f):
return*'overrid den*__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__(se lf.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(se lf, 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(se lf, 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(PathSubcla ss(s).parent) is path

Now: type(PathSubcla ss(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*ther e'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__(sel f): 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
5950
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 lisp-like linked list class as a subclass of list. The __iter__ seems to work as i'd like, by traversing the links, and the __repr__ seems to work properly for somethings but not others. The basic idea is that a list such as is converted to ]],...
7
1910
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 surprised when it didn't work, so I now want to know why :) Given the following class definition: class MyClass(object): def Edit(self):
10
2412
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) ComboBox.SelectedValue = db_value; If the db_value was not included in the ComboBox value list the ComboBox.SelectedIndex used to return -1, Now the very same code is
19
2979
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 provide an open TD with a DIV in it for the content of this formlet. (The DIV is for DHTML to hide and show the content) I've created a web page showing step by step the two problems I'm encountering. This problem is much easier to see than it...
2
2291
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 In the current release of our system, we decided to "wrap" the ASP.NET Session and Application objects to improve code clarity and accuracy. For example, instead of: Session = new SomeListClass;
0
1755
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 code works correctly. If there is no debugger it doesn't fire, which causes the app to have problems. Here's what the code does: The TemplateData class inherits from the DataSet Object, in the constructor it loads itself with Data from an XML...
1
1478
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
1672
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 objects. Here is some abbreviated code to help me explain. #################################### class Item(object) __text = "" def __get_text(self): return self.__text
7
1417
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 Printer(object):
1
9182
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9120
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4521
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4785
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3228
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.