bodacydo
bodacydo

Reputation: 79309

Can I use the variable name "type" as function argument in Python?

Can I use type as a name for a python function argument?

def fun(name, type):
    ....

Upvotes: 29

Views: 20677

Answers (5)

Shameem
Shameem

Reputation: 2814

You can use _type for that. For example:

def foo(_type):
    pass

If you use type, you can't use type() in that function. For example:

>>> type('foo')
<type 'str'>
>>> type = 'bar'
>>> type('foo')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'str' object is not callable

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798546

You can use any non-keyword as an identifier (as long as it's a valid identifier of course). type is not a keyword, but using it will shadow the type built-in.

Upvotes: 5

jathanism
jathanism

Reputation: 33716

You can, but you shouldn't. It's not a good habit to use names of built-ins because they will override the name of the built-in in that scope. If you must use that word, modify it slightly for the given context.

While it probably won't matter for a small project that is not using type, it's better to stay out of the habit of using the names of keywords/built-ins. The Python Style Guide provides a solution for this if you absolutely must use a name that conflicts with a keyword:

single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

Tkinter.Toplevel(master, class_='ClassName')

Upvotes: 46

Roger Pate
Roger Pate

Reputation:

You can, and that's fine. Even though the advice not to shadow builtins is important, it applies more strongly if an identifier is common, as it will increase confusion and collision. It does not appear type will cause confusion here (but you'll know about that more than anyone else), and I could use exactly what you have.

Upvotes: 8

Francesco
Francesco

Reputation: 3250

You can, but you would be masking the built-in name type. So it's better not to do that.

Upvotes: 2

Related Questions