0

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Erdem
  • 45
  • 8
  • Type is only an hint, like for `mypy` tool that will check code type, you'll always be able to pass anu data type, this is python ;) – azro Mar 30 '20 at 13:37
  • 1
    See https://stackoverflow.com/q/32557920/3001761 for the first example. These hints are used by IDEs and other tooling. – jonrsharpe Mar 30 '20 at 13:38

1 Answers1

0

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)