How do I restore an inline value when a parameter has the same name?

I know you shouldn't use built-in names as parameters for functions, but sometimes they make the most sense:

def foo(range=(4,5), type="round", len=2):

      

But if this has been done and the variable has range

been processed and is no longer needed, how do I go back to the built-in range

and use it internally foo()

?

del range

does not restore inline function:

UnboundLocalError: local variable 'range' referenced before assignment

      

+3


source to share


2 answers


For Python 2.x

import __builtin__
range = __builtin__.range

      



For Python 3.x

import builtins
range = builtins.range

      

+4


source


Also for both python versions you can use __builtins__

without importing anything.

Example -



>>> def foo(range=(4,5)):
...     print(range)
...     range = __builtins__.range
...     print(range)
...
>>> foo()
(4, 5)
<class 'range'>

      

+3


source







All Articles