4

I believe types can be specified in Python as is mentioned here: https://docs.python.org/3/library/typing.html

I am using following simple function modified from one on above page:

def greeting(name: str) -> str:
    print("From inside function.")
    return 'Hello ' + name

As expected, it works when a string is sent as argument. However, when an integer is used as an argument, it still reaches inside the function and there is error thrown at return statement level:

> print(greeting(55))
From inside function.
Traceback (most recent call last):
  File "testing.py", line 16, in <module>
    print(greeting(55))
  File "testing.py", line 13, in greeting
    return 'Hello ' + name
TypeError: Can't convert 'int' object to str implicitly

Same error occurs if the function definition does not have type specification:

def greeting(name):

Then what is the advantage of having type specification in function header?

def greeting(name: str) -> str:
rnso
  • 23,686
  • 25
  • 112
  • 234
  • 1
    [***"Python will remain a dynamically typed language"***](https://www.python.org/dev/peps/pep-0484/#non-goals) - those hints are for humans, and tools *other than* the interpreter. – jonrsharpe Apr 13 '19 at 12:36

1 Answers1

3

Python is dynamically typed; at run time name can be any value. The function annotations only provide type hints, which Python itself ignores but other tools can use for static type checking. That is, at runtime, greeting(4) is perfectly legal (but results in a run-time error when you try to evaluate 'Hello' + 4). A tool like mypy, however, will flag greeting(4) as an error because 4 is, indeed, not the str that you said name should take.

Think of the type hints as parseable and machine-checkable comments.

doc.python about type hints

Kobap Bopy
  • 61
  • 8
chepner
  • 497,756
  • 71
  • 530
  • 681