Compatibility of python library for range and xrange

时间:2016-07-11 22:49:45

标签: python python-2.7 python-3.x code-maintainability

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.

0 个答案:

没有答案