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

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


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

解决方案


1. 指定函数的参数类型


如果为以下则指定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. 指定函数的返回参数类型


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


所以可以改为:

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. 指定局部变量属性的类型

4. 预期类型来进行判断操作:【个人感觉这个比较好用

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 打开
注意:该选项会把调试运行时间耗时加长!

并且在
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】打开


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

--------------------- 
作者:?Briella 
来源:CSDN 
原文:https://blog.csdn.net/weixin_33738982/article/details/86957297 
版权声明:本文为博主原创文章,转载请附上博文链接!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值