当前位置:网站首页>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 None
Now 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
边栏推荐
- Process and multithreading
- 程序员大部分时间不是写代码,而是。。。
- How to use arbitrarygen code generator what are the characteristics of this generator
- 23. opencv - image mosaic project
- Mongodb index operation
- 栈题目:括号的分数
- Hill sorting graphic explanation + code implementation
- Fashionable pop-up mode login registration window
- How to convert an array to an object, and how to convert an object to an array
- 解决DBeaver SQL Client 连接phoenix查询超时
猜你喜欢
Today's sleep quality record 76 points
Quick completion guide for mechanical arm (I): development overview of mechanical arm
把騰訊搬到雲上,治愈了他們的技術焦慮
Quick completion guide for mechanical arm (II): application of mechanical arm
MYSQL_ Elaborate on database data types
JMeter interface test tool foundation - sampler (II)
“一个优秀程序员可抵五个普通程序员!”
2022 the most complete and detailed JMeter interface test tutorial and detailed interface test process in the whole network - JMeter test plan component (thread < user >)
Quick completion guide for mechanical arm (zero): main contents and analysis methods of the guide
把腾讯搬到云上,治愈了他们的技术焦虑
随机推荐
机械臂速成小指南(一):机械臂发展概况
Lightweight deployment of firefoxsend temporary file sharing service using Tencent cloud
System design: load balancing
[Qianfan 618 countdown!] IAAs operation and maintenance special preferential activities
Maui's way of learning -- Opening
Ppt drawing related, shortcut keys, aesthetics
[net action!] Cos data escort helps SMEs avoid content security risks!
26. delete duplicates of ordered array
Can text pictures be converted to word? How to extract text from pictures
机械臂速成小指南(零):指南主要内容及分析方法
[latest in the whole network] how to start the opentsdb source code in the local ide run
Canvas falling ball gravity JS special effect animation
What is wireless WiFi? What are the benefits of wireless WiFi
Déplacer Tencent sur le cloud a guéri leur anxiété technologique
Five methods of JS array summation
Spark submission parameter -- use of files
Act as you like
The nodejs service global timeout callback failed to get process Domain problem
Extremenet: target detection through poles, more detailed target area | CVPR 2019
Today's sleep quality record 76 points