Guest User

Untitled

a guest
Oct 5th, 2013
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # implements_to_string class decorator that helps implementing classes with __unicode__ or __str__ methods
  2. # Based on: Steven's suggestions
  3.  
  4. from __future__ import print_function
  5. import sys
  6.    
  7. def decorate(cls):
  8.     print("decorate called")
  9.     if sys.version_info[0] > 2:
  10.         cls.__dict__["__str__"].__name__ = '__bytes__'
  11.         cls.__dict__["__unicode__"].__name__ = '__str__'
  12.         cls.__bytes__ = cls.__dict__["__str__"]
  13.         cls.__str__ = cls.__dict__["__unicode__"]  
  14.     return cls
  15.  
  16. @decorate
  17. class Test(object):
  18.  
  19.     def __init__(self):
  20.         self.__dict__["encoding"] = self.encoding
  21.  
  22.     def __str__(self):
  23.         return "str called".encode(self.encoding)
  24.  
  25.     def __unicode__(self):
  26.         return "unicode called"
  27.  
  28.     @property
  29.     def encoding(self):
  30.         """In reality this method extracts the encoding from a file"""
  31.         return "utf-8" # rot13 no longer exists in Python3
  32.  
  33. if __name__ == "__main__":
  34.     t = Test()
  35.     if sys.version_info[0] == 2:
  36.         print(unicode(t))
  37.     print(str(t))
Advertisement
Add Comment
Please, Sign In to add comment