In python, why import an “object” from an inline module?

To upgrade to python 3, I'm trying to figure out how to write codes in python 2 and python 3. The following code is from python-future.org and illustrates how to create an iterator that is compatible with both versions of python.

 from builtins import object class Upper(object): def __init__(self, iterable): self._iter = iter(iterable) def __next__(self): # Py3-style iterator interface return next(self._iter).upper() # builtin next() function calls def __iter__(self): return self itr = Upper('hello') assert next(itr) == 'H' # compatible style assert list(itr) == list('ELLO') 

The code works fine in python 2, but, to my surprise, if I delete the import statement, I get a TypeError: Upper object is not an iterator error TypeError: Upper object is not an iterator . I often derived my custom classes from object , but I never imported it from inline classes. Why does just importing an object change the behavior of the code?

+5
source share
1 answer

You (indirectly) import from the module future.builtins ; it provides a custom base class of object , which adds special names that point forward.

In Python 2, iterators must have a next() method (as well as __iter__ ); this method has been renamed __next__ in Python 3 . Without using the future.builtins.object version, you just skip the next__next__ provided in Python 2.

See the source code for future.types.newobject.py :

 def next(self): if hasattr(self, '__next__'): return type(self).__next__(self) raise TypeError('newobject is not an iterator') 

Note that builtins will return standard built-in objects, if you use Python 3, the module only returns gaskets such as for Python 2.

You can simply add the same alias:

 class Upper(object): def __init__(self, iterable): self._iter = iter(iterable) def __iter__(self): return self def __next__(self): # Py3-style iterator interface return next(self._iter).upper() # builtin next() function calls next = __next__ # Py2 alias 
+10
source

Source: https://habr.com/ru/post/1246774/


All Articles