I’m working on a python program and the author has written a function that looks like this
def blah(): str = "asdf asdf asdf" doStuff(str)
This seems to work, even though str is a built in function and shouldn’t be used as a variable.
What is actually happening here? My guess is str will no longer be usable as a function, but only in the scope of the blah() function he’s written. Is that correct? This won’t redefine str globally, right?
Advertisement
Answer
Internally, the function’s local variable table will contain an entry for str
, which will be local to that function. You can still access the builtin class within the function by doing builtins.str
in Py3 and __builtin__.str
in Py2. Any code outside the function will not see any of the function’s local variables, so the builtin class will be safe to use elsewhere.
There is another caveat/corner case here, which is described in this question. The local table entry is created at compile-time, not at runtime, so you could not use the global definition of str
in the function even before you assign "asdf asdf asdf"
to it:
def blah(): x = str(12) str = "asdf asdf asdf" doStuff(str)
will fail with an UnboundLocalError
.