对于PyCharm某些库没有自动提示的处理

前言

因为python是动态语言,特别是类似网络请求返回参数,在还没收到请求前都不知道参数类型,导致没法用自动提示,如图:
1381777-dad7f722b805bda9.png

resp没法提示.decode()之类的
pycharm帮助文档有提供类型定义,方便我们自动智能提示

解决方案

1. 指定函数的参数类型:

1381777-f6d9a165874c553f.png

如果为以下则指定param为str类型:

def f(param: str):

如果为以下则指定param为str类型,但可以不传入参数(就是可以为f()):

def f(param: str = None):

如果为以下则指定param为str类型和Bool类型:

def f(param: Union[str, bool]):

如果为以下则可选param为str类型:

def f(param: Optional[str] = None):

2. 指定函数的返回参数类型:

1381777-a401792788905be5.png

但如果如下图就不行,因为Python在定义类之前不允许引用类对象:


1381777-d35746d26de58146.png

所以可以改为:

class ToDo(Base):
    __tablename__ = 'todo'
    id = Column(Integer, primary_key=True)
    title = Column(Text)

    @classmethod
    def list(cls) -> List['ToDo']:
        return session.query(cls).order_by(cls.title)

3. 指定局部变量属性的类型:

1381777-989b8a143888720a.png

4. 预期类型来进行判断操作:

1381777-173985d64805b45c.png

5. python3.6以上版本可用的,转换变量:

3.6之前:

from typing import List, Optional
xs = []  # type: List[Optional[str]]

3.6之后

from typing import List, Optional
xs: List[Optional[str]] = []

注意:以上5种方法,如果光标在想注释的变量上,按快捷键⌥⏎(Alt + Enter),就能用选项选择来快捷生成

6. 运行时(调试)收集对象类型:

File | Settings | Build, Execution, Deployment | Python Debuggerfor Windows and Linux
PyCharm | Preferences | Build, Execution, Deployment | Python Debugger for macOS
把Collect run-time types information for code insight 打开
注意:该选项会把调试运行时间耗时加长!

1381777-d31d1cf8065ac0ae.png

并且在
File | Settings | Editor | General | Smart Keys for Windows and Linux
PyCharm | Preferences | Editor | General | Smart Keys for macOS
Smart Keys中,把【Insert type placeholders in the documentation comment stub】打开
1381777-545dc66857c7e8a4.png

那么在debug模式运行一遍的情况下,对方法调用(Alt+ Enter),选择【 Insert documentation string stub】,就能自动对注释的参数类型进行定义
1381777-b7300cf867dbe4e7.png

1381777-3a39866563bb36b3.png

猜你喜欢

转载自blog.csdn.net/weixin_33738982/article/details/86957297