我的 mypy 遇到一些问题。
我有一个抽象类和一个继承它的类:
from __future__ import annotations
from abc import abstractmethod, ABC
from typing import Union
class Base(ABC):
@abstractmethod
def the_method(self, a_class: Union[Base, float, int]) -> None:
...
@abstractmethod
def other_method(self) -> None:
...
class MyClass(Base):
def __init__(self, something: str = "Hello") -> None:
self.something = something
def the_method(self, a_class: Union[MyClass, float, int]) -> None:
print(a_class)
def other_method(self) -> None:
print(self.something)
Run Code Online (Sandbox Code Playgroud)
我知道里氏替换原则。然而MyClass是 的一种类型,Base因为它继承自它。但mypy仍然会引发错误:
from __future__ import annotations
from abc import abstractmethod, …Run Code Online (Sandbox Code Playgroud) 我如何声明一个数组(或至少是列表)@dataclass?类似于下面的内容:
from dataclasses import dataclass
@dataclass
class Test():
my_array: Array[ChildType]
Run Code Online (Sandbox Code Playgroud) python type-hinting python-3.x python-dataclasses python-typing
所以我知道Python的typing.Optional. 但我编写了自己的粗略代码PyOptional(此处为代码),并希望Optional[T]与我的PyOptionalto结合起来PyOptional[T]。
我目前正在使用 Python 3.7 并尝试扩展typing.Optional.
我的一些PyOptional:
class PyOptional:
T: TypeVar = TypeVar("T")
def __init__(self, obj: T):
self.value: Any = obj
def get(self) -> Optional[T]:
return self.value
def or_else(self, default) -> T:
return self.value or default
Run Code Online (Sandbox Code Playgroud)
我想要的伪代码:
def find_user_by_id(id: int) -> PyOptional[User]:
return PyOptional(db.find_user_by_id(id))
Run Code Online (Sandbox Code Playgroud)
我的目标是让 IDE 能够检查预期的返回类型,并且仍然能够在返回的对象上调用我的方法。因此它必须符合 PEP 要求。
我有一些自动生成的代码,它定义了许多具有通用属性的类,例如不幸的是,它们没有基类、接口等。
class A:
errors = []
class B
errors = []
Run Code Online (Sandbox Code Playgroud)
我该如何描述一种类型?我不能轻易改变所有这些类型。
def validate(obj: ???):
if errors:
raise Exception("something wrong")
Run Code Online (Sandbox Code Playgroud) 是否可以创建访问可变长度参数类型的泛型类型?
基本上,我正在尝试创建一个通用的 observable,用户可以在其中定义他们想要使用类型提示接受的参数。
前任:
Types = TypeVar("Types", var_length=True)
class Obserable(Generic[Types]):
def subscribe(func: Callable[[Types], None]):
...
def notify(*args: Types):
...
def callback(arg1: int, arg2: str, arg3: int) -> None:
...
observer: Observable[int, str, int] = Observable()
observer.subscribe(callback)
observer.notify(1, "hello", 5)
Run Code Online (Sandbox Code Playgroud) 我想从未绑定的TypedDict子类中获取密钥。
这样做的正确方法是什么?
下面我有一个hacky方法,我想知道是否有更标准的方法。
当前方法
我inspect.getmembers在TypedDict子类上使用,并看到__annotations__属性包含键 + 类型注释的映射。从那里,我.keys()用来访问所有密钥。
from typing_extensions import TypedDict
class SomeTypedDict(TypedDict):
key1: str
key2: int
print(SomeTypedDict.__annotations__.keys())
Run Code Online (Sandbox Code Playgroud)
印刷: dict_keys(['key1', 'key2'])
这确实有效,但我想知道,有没有更好/更标准的方法?
版本
python==3.6.5
typing-extensions==3.7.4.2
Run Code Online (Sandbox Code Playgroud) 在 Python 类型中,循环依赖可以通过前向引用来解决:
class A:
b: "B"
def __init__(self, b: "B"):
self.b = b
class B:
a: A
def __init__(self):
self.a = A(self)
Run Code Online (Sandbox Code Playgroud)
mypy 将成功进行类型检查。
但是,如果我将A和拆分B为单独的文件/模块:
a.py:
class A:
b: "B"
def __init__(self, b: "B"):
self.b = b
Run Code Online (Sandbox Code Playgroud)
b.py:
from .a import A
class B:
a: A
def __init__(self):
self.a = A(self)
Run Code Online (Sandbox Code Playgroud)
并使用 mypy 检查模块或包,它失败:
$ mypy -p tt
tt/a.py:2: error: Name 'B' is not defined
tt/a.py:4: error: Name 'B' is not defined
Run Code Online (Sandbox Code Playgroud)
除了将两者放在同一个文件中之外,还有其他方法可以解决这个问题吗?
(使用Python 3.8.4测试) …
是否可以在 python 中编写一个 typehint 来保证 ifNone被赋予函数然后None返回?
例如,这是可能的:
\nfrom typing import Dict, Union\ndef getMaybe(dictionary: Optional[Dict], key: str) -> Optional[str]:\n if dictionary is None:\n return dictionary\n\n return dictionary.get(key)\nRun Code Online (Sandbox Code Playgroud)\n但即使我知道参数有值,类型签名也不能保证输出有值。例如:
\ndef printer(msg: str):\n print(msg)\n\ndata = {\'a\': \'a\'}\nresult = getMaybe(data, \'a\')\nprinter(result)\nRun Code Online (Sandbox Code Playgroud)\n给出错误:
\nerror: Argument of type "str | None" cannot be assigned to parameter "msg" of type "str" in function "printer"\n \xc2\xa0Type "str | None" cannot be assigned to type "str"\n \xc2\xa0\xc2\xa0Type "None" cannot …Run Code Online (Sandbox Code Playgroud) 我喜欢 Pylance 类型检查。
但是,如果我有一个变量var: Union[None, T],在那里T实现foo,pylance 将在以下位置抛出错误:
var.foo()因为 typeNone没有实现foo.
有没有办法解决这个问题?一种告诉 Pylance 的方法“这个变量None有时是,但在这种情况下,我 100% 确定它会被分配
python-3.x visual-studio-code vscode-settings python-typing pylance
我正在编写一个函数来帮助处理一个可选的依赖项(类似于pytest.importorskip),我想输入它,但不确定要使用什么类型。因为我总是返回一个特定的模块或 None,我想我可以比“Any”更具体。
def try_import_pyarrow():
try:
import pyarrow
except ImportError:
pyarrow = None
return pyarrow
Run Code Online (Sandbox Code Playgroud) python-typing ×10
python ×9
python-3.x ×4
type-hinting ×4
mypy ×2
dictionary ×1
generics ×1
inheritance ×1
oop ×1
pylance ×1