pycharm 无法忍受的时间的不透明.struct_time

uqjltbpv  于 2023-04-06  发布在  PyCharm
关注(0)|答案(1)|浏览(105)

为什么pylint和IDE的intellisense功能在识别time.struct_time示例时遇到了困难?下面的代码包含了一些对类、命名元组和类似命名元组的time.struct_time的存在/不存在属性的琐碎测试。在pylint中,一切都按预期工作,IntelliJ和VSCode -除了time.struct_time之外,在每种情况下都会报告对缺失属性的访问-它在这些工具中都不会生成警告或错误。难道他们不知道它是什么,它的属性是什么吗?

import time
from collections import namedtuple

t = time.localtime()
e = t.tm_mday
e = t.bad # this is not reported by linters or IDEs. 

class Clz:
    cvar = 'whee'

    def __init__(self):
        self.ivar = 'whaa'

o = Clz()
e = Clz.cvar
e = o.ivar
e = Clz.bad
e = o.bad

Ntup = namedtuple('Ntup', 'thing')
n = Ntup(thing=3)
e = n.thing
e = n.bad

这个问题的上下文是pipenv中的以下最新bug-

# Halloween easter-egg.          
if ((now.tm_mon == 10) and (now.tm_day == 30))

很明显,传递路径从未被测试过,但典型的静态分析工具似乎也帮不上忙,这对于标准库中的类型来说是很奇怪的。
(Fix可在https://github.com/kennethreitz/pipenv/commit/033b969d094ba2d80f8ae217c8c604bc40160b03上查看全文)

xpcnnkqh

xpcnnkqh1#

time.struct_time是一个用C定义的对象,这意味着它不能被静态地内省。自动完成软件可以解析Python代码,并对类和命名元组支持什么做出合理的猜测,但它们不能对C定义的对象这样做。
大多数系统使用的变通方法是生成存根文件;通常通过在运行时内省对象(导入模块并记录找到的属性)。例如,CodeIntel(Komodo IDE的一部分)使用XML file format called CIX。然而,这更容易出错,因此这样的系统会 * 谨慎行事 *,并且不会显式地将未知属性标记为错误。
如果你使用Python 3编写代码,你可以考虑使用type hinting。对于C扩展,你仍然需要存根文件,但社区现在很擅长维护这些文件。标准库存根文件在project called typeshed中维护。
你必须在你的项目中添加类型提示:

#!/usr/bin/env python3
import time
from collections import namedtuple

t: time.struct_time = time.localtime()
e: int = t.tm_mday
e = t.bad  # this is not reported by linters or IDEs.

class Clz:
    cvar: str = 'whee'
    ivar: str

    def __init__(self) -> None:
        self.ivar = 'whaa'

o = Clz()
s = Clz.cvar
s = o.ivar
s = Clz.bad
s = o.bad

Ntup = namedtuple('Ntup', 'thing')
n = Ntup(thing=3)
e = n.thing
e = n.bad

但是然后flake8 toolflake8-mypy plugin组合将检测坏属性:

$ flake8 test.py
test.py:8:5: T484 "struct_time" has no attribute "bad"
test.py:22:5: T484 "Clz" has no attribute "bad"
test.py:23:5: T484 "Clz" has no attribute "bad"
test.py:28:5: T484 "Ntup" has no attribute "bad"

PyCharm也建立在这项工作的基础上,也许可以检测到相同的无效使用。它肯定是directly supports pyi files

相关问题