|
1 | 1 | # Annotations for Python Functions |
2 | 2 | # ------------------------------------------------------------------------------ |
3 | | -# Annotations in Python functions allow you to specify the expected types of |
4 | | -# parameters and the return type of the function. This can help with code |
5 | | -# readability and static type checking. |
| 3 | +# Annotations were introduced in Python 3.0 and allow developers to attach |
| 4 | +# metadata to function parameters and return values. The metadata can be of |
| 5 | +# any type, but it is commonly used to indicate the expected data types of |
| 6 | +# parameters and the return value of a function. |
6 | 7 | # |
7 | | -# There are no strict rules enforced by Python regarding these A13_type_hints, |
8 | | -# but they serve as a guide for developers and can be used by tools like |
9 | | -# type checkers, IDEs, and documentation 01_generators. |
| 8 | +# Annotations are not enforced at runtime, but they can be used by static |
| 9 | +# type checkers, IDEs, and documentation generators to provide better |
| 10 | +# support for developers. The annotations are stored in the `__annotations__` |
| 11 | +# attribute of the function object. |
| 12 | + |
10 | 13 |
|
11 | 14 | def add(x: int, y: int) -> int: |
12 | 15 | return x + y |
| 16 | + |
| 17 | +def sub(x: "int", y: "int") -> "int": |
| 18 | + return x - y |
| 19 | + |
| 20 | +print(add.__annotations__) |
| 21 | +# Output: {'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>} |
| 22 | + |
| 23 | +print(sub.__annotations__) |
| 24 | +# Output: {'x': 'int', 'y': 'int', 'return': 'int'} |
0 commit comments