math2001 math2001 - 1 month ago 6
Python Question

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

I don't understand what the

arg: str
means

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


hello('something')


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
hello
with an
int
, no error.

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

Any idea about what this is doing?

Matt

Answer

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}
Comments