Call Built-in Function If Overwritten By A Variable Of The Same Name
Solution 1:
Your type
variable has overwritten* the built-in type
function. But you can still access the original via the __builtin__
module in Python 2, or builtins
in Python 3.
Python 2:
>>> type = "string">>> type("test")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str'objectisnotcallable>>> import __builtin__
>>> __builtin__.type("test")
<type'str'>
Python 3:
>>> type = "string">>> type("test")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str'objectisnotcallable>>> import builtins
>>> builtins.type("test")
<type'str'>
However, it would be better to avoid the need for this by choosing a different variable name.
It's also worth mentioning that it makes no difference that you only assign to type
after attempting to call type
as a function. In Python, a name is bound to a function as a local variable if it is assigned to anywhere within that function (and is not declared global). So even though you only assign to type
in the second line of the function, type
is still a local variable throughout the whole function.
* Strictly speaking, "hidden" would probably be a better description, as the built-in type
function is still there, it's just that Python resolves variables names looking for local definition first, and built-ins last.
Solution 2:
If you assign a value to a variable inside a function, it becomes a local variable in that function. It will no longer refer to it's original global built-in function, even though you assign a new value at the end of the function.
You must be getting this error too.
UnboundLocalError: local variable 'type' referenced before assignment
Best practice is not to override builtin functions or modules.
Solution 3:
It is not a good practice to use builtin functions as variable name. So You can rename your variable name from type to _type
Post a Comment for "Call Built-in Function If Overwritten By A Variable Of The Same Name"