SHOW:
|
|
- or go back to the newest paste.
| 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/ |
| 2 | + | # Based on: Steven's suggestions |
| 3 | - | # However, the code below is supposed to work for an arbitrary encoding, not just utf-8 |
| 3 | + | |
| 4 | from __future__ import print_function | |
| 5 | import sys | |
| 6 | ||
| 7 | - | isPy3k = sys.version_info[0] == 3 |
| 7 | + | def decorate(cls): |
| 8 | print("decorate called")
| |
| 9 | - | if isPy3k: |
| 9 | + | if sys.version_info[0] > 2: |
| 10 | - | implements_to_string = lambda x: x |
| 10 | + | cls.__dict__["__str__"].__name__ = '__bytes__' |
| 11 | - | else: |
| 11 | + | cls.__dict__["__unicode__"].__name__ = '__str__' |
| 12 | - | print "you're using Python 2" |
| 12 | + | cls.__bytes__ = cls.__dict__["__str__"] |
| 13 | - | def implements_to_string(cls): |
| 13 | + | cls.__str__ = cls.__dict__["__unicode__"] |
| 14 | - | class Klass(cls): |
| 14 | + | return cls |
| 15 | - | def __init__(self, *args, **kwargs): |
| 15 | + | |
| 16 | - | super(Klass, self).__init__(*args, **kwargs) |
| 16 | + | @decorate |
| 17 | - | print "defining __unicode__" |
| 17 | + | |
| 18 | - | cls.__unicode__ = cls.__str__ |
| 18 | + | |
| 19 | - | print "defining __str__, which uses %s encoding" % self.encoding |
| 19 | + | def __init__(self): |
| 20 | - | cls.__str__ = lambda x: x.__unicode__().encode(self.encoding) |
| 20 | + | self.__dict__["encoding"] = self.encoding |
| 21 | - | return Klass |
| 21 | + | |
| 22 | def __str__(self): | |
| 23 | - | @implements_to_string |
| 23 | + | return "str called".encode(self.encoding) |
| 24 | ||
| 25 | def __unicode__(self): | |
| 26 | return "unicode called" | |
| 27 | ||
| 28 | @property | |
| 29 | - | return "rot13" |
| 29 | + | |
| 30 | """In reality this method extracts the encoding from a file""" | |
| 31 | return "utf-8" # rot13 no longer exists in Python3 | |
| 32 | - | return "str called" |
| 32 | + | |
| 33 | if __name__ == "__main__": | |
| 34 | t = Test() | |
| 35 | if sys.version_info[0] == 2: | |
| 36 | - | print unicode(t) |
| 36 | + | print(unicode(t)) |
| 37 | - | print str(t) |
| 37 | + | print(str(t)) |