1#function expects a string and returns a string
2def greeting(name: str) -> str:
3 return 'Hello ' + name
1# Some basic type annotations
2#
3# Note that type annotations are not enforced by the interpreter.
4# The code
5# a: int = 5
6# a = "hello"
7# is valid Python.
8
9# A built-in library with some extra types that can be used
10# for annotations
11from typing import Union, Optional, List, Tuple
12
13a: int = 6 # A variable annotated as int
14
15# This denotes a variable that will hold ints and floats over
16# the course of its usage.
17two_types: Union[int, float] = 5.6
18
19# This variable could hold str or it could be None. This is
20# effectively the same as typing opt as Union[str, None].
21opt: Optional[str] = None
22
23# This is a function with type annotations; it takes two
24# int parameters and returns bool.
25def annotated_func(x: int, y: int) -> bool:
26 return x > y
27
28# You can also annotate a certain data structure and the type of
29# data you intend it to contain.
30l: List[int] = [1, 2, 3, 4]
31t: Tuple[chr] = ('a', 'b', 'c', 'd')
32
33# In Python 3.9+, list[<TYPE>] and tuple[<TYPE>] can be used
34# instead. They're aliases for typing.List and typing.Tuple.
1# This example illustrates both parameter and return type annotation
2# Collection annotations are also supported
3from typing import List
4
5def greeting(names: List[str]) -> str:
6 return 'Hello, ' + names[0] ' and ' + names[1]