Before you dive in, here is my question: how can I use type hints in a subclass to specify a different type on an instance attribute?
If you are unclear on what that means, read below, where I have drawn up an example to clarify things.
Full Explanation
I have an abstract class Foo
, and a subclass of Foo
called SubclassOfFoo
.
Foo
has an abstract method get_something
that returns an object of type Something
.
Something
has a …
首先,我想说如果有人可以在这里提供帮助,您真是不可思议。
一般问题
我的Python程序需要与MSMQ进行交互。基本上,我想窥视一个队列,如果队列中没有任何内容,则指定一个超时。
但是,尽管我已尽力而为,但当队列中先前没有任何值时,我无法让Peek()等待超时间隔。 您能否指出此代码中缺少的内容?
我当前的代码
现在是我的代码:
from socket import gethostname
import win32com.client
import pythoncom
import clr
clr.AddReference("System")
clr.AddReference("System.Messaging")
from System import TimeSpan
from System.Messaging import MessageQueue
# Source: [1]
# [1] https://docs.microsoft.com/en-us/previous-versions/windows/desktop/msmq/ms707027%28v%3dvs.85%29
MQ_DENY_NONE = 0x0
MQ_PEEK_ACCESS = 0x1
MQ_SEND_ACCESS = 0x2
# Set up queue
pythoncom.CoInitialize()
qinfo = win32com.client.Dispatch("MSMQ.MSMQQueueInfo")
qinfo.FormatName = f"direct=os:{gethostname()}\\PRIVATE$\\MyQueue"
queue = qinfo.Open(MQ_PEEK_ACCESS, MQ_DENY_NONE)
# Receive a value
timeout_sec = 1.0
timespan = TimeSpan.FromSeconds(timeout_sec)
label, body = "", ""
# TODO: timeout value does not appear working. …
Run Code Online (Sandbox Code Playgroud) 当传递函数时,我通常用 来提示它们typing.Callable
。
的文档声明collections.abc.Callable
它有四种 dunder 方法:
类 collections.abc.Callable
分别提供方法
__contains__()
、__hash__()
、__len__()
和的类的 ABC__call__()
。
有一次,我想检查__wrapped__
函数上是否有属性。通过检查,这在运行时工作得很好hasattr(func, "__wrapped__")
。
当使用 进行静态类型检查时mypy
,它会报告:error: "Callable[..., Any]" has no attribute "__wrapped__" [attr-defined]
。这对我来说很有意义,因为Callable
不应该有__wrapped__
属性。
如何正确输入Callable
带有__wrapped__
属性的提示 a?我可以做一些其他类型的提示或解决方法吗?
代码示例
我正在使用mypy==0.782
和Python==3.8.2
:
from functools import wraps
from typing import Callable
def print_int_arg(arg: int) -> None:
"""Print the integer argument."""
print(arg)
@wraps(print_int_arg)
def wrap_print_int_arg(arg: int) -> None: …
Run Code Online (Sandbox Code Playgroud) 总是setuptools
安装Python吗?
我想在脚本setuptools
之外的运行时调用setup.py
。
换句话说,我应该包含setuptools
在我的包的requirements.txt
和setup.py
列表中install_requires
吗?
背景
我注意到在创建新的虚拟环境(使用 Python 3.7.9)时,默认安装了pip
和:setuptools
python -m venv venv
source ./venv/bin/activate
pip list
Package Version
---------- -------
pip 20.1.1
setuptools 47.1.0
Run Code Online (Sandbox Code Playgroud)
这记录在此处:创建虚拟环境:
venv 在 Python 3.3 及更高版本中默认可用,并将 pip 和 setuptools 安装到 Python 3.4 及更高版本中创建的虚拟环境中。
即使在 Python 3.7.6 的普通版本中(通过安装pyenv
),默认安装的包也是pip
和setuptools
。
研究
setuptools 应该包含在 Python 的 setup_requires 中吗?
通知setuptools
不应包含在 中setup_requires
,但没有谈论将其包含在运行时使用的包要求中。
pytest
我正在尝试在我的 Mac 终端中使用。我没有pytest.ini
设置,现在也不想进行设置。
当我单独运行该命令时pytest
,它会DeprecationWarning
为我的虚拟环境(名为venv
,位于我的项目根目录中)中的多个站点包打印警告 ( )。
venv/lib/python3.6/site-packages/eventlet/patcher.py:1
/path/to/venv/lib/python3.6/site-packages/eventlet/patcher.py:1: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
import imp
Run Code Online (Sandbox Code Playgroud)
我想venv/
在运行时忽略该目录pytest
,因此我的警告仅与我的项目相关。
我如何无法在pytest
我的虚拟环境中运行?
我尝试过的
我尝试过该--ignore
标志的多个版本:
venv/lib/python3.6/site-packages/eventlet/patcher.py:1
/path/to/venv/lib/python3.6/site-packages/eventlet/patcher.py:1: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
import imp
Run Code Online (Sandbox Code Playgroud)
(来源)
并使用-k
pytest --ignore=venv
pytest --ignore=./venv/
pytest …
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用pySerial==3.4
,并发现相当缺乏的文档serial.Serial.flush()
:
文件类对象的刷新。在这种情况下,请等待所有数据写入。
问题
flush
而不是单独重置输入/输出缓冲区?serial = Serial("COM3")
# Option 1
serial.flush()
# Option 2
serial.reset_input_buffer()
serial.reset_output_buffer()
Run Code Online (Sandbox Code Playgroud)
相关问题
我正在尝试根据错误代码消除 mypy 错误。这是使用这样的东西完成的:
from foolib import foo # type: ignore[attr-defined]
Run Code Online (Sandbox Code Playgroud)
我相信 PyCharm 将我的type: ignore[code]
评论解释为类型评论,并将报告ignore
作为未解决的参考。
此外,PyCharm 需要括号内的表达式。
mypy
我试图抑制的错误:
pylint_ignore.py:8: error: Skipping analyzing 'pylint.utils': found module but no type hints or library stubs [import]
Run Code Online (Sandbox Code Playgroud)
是的,我知道我可以只说type: ignore
,而不包含代码,或者指定忽略配置文件中的这个特定导入。但是,我想指定错误代码,因为我认为这是一个很好的功能。
我怎样才能让 PyCharm 不抱怨这个?
研究
帮我实现下Preferences --> Editor --> Inspections --> Python --> Unresolved references
,我可以添加一个完全限定的符号名称来忽略。
我相信这是正式记录在这里。
我尝试添加*.ignore.*
(因为我不想建立每个模块的忽略列表),但这不起作用。
如果这是正确的方法,你能帮我找出正确的语法吗?
版本
mypy==0.770
python==3.6.5
PyCharm PE 2020.1
Run Code Online (Sandbox Code Playgroud) 我通常使用unittest.mock.Mock
的wraps
功能来创建功能齐全的间谍对象。
这是一个运行时运行良好的示例:
from threading import Event
from typing import Union
from unittest.mock import Mock
spy_event: Union[Mock, Event] = Mock(wraps=Event())
spy_event.set()
assert spy_event.is_set()
# How can I type hint so this error doesn't show up from mypy?
spy_event.set.assert_called_once_with() # error: Item "function" of
# "Union[Any, Callable[[], None]]" has no attribute "assert_called_once_with"
Run Code Online (Sandbox Code Playgroud)
您可以看到,Union[Mock, Event]
类型提示不起作用。
如何正确输入提示包裹在 a 中的对象Mock
?
版本
Python==3.8.6
mypy==0.812
Run Code Online (Sandbox Code Playgroud) 我一直试图理解TypeVar
以两种不同方式使用它时的边界:
Enums = TypeVar("Enums", Enum1, Enum2)
Enums = TypeVar("Enums", bound=Union[Enum1, Enum2])
这是我正在使用的代码:
#!/usr/bin/env python3.6
"""Figuring out why enum is saying incompatible return type."""
from enum import IntEnum, EnumMeta
from typing import TypeVar, Union
class Enum1(IntEnum):
MEMBER1 = 1
MEMBER2 = 2
class Enum2(IntEnum):
MEMBER3 = 3
MEMBER4 = 4
# Enums = TypeVar("Enums", bound=Union[Enum1, Enum2]) # Case 1... Success
Enums = TypeVar("Enums", Enum1, Enum2) # Case 2... error: Incompatible return value
def _enum_to_num(val: int, cast_enum: EnumMeta) -> Enums: …
Run Code Online (Sandbox Code Playgroud) 我为重复的代码片段启用了 PyCharm 检查(检查 --> 常规 --> 重复的代码片段)。
我正在尝试使用noinspection
标签在我的 Python 代码中本地禁用此检查。但是,我无法弄清楚 noinspection 标签。它没有记录在我常用的来源中:pylover/inspections.txt
有人知道吗?
我尝试过的
不起作用的选项:
# noinspection Duplicates
//noinspection Duplicates
(这不适用于Python)# SuppressWarnings("Duplicates")
# noinspection DuplicatedCode
(来自JetBrains YouTrack PY-38309)我不想取消检查,我只是想能够局部抑制它。
我还尝试运行pylover/inspections.txt中记录的命令:
unzip -p lib/pycharm.jar com/jetbrains/python/PyBundle.properties | grep -B1 INSP.NAME | grep '^#' | sed 's|Inspection||g' | sed -e 's|#\s\{,1\}|# noinspection |'
Run Code Online (Sandbox Code Playgroud)
我在那里没有看到任何重复的内容。
版本