In order to transition to python 3, I am trying to understand writing python 2 and python 3 compatible codes. The following code is from python-future.org and illustrates a way to construct an iterator that would be 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 runs fine in python 2, but to my surprise, if i remove the import statement then i get an error TypeError: Upper object is not an iterator. I often derive my custom classes from object but i have never imported it from builtins. Why does simply importing object change the behaviour of the code?
builtinsto be pip-installed. It's designed for writing code compatible on Python 2 and 3. - Aaron ChristiansenImportError: No module named builtins. There is a module named__builtin__, and I can dofrom __builtin__ import object, but it makes no difference, I get theTypeError: Upper object is not an iteratoreither way. Which makes sense, because in Python 2 you implementnext, not__next__, to be an iterator. I think the code sample you are reading is just wrong. Could you please post a direct link to it? Also please tell us exactly which versions of Python 2 and 3 you are testing with. - zwolobjectavailable in the default namespace and the one that is imported frombuiltins? - deepakbuiltinsis another forward-compatibility bolt-on likesix? I'm not finding it on PyPI, where do you get it? - zwol