我使用importlib.import_module如下动态加载Python模块
def load_module(mod_name: str) -> ???:
return importlib.import_module(mod_name)
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我模块类型的正确类型注释是什么.该typing模块不包含一个,我在其他地方找不到答案.
I am using PyCharm to develop some Python app. I am trying to use as cutting-edge python as possible, so I am making use of new python features. I have a problem with type hinting.
Let's all take a look at my DataAnalyzer class:
class DataAnalyzer:
def __init__(self, train_data: pd.DataFrame, test_data: pd.DataFrame) -> None:
self.train_data = train_data
self.test_data = test_data
def analyze(self):
pass
Run Code Online (Sandbox Code Playgroud)
Now PyCharm spams me with yellow bulbs wanting me to add type annotations to self.train_data and …
我希望对某些字典执行静态类型检查( pylancein )。vscode“棘手”的部分是我希望一些参数是可选的并且根本不显示在字典中。我尝试过使用dataclassesandTypedDict但到目前为止还没有运气。
from typing import Optional, List
from dataclasses import dataclass, asdict
@dataclass
class SubOrder:
name: str
@dataclass
class Order:
name: str
sub_orders: Optional[List[SubOrder]]
assert asdict(Order(name="Pizza")) == {"name": "Pizza"}
assert asdict(Order(name="Pizza", sub_orders=[SubOrder(name="Pasta")])) == {
"name": "Pizza",
"sub_orders": [{"name": "Pasta"}],
}
Run Code Online (Sandbox Code Playgroud)
这是可以实现的吗dataclasses?我基本上只是希望我的静态类型检查器 ( pylance/ pyright) 来检查我的字典,这就是我使用dataclasses. 我也尝试过TypedDict,但类型检查器的行为似乎不像我那样。他们总是要求我设置sub_orders。
以下代码通过了,但pylance对没有 感到不满意sub_orders。
from typing import Optional, List, TypedDict
class SubOrder(TypedDict):
name: str …Run Code Online (Sandbox Code Playgroud) 假设我们有一个简单的函数,它open()使用固定的参数进行调用:
def open_for_writing(*args, **kwargs):
kwargs['mode'] = 'w'
return open(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
如果我现在尝试调用open_for_writing(some_fake_arg = 123),没有类型检查器(例如 mypy)可以判断这是一个不正确的调用:它缺少所需的file参数,并且添加了另一个不属于open签名的参数。
我如何告诉类型检查器*args和**kwargs必须是open参数规范的子集?我意识到 Python 3.10 有新ParamSpec类型,但它似乎不适用于这里,因为你无法获得ParamSpec像open.
tuple[str, ...]vs 和有什么区别tuple[str]?(蟒蛇打字)
我正在研究具有广泛类型提示的代码库,由 mypy 检查。在某些情况下,我们有一个从enum.Enum静态已知值或其他小型有限集 ( typing.Literal) 到固定值的映射,因此使用字典很方便:
# GOOD
from enum import Enum, auto
class Foo(Enum):
X = auto()
Y = auto()
lookup: dict[Foo, str] = {Foo.X: "cool", Foo.Y: "whatever"}
print(lookup[Foo.X])
Run Code Online (Sandbox Code Playgroud)
然而,这个字典不必是详尽的(又名全部):mypy 对于缺少键非常满意,并且缺少键的索引将在运行时失败。在实践中,对于大型枚举(在定义 时忘记成员dict),或者向现有枚举添加成员时(尤其是在lookup完全不同的文件时),很容易发生这种情况。
例如,这很好地通过了mypy --strict,但在运行时失败了,因为我们“忘记”更新lookup自身:
# BAD
from enum import Enum, auto
class Foo(Enum):
X = auto()
Y = auto()
Z = auto() # NEW
lookup: dict[Foo, str] = {Foo.X: "cool", Foo.Y: "whatever"}
print(lookup[Foo.Z]) # CHANGED
Run Code Online (Sandbox Code Playgroud)
我希望能够将特定的字典/映射标记为全部/详尽,这意味着,例如,mypy …
假设我有一个 python 函数,它的单个参数是一个非平凡类型:
from typing import List, Dict
ArgType = List[Dict[str, int]] # this could be any non-trivial type
def myfun(a: ArgType) -> None:
...
Run Code Online (Sandbox Code Playgroud)
...然后我有一个从 JSON 源中解压出来的数据结构:
import json
data = json.loads(...)
Run Code Online (Sandbox Code Playgroud)
我的问题是:如何检查在运行时是data有正确的类型被用作论据来myfun()使用它作为一个参数之前myfun()?
if not isCorrectType(data, ArgType):
raise TypeError("data is not correct type")
else:
myfun(data)
Run Code Online (Sandbox Code Playgroud) 有什么区别和用例typing.Collection?
例如:
from typing import Collection, Iterable
foo: Collection[int] = (1, 2)
bar: Iterable[int] = (1, 2)
spam: tuple[int] = (1, 2)
Run Code Online (Sandbox Code Playgroud)
对于我来说,一切看起来都一样,我不明白为什么不使用 always list、tuple等作为类型提示。
我使用的一些包没有类型提示它们的代码,所以当我使用它们时,Pylance 不断告诉我我使用的函数有部分未知的类型,这是我无法解决的问题。有没有办法禁用此类错误?
在打字稿中,我们有Partial 类型,所以我们可以这样做:
interface Foo {
x:number
y:number
}
const foo:Partial<Foo> = {x: 1}
Run Code Online (Sandbox Code Playgroud)
(通过这个我们可以使接口的所有属性都是可选的)
在 Python 中,我们可以使用 来做到这一点total=False,如下所示:
from typing_extensions import TypedDict
class Foo(TypedDict, total=False):
x:int
y:int
foo:Foo = {'x':1}
Run Code Online (Sandbox Code Playgroud)
但这种方法不太好,因为这意味着 allFoo必须将所有属性尽可能为 None,并且我们需要进行大量类型转换。在 python 中,是否有一种方法可以声明 TypedDict,然后将其某些实现作为该类型的子集,如下所示:
from typing_extensions import TypedDict
class Foo(TypedDict):
x: int
y: int
foo:Partial[Foo] = {'x': 1}
Run Code Online (Sandbox Code Playgroud) python ×10
python-typing ×10
python-3.x ×3
type-hinting ×3
mypy ×2
typeddict ×2
enums ×1
partial ×1
pycharm ×1
pylance ×1
pyright ×1
typing ×1