math2001 math2001 - 11 months ago 46
Python Question

What does mean two points and a class after args: def func(value:str)

I don't understand what the

arg: str

def hello(arg: str):
print('do stuff!', arg)


I thought it was specifing a type, but I tried to call hello, and I haven't got any exception. I've tried to call
with an
, no error.

I've done a few test, but I haven't come up with anything...

Any idea about what this is doing?


Answer Source

You are correct def hello(arg: str): does specify a type for the argument. But in Python, it only provides type-hinting. This means that you can theoretically pass any type of instance to the function. Type-hinting is useful for development and for IDEs because it can help the program notify you if you're passing unexpected arguments to a function.

Extra note, these type-hints are stored in the function under __annotations__:

In [1]: def f(arg: int):
   ...:     return arg

In [2]: f.__annotations__
Out[2]: {'arg': int}