8

I have a variable typeand 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'
David Scarlett
  • 3,171
  • 2
  • 12
  • 28
Vivek Basappa
  • 353
  • 4
  • 8

3 Answers3

16

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.

Community
  • 1
  • 1
David Scarlett
  • 3,171
  • 2
  • 12
  • 28
  • While I agree that function names shouldn't be retasked as variable names, I can't stand that Python a) allows it, and b) claims so many incredibly common terms as function names. It's wrong to expect Python users to know every single built-in function name and not to use terms like "type" and "range". :( – Rikaelus Jul 19 '19 at 06:57
1

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.

thavan
  • 2,409
  • 24
  • 32
1

It is not a good practice to use builtin functions as variable name. So You can rename your variable name from type to _type

Maninder Singh
  • 829
  • 1
  • 7
  • 13