Note that there are some explanatory texts on larger screens.

plurals
  1. PODifferent instance-method behavior between Python 2.5 and 2.6
    primarykey
    data
    text
    <p>Trying to change the <code>__unicode__</code> method on an instance after it's created produces different results on Python 2.5 and 2.6.</p> <p>Here's a test script:</p> <pre><code>class Dummy(object): def __unicode__(self): return u'one' def two(self): return u'two' d = Dummy() print unicode(d) d.__unicode__ = d.two print unicode(d) print d.__unicode__() </code></pre> <p>On Python 2.5, this produces</p> <pre><code>one two two </code></pre> <p>That is, changing the instance's <code>__unicode__</code> also changes <code>unicode(instance)</code></p> <p>On Python 2.6, this produces</p> <pre><code>one one two </code></pre> <p>So, after a change, <code>unicode(instance)</code> and <code>instance.__unicode__()</code> return different results.</p> <p>Why? How can I get this working on Python 2.6?</p> <p>(For what it's worth, the use case here is that I want to append something to the output of <code>__unicode__</code> for all subclasses of a given class, without having to modify the code of the subclasses.)</p> <p><strong>Edit to make the use case a little clearer</strong></p> <p>I have Class A, which has many subclasses. Those subclasses define simple <code>__unicode__</code> methods. I want to add logic so that, for instances of a Class A subclass, unicode(instance) gets something tacked on to the end. To keep the code simple, and because there are many subclasses I don't want to change, I'd prefer to avoid editing subclass code.</p> <p>This is actually existing code that works in Python 2.5. It's something like this:</p> <pre><code>class A(object): def __init__(self): self._original_unicode = self.__unicode__ self.__unicode__ = self.augmented_unicode def augmented_unicode(self): return self._original_unicode() + u' EXTRA' </code></pre> <p>It's this code that no longer works on 2.6. Any suggestions on how to achieve this without modifying subclass code? (If the answer involves metaclasses, note that class A is itself a subclass of another class -- django.db.models.Model -- with a pretty elaborate metaclass.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload