3

I know you're "not supposed to" use builtin 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 range variable has been processed and is no longer needed, how do I get back to the builtin range and use it inside foo()?

del range doesn't restore the builtin:

UnboundLocalError: local variable 'range' referenced before assignment
Community
  • 1
  • 1
endolith
  • 25,479
  • 34
  • 128
  • 192
  • 1
    Range of what? Range of response times? Range of fuel efficiencies? There should be something you can roll into the name to differentiate from the generic built-in. – TigerhawkT3 Jul 02 '15 at 04:44
  • 1
    Obviously it's a range of `foo`s. ;) – Ethan Furman Jul 02 '15 at 14:02
  • @TigerhawkT3 range of foo, obviously. `foo(foo_range=(4,5))` would be redundant. :) – endolith Jul 02 '15 at 14:04
  • `del range` works at global scope because it removes `range` from the global namespace, and global lookups check the builtin namespace after the global namespace. It does not work at local scope because it removes `range` from the local namespace, but the variable is *still looked up as a local, and only as a local*. – Karl Knechtel Aug 09 '22 at 06:38

2 Answers2

4

For Python 2.x

import __builtin__
range = __builtin__.range

For Python 3.x

import builtins
range = builtins.range
Jens
  • 8,423
  • 9
  • 58
  • 78
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
3

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'>
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176