I have a variable type
and I want to use builtin type()
function
Example
def fun(inv):
log.debug('type of inv {}'.format(type(inv)))
type = 'int'
I get the following error when i run the function:
AttributeError: 'module' object has no attribute 'type'
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. Best practice is not to override builtin functions or modules.
Yes, variables belonging to different function can have same name because their scope is limited to the block in which they are defined.
Builtin functions All Python applications rely on them, and usually don't expect that these functions are overriden. In practice, it is very easy to override them.
@NicolasMiari, local variable with same name will also give a compiler error if he tries to actually call the function: error: called object 'abc' is not a function .
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' object is not callable
>>> 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' object is not callable
>>> 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With