Any __future__ imports for xrange range incompatibility?

Writing for Python 2, I always use xrange , but it is renamed to Python 3. Therefore, I mainly write

 if sys.version.startswith('3'): zrange = range else: zrange = xrange 

and use zrange below. Is there a more elegant solution (without depending on a third-party package), for example from __future__ import unicode_literal ?

+6
source share
1 answer

No, there is no import from __future__ for this, and you do not need to use a third-party package. Just catch the name error if xrange not available:

 try: zrange = xrange except NameError: zrange = range 

There is really no need to test versions.

Personally, I would not create a new name, just repeat using xrange in Python 3:

 try: xrange except NameError: xrange = range 

Packages that must support both Python 2 and Python 3 typically create a compat module to handle such bridges. See requests.compat module , for example, where they use the test version only because it limits the number of tests to just one if .

+9
source

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


All Articles