| Start |
|---|
| Adding types to a function Let's take an example of a function which receives two arguments and returns a value indicating their sum: By looking at this code, one can not safely and without doubt indicate the type of the arguments for function and with strings: and with other values, such as Due to this dynamic nature of python types, where many are applicable for a given operation, any type checker would not be able to reasonably assert whether a call for this function should be allowed or not. To assist our type checker we can now provide type hints for it in the Function definition indicating the type that we allow. To indicate that we only want to allow Annotations follow the argument name and are separated by a Similarly, to indicate only Apart from specifying the type of the arguments, one could also indicate the return value of a function call. This is done by adding the Now we've indicated that the return value when calling Although type hints are mostly used by type checkers and IDEs, sometimes you may need to retrieve them. This can be done using the |
| Generic Types The |
| NamedTuple Creating a namedtuple with type hints is done using the function NamedTuple from the Note that the name of the resulting type is the first argument to the function, but it should be assigned to a variable with the same name to ease the work of type checkers. |
| Variables and Attributes Variables are annotated using comments: Starting from Python 3.6, there is also new syntax for variable annotations (opens new window). The code above might use the form Unlike with comments, it is also possible to just add a type hint to a variable that was not previously declared, without setting a value to it: Additionally if these are used in the module or the class level, the type hints can be retrieved using Alternatively, they can be accessed by using the |
Class Members and Methods Forward reference of the current class is needed since annotations are evaluated when the function is defined. Forward references can also be used when referring to a class that would cause a circular import if imported. |
Type hints for keyword arguments Note the spaces around the equal sign as opposed to how keyword arguments are usually styled. Syntax
RemarksType Hinting, as specified in |
Read Article
https://develop.horje.com/learn/1434/reference