[Tutor] class decorator question

Albert-Jan Roskam fomcl at yahoo.com
Sat Oct 5 14:33:46 CEST 2013


Hi,

On http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/ I saw a very cool and useful example of a class decorator. It (re)implements __str__ and __unicode__ in case Python 2 is used. For Python 3, the decorator does nothing. I wanted to generalize this decorator so the __str__ method under Python 2 encodes the string to an arbitrary encoding. This is what I've created: http://pastebin.com/vghD1bVJ.

It works, but the code is not very easy to understand, I am affraid. Or is it? And I have no idea how to call the class Klass. Maybe reimplements_Test? Is this a good approach, or can this be done in an easier way? I would *really* like keep statements "if sys.version_info[0] == 3..." separate from the "main" code. Also, learning about class decorators is cool ;-). So the code below... mehhh  no sir, I don't like it.


def __str__(self):

    if sys.version_info[0] == 3:
        blah
    else:
        bleh
  
if sys.version_info[0] == 2:
    def __unicode__(self):
        blooooh


 
Regards,
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131005/0c1abe5d/attachment.html>


More information about the Tutor mailing list