Search code examples
pythonfunctiondefinition

How does specifying type of input and output in function header or docstring work?


I recently started to learn programming with Python and in some sources I encounter code:

def f(x : int) -> str:

or

def f(x):
    """(int) -> str...."""

When I try the first code it doesn't seem to limit input or output of the function. does that mean they are for code clarity and use of either of them depends personal preference or am I missing something?


Solution

  • does that mean they are for code clarity

    Yes, type hinted code is generally easier to read and understand.

    You can also use third-party tools to check your code. There are two tools that you could use for this: mypy, and pyre.

    If you have a module called example.py:

    def foo(bar: int) -> str:
        return str(bar)
    
    
    foo("hello, world")
    foo(1)
    foo(b'\x00')
    

    You could check it like this:

    $ mypy example.py 
    example.py:5: error: Argument 1 to "foo" has incompatible type "str"; expected "int"
    example.py:7: error: Argument 1 to "foo" has incompatible type "bytes"; expected "int"
    Found 2 errors in 1 file (checked 1 source file)