Python - typing module - common type tips


typing is a module only available in python 3.5

Pre learning

Python type prompt:

Common type tips

  • int,long,float: integer, long integer, float;
  • bool,str: Boolean, string type;
  • List, Tuple, Dict, Set: list, tuple, dictionary, set;
  • Iteratable, iterator: iteratable type, iterator type;
  • Generator: generator type;

The first two lines of lowercase do not need to be imported, and the last three lines need to be imported through the typing module

Common type tips chestnut

Specifies the function parameter type

Single parameter

# The name parameter type is str
def greeting(name: str) :
    return "hello"


Multiple parameters

# Multiple parameters with different parameter types
def add(a: int, string: str, f: float, b: bool or str):
    print(a, string, f, b)

bool or str: represents that the parameter b can be Boolean or string

Specifies the type of parameter returned by the function

Simple chestnut

# The return value of the function is specified as a string
def greeting(name: str) -> str:
    return "hello"


More complicated chestnuts

from typing import Tuple, List, Dict

# Returns data of Tuple type. The first element is List, the second element is Tuple, the third element is Dict, and the fourth element can be string or Boolean
def add(a: int, string: str, f: float, b: bool or str) -> Tuple[List, Tuple, Dict, str or bool]:
    list1 = list(range(a))
    tup = (string, string, string)
    d = {"a": f}
    bl = b
    return list1, tup, d, bl

# The call writing method of warn is not supported
print(add(1, "2", 123, True))

# Output results
([0], ('2', '2', '2'), {'a': 123}, True)


List, Set, Dict source code

As you can probably guess, their bottom layer is related to list, set and dict

Tuple source code

It's different from the other three, but it's also related to tuple

Can I use list, set, dict and tuple when specifying types?

Yes, but the data type of the element cannot be specified

def test(a: list, b: dict, c: set, d: tuple):
    print(a, b, c, d)

List[T] and Set[T] can only pass one type. If you pass more than one type, an error will be reported

a: List[int, str] = [1, "2"]
b: Set[int, str] = {1, 2, 3}

IDE will not report an error, but it will report an error at runtime

Traceback (most recent call last):
  File "/Users/polo/Documents/pylearn/Chapter II: Foundation/", line 36, in <module>
    a: List[int, str] = [1, "2"]
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/", line 261, in inner
    return func(*args, **kwds)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/", line 683, in __getitem__
    _check_generic(self, params)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/", line 215, in _check_generic
    raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
TypeError: Too many parameters for typing.List; actual 2, expected 1

List passed too many parameters, expected 1, actual 2

Will Tuple[T] report an error if it passes more than one?

d: Tuple[int, str] = (1, "2")

# Output results
(1, '2')

You can't report an error

Let's look at the various ways Tuple[T] is written

If only one int is written and two int elements are assigned, warning will be reported

What if Tuple[T] specifies the number of types and the number of assigned elements are inconsistent?

d: Tuple[int, str] = (1, "2", "2") 

No error will be reported, but there will also be warning

To sum up the two chestnuts, draw a conclusion

Tuple[T] when specifying a type, it is only for the element type under the same index

If you want to specify a type like List[T], it can be effective for all elements

d: Tuple[int, ...] = (1, 2, 3)
d: Tuple[Dict[str, str], ...] = ({"name": "poloyy"}, {"age": "33"})

Specify a type followed by All right

This article is from:

Python - typing module - common type tips - small pineapple test notes - blog Garden

Type alias 



Python - typing module - Callable - little pineapple test notes - blog Garden

TypeVar generics

Python - typing module - TypeVar generics - little pineapple test notes - blog Garden

Any Type

Python - typing module - Any Type - small pineapple test notes - blog Garden


Python - typing module - Union - little pineapple test notes - blog Garden


Python - typing module - Optional - small pineapple test notes - blog Garden

Keywords: Python

Added by manmanman on Wed, 05 Jan 2022 06:12:50 +0200