Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # implements_to_string class decorator that helps implementing classes with __unicode__ or __str__ methods
- # Based on: http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/
- # However, the code below is supposed to work for an arbitrary encoding, not just utf-8
- import sys
- isPy3k = sys.version_info[0] == 3
- if isPy3k:
- implements_to_string = lambda x: x
- else:
- print "you're using Python 2"
- def implements_to_string(cls):
- class Klass(cls):
- def __init__(self, *args, **kwargs):
- super(Klass, self).__init__(*args, **kwargs)
- print "defining __unicode__"
- cls.__unicode__ = cls.__str__
- print "defining __str__, which uses %s encoding" % self.encoding
- cls.__str__ = lambda x: x.__unicode__().encode(self.encoding)
- return Klass
- @implements_to_string
- class Test(object):
- @property
- def encoding(self):
- """In reality this method extracts the encoding from a file"""
- return "rot13"
- def __str__(self):
- return "str called"
- if __name__ == "__main__":
- t = Test()
- print unicode(t)
- print str(t)
Advertisement
Add Comment
Please, Sign In to add comment