utilities.rst 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. .. _utilities-guide:
  2. Utilities
  3. ---------
  4. :mod:`future` also provides some useful functions and decorators to ease
  5. backward compatibility with Py2 in the :mod:`future.utils` and
  6. :mod:`past.utils` modules. These are a selection of the most useful functions
  7. from ``six`` and various home-grown Py2/3 compatibility modules from popular
  8. Python projects, such as Jinja2, Pandas, IPython, and Django. The goal is to
  9. consolidate these in one place, tested and documented, obviating the need for
  10. every project to repeat this work.
  11. Examples::
  12. # Functions like print() expect __str__ on Py2 to return a byte
  13. # string. This decorator maps the __str__ to __unicode__ on Py2 and
  14. # defines __str__ to encode it as utf-8:
  15. from future.utils import python_2_unicode_compatible
  16. @python_2_unicode_compatible
  17. class MyClass(object):
  18. def __str__(self):
  19. return u'Unicode string: \u5b54\u5b50'
  20. a = MyClass()
  21. # This then prints the Chinese characters for Confucius:
  22. print(a)
  23. # Iterators on Py3 require a __next__() method, whereas on Py2 this
  24. # is called next(). This decorator allows Py3-style iterators to work
  25. # identically on Py2:
  26. @implements_iterator
  27. class Upper(object):
  28. def __init__(self, iterable):
  29. self._iter = iter(iterable)
  30. def __next__(self): # note the Py3 interface
  31. return next(self._iter).upper()
  32. def __iter__(self):
  33. return self
  34. print(list(Upper('hello')))
  35. # prints ['H', 'E', 'L', 'L', 'O']
  36. On Python 3 these decorators are no-ops.