gpt4 book ai didi

python-3.x - time.struct_time 难以忍受的不透明性

转载 作者:行者123 更新时间:2023-12-04 00:43:44 26 4
gpt4 key购买 nike

为什么 pylint 和 IDE 的智能感知功能无法识别 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 中的以下最新错误 -

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

显然,传递路径从未经过测试,但典型的静态分析工具似乎也无济于事。这对于标准库中的类型来说很奇怪。

(可以在 https://github.com/kennethreitz/pipenv/commit/033b969d094ba2d80f8ae217c8c604bc40160b03 看到完整的修复)

最佳答案

time.struct_time 是用 C 语言定义的对象,这意味着它不能被静态地自省(introspection)。自动完成软件可以解析 Python 代码并合理猜测支持哪些类和命名元组,但它们不能对 C 定义的对象执行此操作。

大多数系统使用的解决方法是生成 stub 文件;通常通过在运行时内省(introspection)对象(导入模块并记录找到的属性)。例如,CodeIntel(Komodo IDE 的一部分)使用 XML file format called CIX .但是,这更容易出错,因此这样的系统宁可谨慎行事,也不会明确地将未知属性标记为错误。

如果您使用 Python 3 编写代码,您可以考虑使用 type hinting .对于 C 扩展,您仍然需要 stub 文件,但社区现在非常擅长维护这些文件。标准库 stub 文件保存在 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 tool结合 flake8-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 .

关于python-3.x - time.struct_time 难以忍受的不透明性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46594779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com