0

I have a python library in which I have frequently used the following type of code

for i in range(...):
    # code

Now I know that for larger values, range will be a monster.

Hence I want to use xrange instead of range, but at the same time, I do not wish to replace the word "range" with anything else in the lib and wants it to be compatible with python 2.7 and 3.x.

This is the current implementation:

try:
    range = xrange
except NameError:
    pass

Now I have two questions.

  1. Is the above implementation perfect (keeping in mind that the code is not for general purpose use but for a lib which will be maintained by other collaborators as well). If not, please suggest a way to do so (without using any other module)
  2. Please suggest me the code structure (file/directory name in which I should keep the above code and import it wherever necessary)

Thanks.

pokemon
  • 710
  • 1
  • 5
  • 10
  • `from builtins import range`, then use `range`. It'll work and be forward compatible. See [python-future idioms list](http://python-future.org/compatible_idioms.html#xrange). – Dan Jul 11 '16 at 22:56
  • I do not wish to use any extra module (`builtins` not available in python 2.7 by default) – pokemon Jul 11 '16 at 22:58
  • @Dan: The `builtins` module listed there is a third-party library with an extremely confusing name and interface, not something that comes with Python. – user2357112 Jul 11 '16 at 23:05

0 Answers0