当前位置:网站首页>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 .

f13193452f43296807808a183741feaf.png

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

daa0bbeb98fdb1618ac730c65e9ace7e.png

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 :

f5a7a5f036485b8a66cf28e417e5040d.png

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 :

fb196d8514e271229217f7a324dbbceb.png

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 :

33f3a990e02b2a461c23aa111b7cb8b3.png

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 :

3db083b1c69fed46e2437041d5092a5a.png

600d182e300e1b6d31f8e0f38b49f7ef.png

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

56495ffd4f582813c3e1c2e199f946db.png

Scan purchase

44e6ec1d1bd31fb17abe1b48060dd595.png

f0a250dc3502f80489440978c9e3cb0f.png

You'd better watch it

outside_default.png

原网站

版权声明
本文为[VIP_ CQCRE]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240941503460.html