Guest User

Untitled

a guest
Oct 5th, 2013
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.18 KB | None | 0 0
  1. # implements_to_string class decorator that helps implementing classes with __unicode__ or __str__ methods
  2. # Based on: http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/
  3. # However, the code below is supposed to work for an arbitrary encoding, not just utf-8
  4.  
  5. import sys
  6.  
  7. isPy3k = sys.version_info[0] == 3
  8.  
  9. if isPy3k:
  10.     implements_to_string = lambda x: x
  11. else:
  12.     print "you're using Python 2"
  13.     def implements_to_string(cls):
  14.         class Klass(cls):
  15.             def __init__(self, *args, **kwargs):
  16.                 super(Klass, self).__init__(*args, **kwargs)
  17.                 print "defining __unicode__"
  18.                 cls.__unicode__ = cls.__str__
  19.                 print "defining __str__, which uses %s encoding" % self.encoding                
  20.                 cls.__str__ = lambda x: x.__unicode__().encode(self.encoding)
  21.         return Klass
  22.  
  23. @implements_to_string
  24. class Test(object):
  25.  
  26.     @property
  27.     def encoding(self):
  28.         """In reality this method extracts the encoding from a file"""
  29.         return "rot13"
  30.  
  31.     def __str__(self):
  32.         return "str called"
  33.  
  34. if __name__ == "__main__":
  35.     t = Test()
  36.     print unicode(t)
  37.     print str(t)
Advertisement
Add Comment
Please, Sign In to add comment