当前位置:网站首页>Any and typevar make the automatic completion of IDE better
Any and typevar make the automatic completion of IDE better
2022-06-24 11:00:00 【VIP_ CQCRE】
This is a 「 Attacking Coder」 Of the 650 Technology sharing
author :kingname
source : Unheard of Code
“
It is necessary to read this article 6 minute .
” I believe many students are writing Python When , Will use type annotations to improve code readability , It also helps IDE Realize automatic completion .
Suppose we now have an object , This object can be a list or a generator , I write a function , Get its first element . The code is simple :
from typing import Iterator
from contextlib import suppress
class People:
def __init__(self, name):
self.name = name
def eat(self):
print(f'{self.name} I am eating ')
def walk(self):
print(f'{self.name} Walking ')
def get_first_element(ele_list):
if isinstance(ele_list, list):
return ele_list[0] if ele_list else None
if isinstance(ele_list, Iterator):
with suppress(Exception):
value = next(ele_list)
return value
return None
if __name__ == '__main__':
kingname = People('kingname')
pm = People('pm')
people_list = [kingname, pm]
obj = get_first_element(people_list)
if obj:
print(obj.)The code is written , But when I get the first element , When you want to print the data in it , I found that I had forgotten People What properties does this class have , And then PyCharm The automatic completion of is also invalid , I had to turn the code back , Go looking for People Defined location , Very inefficient . As shown in the figure below .

If we use type notation , We can solve this problem :

This general usage , Everyone must know .
Now comes the question , We have nothing but People class , also Cat class , And the elements in the list may be all People Class , Maybe it's all Cat Class instance , What about this situation ?
First you have the first problem ,get_first_element How to write the type label of the parameter of ?
You might write like this :
def get_first_element(ele_list: Union[List[Union[People, Cat]], Iterator[Union[People, Cat]]]) If there is another one Dog Class? ?
To simplify the operation , You may use Any, type , therefore get_first_element It's like this :
def get_first_element(ele_list: Union[List[Any], Iterator[Any]]) -> Optional[Any]:
if isinstance(ele_list, list):
return ele_list[0] if ele_list else None
if isinstance(ele_list, Iterator):
with suppress(Exception):
value = next(ele_list)
return value
return NoneNow you find the problem again ,PyCharm The automatic completion of is broken again . because Any It's any kind of , So before the code runs , It doesn't know what you're returning . As shown in the figure below :

In this case , You need to use Python In type annotations Generic 了 . We know , Generics are a concept in static languages ,Python Because of the use of type annotations , There are also types . So I borrowed this concept .
Let's see how to use it :
from typing import TypeVar
T = TypeVar('T') Notice the variable name here T and TypeVar Parameters of 'T' It can be written as any string at the same time , But the variable name should be consistent with the parameter . for example :
GodType = TypeVar('GodType') And then put T As Any Just use the same . Let's see the effect :

You can see ,PyCharm It can be completed automatically again . Use TypeVar, You can tell PyCharm, The returned type is the same as that in the passed in parameter T The type of corresponding position shall be consistent . For example, in the passed in parameter ,T stay List[T] perhaps Generator[T] in , Therefore, the returned parameters should be consistent with the elements in the list or the element types in the generator .
We use it Cat Generator to test , Discovery can also be completed automatically :

There's more , If my list has Cat Example , And then there is People What about the instance of ? This is the time ,PyCharm I will list all the possible complements of the two examples :


End
Cui Qingcai's new book 《Python3 Web crawler development practice ( The second edition )》 It's officially on the market ! The book details the use of zero basis Python Develop all aspects of reptile knowledge , At the same time, compared with the first edition, it has added JavaScript reverse 、Android reverse 、 Asynchronous crawler 、 Deep learning 、Kubernetes Related content , At the same time, this book has obtained Python The father of Guido The recommendation of , At present, this book is on sale at a 20% discount !
Content introduction :《Python3 Web crawler development practice ( The second edition )》 Content introduction

Scan purchase


You'd better watch it

边栏推荐
- Spark submission parameter -- use of files
- What is the resource search platform and how resource search works
- Common third-party UI frameworks
- Lightweight deployment of firefoxsend temporary file sharing service using Tencent cloud
- Quick completion guide for manipulator (III): mechanical structure of manipulator
- 使用Process Monitor工具监测进程对注册表和文件的操作
- Canvas pipe animation JS special effect
- Many of my friends asked me what books and online classes I recommended. This time, I contributed all the materials that I had been hiding for a long time (Part 1)
- SQL Server about like operator (including the problem of field data automatically filling in spaces)
- Tencent's open source project "Yinglong" has become a top-level project of Apache: the former long-term service wechat payment can hold a million billion level of data stream processing
猜你喜欢

Programmers spend most of their time not writing code, but...

Quick completion guide for mechanical arm (I): development overview of mechanical arm

Differences among cookies, session, localstorage and sessionstorage

机械臂速成小指南(一):机械臂发展概况

把騰訊搬到雲上,治愈了他們的技術焦慮

服乔布斯不服库克,苹果传奇设计团队解散内幕曝光

Déplacer Tencent sur le cloud a guéri leur anxiété technologique

SQL Server about like operator (including the problem of field data automatically filling in spaces)

Any 与 TypeVar,让 IDE 的自动补全更好用

Canvas falling ball gravity JS special effect animation
随机推荐
历史上的今天:图灵诞生日;互联网奠基人出生;Reddit 上线
Preparation for a series of courses on WordPress applet generation
"Adobe international certification" Adobe Photoshop adjusts cropping, rotation and canvas size
Common third-party UI frameworks
How to use arbitrarygen code generator what are the characteristics of this generator
Centripetalnet: more reasonable corner matching, improved cornernet | CVPR 2020 in many aspects
Niuke-top101-bm28
Which map navigation is easy to use and accurate?
88. merge ordered arrays
Petit guide de construction rapide du bras mécanique (II): application du bras mécanique
Use the process monitor tool to monitor process operations on registries and files
Base64 decoding method three ways for non professionals
js数组求和的5种方法
What is the knowledge map? What does it do
Detailed explanation of SQL Sever basic data types
Flink checkpoint and savepoint
Stack Title: exclusive time of function
Canvas falling ball gravity JS special effect animation
喜欢就去行动
What characteristics should a good design website have?