In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of "how to use the typing module in Python". The editor shows you the operation process through the actual case. The operation method is simple, fast and practical. I hope this article "how to use the typing module in Python" can help you solve the problem.
Typing Library I. introduction
Python is a weakly typed language. Very often, we may not know the function parameter type or return value type, which may cause some types not to specify a method. If we look back at the code after writing the code for a period of time, we may forget what parameters the function we wrote need to pass and what type of result to return, so we have to read the specific content of the code, which slows down the reading speed. Typing module can solve this problem very well.
The Python runtime does not force the annotation of function and variable types. Type annotations can be used for third-party tools, such as type checker, integrated development environment, static checker, etc.
The main functions of typing are:
Type check to prevent run-time parameter and return value type discrepancies
As an additional description of the development document, it is convenient for the user to pass in and return parameter types when calling
The addition of the module will not affect the operation of the program and will not report formal errors. When pycharm supports typing to check for errors, there will be a yellow warning.
Syntax:
Def function name (parameter: data type)-> return value type: pass variable name: data type = value 2, alias 1, type alias
To define a type alias, you can assign a type to an alias. Type aliases can be used to simplify complex type signatures, while type aliases can be used to simplify complex type signatures.
#! / usr/bin/env python#-*-coding: UTF-8-*-# @ author: A.L.Kun# @ file: test.py# @ time: 2022-5-13 16:54from typing import SequenceConnectionOptions = dict [str, int] # indicates that the key in the dictionary is of string type, and the value of Address = tuple [str, int,...] # indicates that the first data of the tuple is a string, and the second data is an integer Only two pieces of data can be stored in it An ellipsis indicates that n integer data Server = tuple [Address, ConnectionOptions] def broadcast_message (message: str, servers: Sequence [Server] # indicates that [tuple [tuple [str, int], dict [str, int] are stored in a sequence object)-> None: # the return value is empty. Broadcast_message ("a", [("a") 1, 2), {"a": 1})] 2, NewType
Use the NewType helper function to create different types, and the static type checker will treat the new type as a subclass of the original data, which is equivalent to `typedef in C++.
#! / usr/bin/env python#-*-coding: UTF-8-*-# @ author: A.L.Kun# @ file: test.py# @ time: 2022-5-13 16:54from typing import NewTypeUserId = NewType ('UserId', int) # it will not create a new class or introduce other memory Just do a constraint def name_by_id (user_id: UserId)-> str:. Name_by_id (42) # Fails type checkname_by_id (UserId (42)) # OKnum = UserId (5) + 1 # type: int, you can operate on the corresponding data type
At the same time, it can be created nested, that is, you can create a NewType based on NewType
3. Callable object Callable [[Arg1Type, Arg2Type], ReturnType]
For example, a decorator that implements a mutex lock
#! / usr/bin/env python#-*-coding: UTF-8-*-# @ author: A.L.Kun# @ file: test.py# @ time: 2022-5-13 16:54from collections.abc import Callable # Note if you want to use Concatenate and ParamSpec, you must use Callablefrom threading import Lockfrom typing import TypeVarfrom pip._vendor.typing_extensions import Concatenate in this module ParamSpec # Import typing extension P = ParamSpec ('P') # with args and kwargs parameters R = TypeVar ('R') # Custom data type my_lock = Lock () # create a mutex def with_lock (f: Callable [Concatenate [Lock, P], R])-> Callable [P, R]:''one provides a mutex Def inner (* args: P.args, * * kwargs: P.kwargs)-> R: return f (my_lock, * args, * * kwargs) return inner@with_lockdef sum_threadsafe (lock: Lock, numbers: list [float])-> float:''Add a list of numbers together in a thread-safe manner.''' With lock: return sum (numbers) # We don't need to pass in the lock ourselves thanks to the decorator.print (sum_threadsafe ([1.1,2.2,3.3]))
Instead of specifying the call signature, you can declare the return type of the adjustable object by replacing the parameter list in the type prompt: Callable [..., ReturnType] with an ellipsis literal.
Used with Callable and ParamSpec to annotate a high-order callable object that can add, delete, or convert parameters to another callable object. The use form is Concatenate [Arg1Type, Arg2Type,..., ParamSpecVariable]. Concatenate is currently only valid as the first parameter of Callable. The last parameter of Concatenate must be a ParamSpec
III. Generic support
The most basic support for typing module fast consists of Any, Tuple,Callable,TypeVar and Generic types.
1. Generic version of the collection type from typing import (List, # list). Used to comment the return type. To annotate parameters, it is best to use abstract collection types, such as Sequence or Iterable Set, the generic version of # set, the generic version of Dict # dict. It is useful for dimensioning return types. If you want to annotate parameters, using an abstract container type such as Mapping is a better choice. 2. Abstract base class from typing import (Mapping, # the recommended abstract collection type Sequence when you want to annotate the Key-Value type in the function parameter, # when you want to annotate the sequence in the function parameter, such as the list type Recommended abstract collection type Iterable # recommended abstract collection type to annotate iteration types in function parameters) 3. Generics
TypeVar: it's just like template in C++.
#! / usr/bin/env python#-*-coding: UTF-8-*-# @ author: A.L.Kun# @ file: test.py# @ time: 2022-5-13 16:54from typing import (Sequence, TypeVar # restricts multiple variables to the same data type) T = TypeVar ('T') # Can be anything A = TypeVar ('Aids, str, bytes) # Must be str or bytes def repeat (x: t N: int)-> Sequence [T]: "" Return a list containing n references to x. "" Return [x] * ndef longest (x: a, y: a)-> A: "" Return the longest of two strings. "" Return x if len (x) > = len (y) else y
AnyStr
AnyStr is a special type variable AnyStr = TypeVar ('AnyStr', str, bytes) of string and byte types, which is used for functions that can accept any type of string without allowing mixing of different types of strings.
4 、 Any
Special type, indicating that there are no restrictions on the type
Each type is compatible with Any
Any is compatible with every type
Any is a special type. The static type checker treats all types as compatible with Any, and vice versa, and Any is also compatible with all types.
This means that you can perform any operation or method call on a value of type Any and assign it to any variable
As shown below, Python does not perform type checking when assigning a value of type Any to a more specific type. For example, when assigning a to s, the static type checker does not report an error even if s is declared to be of type str and receives an int value at run time
#! / usr/bin/env python#-*-coding: UTF-8-*-# @ author: A.L.Kun# @ file: test.py# @ time: 2022-5-13 16:54from typing import (Any, NoReturn) # indicates that the function does not return a value) def test (s: Any)-> NoReturn: s.item () # will not detect whether there is an item () attribute def test_ (s: object)-> NoReturn: s.item () # will detect whether there is an item attribute in s
When the parameter is untyped, it defaults to Any type
5. Special form 5.1 Type
A variable annotated as C can accept a value of type C. In contrast, a variable annotated as Type [C] can accept a value that is itself a class. More precisely, it accepts C's class objects.
#! / usr/bin/env python#-*-coding: UTF-8-*-# @ author: A.L.Kun# @ file: test.py# @ time: 2022-5-13 16:54from typing import (Type,) class User:... class BasicUser (User):. # Accepts User, BasicUser ... def make_new_user (user_class: Type [User])-> User: return user_class () print (make_new_user (User)) 5.2 Union
Union type; Union [X, Y] means either X or Y. To define a union type, you need to be aware of:
The parameter must be a type and must have at least one parameter.
Can inherit or instantiate a union type.
Union [X, Y] cannot be written as Union [X] [Y].
You can use Optional [X] as an acronym for Union [X, None]-the union type of the union type will be flattened.
The union type of only one parameter collapses to the parameter itself, such as:
Union [int] = = int # The constructor actually returns int
Extra parameters are skipped, such as:
Union [int, str, int] = = Union [int, str]
When comparing federated types, the parameter order is ignored, such as:
Union [int, str] = = Union [str, int] 5.3 Optional
Optional type, optional [X] is equivalent to Union [X, None]
5.4 Tuple
The tuple type, Tuple [X, Y], marks a binary type with the first element of type X and the second element of type Y. The type of empty tuple can be written as Tuple [()]
To express a variable-length tuple of the same type, use literal ellipses, such as Tuple [int,...]. A single Tuple is equivalent to Tuple [Any,...] and then to tuple.
Example: Tuple [int, float, str] represents a triple of integers, floating-point numbers, and strings
5.5 Callable
Callable type; Callable [[int], str] is a function that takes an int argument and returns a str. The syntax of the subscript value must be exactly two values: the parameter list and the return type. The parameter list must be a list of types and ellipses; the return value must be a single type
There is no syntax to represent optional or keyword arguments, and this type of function is rarely used for callback functions. Callable [..., ReturnType] (using literal ellipsis) can be used to prompt a callable object, accept any number of arguments, and return ReturnType. A single Callable is equivalent to Callable [..., Any] and, in turn, to collections.abc.Callable.
This is the end of the content about "how to use the typing module in Python". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.