Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 968805
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T02:32:33+00:00 2026-05-16T02:32:33+00:00

Trying to change the __unicode__ method on an instance after it’s created produces different

  • 0

Trying to change the __unicode__ method on an instance after it’s created produces different results on Python 2.5 and 2.6.

Here’s a test script:

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__()

On Python 2.5, this produces

one
two
two

That is, changing the instance’s __unicode__ also changes unicode(instance)

On Python 2.6, this produces

one
one
two

So, after a change, unicode(instance) and instance.__unicode__() return different results.

Why? How can I get this working on Python 2.6?

(For what it’s worth, the use case here is that I want to append something to the output of __unicode__ for all subclasses of a given class, without having to modify the code of the subclasses.)

Edit to make the use case a little clearer

I have Class A, which has many subclasses. Those subclasses define simple __unicode__ 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.

This is actually existing code that works in Python 2.5. It’s something like this:

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'

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.)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T02:32:34+00:00Added an answer on May 16, 2026 at 2:32 am

    It appears that you are not allowed to monkey-patch protocol methods (those that begin and end with double underscores) :

    Note

    In practise there is another exception
    that we haven’t handled here. Although
    you can override methods with instance
    attributes (very useful for monkey
    patching methods for test purposes)
    you can’t do this with the Python
    protocol methods. These are the ‘magic
    methods’ whose names begin and end
    with double underscores. When invoked
    by the Python interpreter they are
    looked up directly on the class and
    not on the instance (however if you
    look them up directly – e.g.
    x.repr – normal attribute lookup
    rules apply).

    That being the case, you may be stuck unless you can go with ~unutbu’s answer.

    EDIT: Or, you can have the base class __unicode__ method search the instance object’s dict for a __unicode__ attribute. If it’s present, then __unicode__ is defined on the instance object, and the class method calls the instance method. Otherwise, we fall back to the class definition of __unicode__.

    I think that this could allow your existing subclass code to work without any changes. However, it gets ugly if the derived class wants to invoke the class implementation — you need to be careful to avoid infinite loops. I haven’t implemented such hacks in this example; merely commented about them.

    import types
    
    class Dummy(object):
        def __unicode__(self):
            func = self.__dict__.get("__unicode__", None)
            if func:
                // WARNING: if func() invokes this __unicode__ method directly,
                // an infinite loop could result. You may need an ugly hack to guard
                // against this. (E.g., set a flag on entry / unset the flag on exit,
                // using a try/finally to protect against exceptions.)
    
                return func()
    
            return u'one'
    
        def two(self):
            return u'two'
    
    d = Dummy()
    print unicode(d)
    funcType = type(Dummy.__unicode__)
    d.__unicode__ = types.MethodType(Dummy.two, d)
    print unicode(d)
    print d.__unicode__()
    

    Testing with Python 2.6 produces the following output:

    > python dummy.py 
    one
    two
    two
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 542k
  • Answers 542k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Use: SELECT p.id as a, p.url as b, t.id as… May 17, 2026 at 3:22 am
  • Editorial Team
    Editorial Team added an answer There are two parts to the problem First Issue You… May 17, 2026 at 3:19 am
  • Editorial Team
    Editorial Team added an answer I thought I'd show the regex approach, too. It doesn't… May 17, 2026 at 3:18 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

Im trying to change images on click similar to what SO does with the
I'm trying to change the background color of a single subplot in a MATLAB
I'm trying to change the background color of single cell be based on a
Basically I'm trying to change the Canvas.Left property of an Ellipse Silverlight control in
I'm trying to change default firstDayOfWeek for java.util.Calendar from SUNDAY to MONDAY. Is it
I'm trying to change user input in wildcard form (*word*) to a regular expression
I am trying to change the rows output by PHP in a table to
I'm trying to change a site's home directory using powershell. This is what I
I'm trying to change the alt of the image, I'm clicking by selecting the
I am trying to change the keys my keyboard sends to applications. I've already

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.