【发布时间】:2020-11-21 01:23:20
【问题描述】:
我有以下 python sn-p 正在生成 MyPy“问题”(在 vscode 中)。
my_struct = MyStruct()
#! set mutable flag to true to place data in our object.
fcntl.ioctl( dev_hand.fileno(), my_ioctl_id, my_struct, True )
错误是:
“ioctl”的参数 3 具有不兼容的类型“my_struct”;预期“联合[int,str]”
MyStruct 是一个 ctypes 结构。使用带有 ctypes 结构的ioctl() 的所有示例都显示将实例传递给ioctl()。确实这确实有效,但现在 MyPy 正在抱怨。
我不希望转换为字节并使用struct 模块手动打包/解包(我认为这是一种解决方案)。
我在 Linux (Debian Buster) 上使用 Python 3.7.3,mypy 0.782
谢谢,布伦丹。
注意:我忘了提到我的代码是针对 Python 2.7,因为它是 Debian Jessie 目标系统的遗留系统。我正在为mypy 使用--py2 开关(必须在Python 3 上运行)。
ioctl()函数有如下签名,貌似来自vscode服务器(远程ssh)ms-python ....typeshed/stdlib/3/fcntl.pyi`
def ioctl(fd: _AnyFile,
request: int,
arg: Union[int, bytes] = ...,
mutate_flag: bool = ...) -> Any: ...
这是一个更完整的代码示例。
from typing import ( BinaryIO, )
import ioctl
import fcntl
from ctypes import ( c_uint32, Structure, addressof )
class Point ( Structure ) :
_fields_ = [ ( 'x', c_uint32 ), ( 'y', c_uint32 ) ]
def ioctl_get_point (
dev_hand,
) :
point = Point()
fcntl.ioctl( dev_hand, 0x12345678, point, True ) #! ** MyPy does NOT complain at all **
def ioctl_get_point_2 (
dev_hand, # type: BinaryIO
) :
point = Point()
fcntl.ioctl( dev_hand, 0x12345678, point, True ) #! ** MyPy complains about arg 3 **
return point
def ioctl_get_point_3 (
dev_hand,
) : # type: (...) -> Point
point = Point()
fcntl.ioctl( dev_hand, 0x12345678, point, True ) #! ** MyPy complains about arg 3 **
return point
def ioctl_get_point_4 (
dev_hand, # type: BinaryIO
) : # type: (...) -> Point
point = Point()
fcntl.ioctl( dev_hand, 0x12345678, point, True ) #! ** MyPy complains about arg 3 **
return point
def ioctl_get_point_5 (
dev_hand, # type: BinaryIO
) : # type: (...) -> Point
point = Point()
fcntl.ioctl( dev_hand, 0x12345678, addressof( point ), True ) #! ** MyPy does NOT complain at all **
return point
对我来说,使用@CristiFati 建议的ctypes.addressof() 函数似乎是最简单的解决方案。
很遗憾,这不起作用。ioctl() 函数需要知道对象的大小。
谢谢,布伦丹。
【问题讨论】:
-
ctypes.addressof(my_struct)? -
您确定您使用的是 Python 3.7.3,并且运行的是 Python 3 版本的 mypy?这看起来像一条 Python 2 错误消息。 (Python 3 mypy 仍然会给你一个错误消息,但它会是一个不同的错误消息。)
-
是的。我在 python2 模式下使用 mypy (
--py2)。我已经用更多信息更新了这个问题。我认为 CristiFati 使用ctypes.addressof()的答案是最简单的解决方案。