我有一个函数可以采用多种typing.Union类型,包括 type torch.float。但如果我使用typing.Unionwithtorch.float作为参数,我会收到错误。这是一个例子:
from typing import Union
import torch
def fct(my_float_or_tensor: Union[torch.float, torch.Tensor]):
pass
Run Code Online (Sandbox Code Playgroud)
我得到了错误
TypeError: Union[t0, t1, ...]: each t must be a type. Got torch.float32.
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
有趣的是,特殊类型也会出现同样的问题,但如果我在类型提示时直接typing.Tuple使用,则不会出现同样的问题。torch.float
当我有以下最小重现代码时:
启动.py
from __future__ import annotations
import a
Run Code Online (Sandbox Code Playgroud)
a.py
from __future__ import annotations
from typing import Text
import b
Foo = Text
Run Code Online (Sandbox Code Playgroud)
b.py
from __future__ import annotations
import a
FooType = a.Foo
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
soot@soot:~/code/soot/experimental/amol/typeddict-circular-import$ python3 start.py
Traceback (most recent call last):
File "start.py", line 3, in <module>
import a
File "/home/soot/code/soot/experimental/amol/typeddict-circular-import/a.py", line 5, in <module>
import b
File "/home/soot/code/soot/experimental/amol/typeddict-circular-import/b.py", line 5, in <module>
FooType = a.Foo
AttributeError: partially initialized module 'a' has no attribute 'Foo' (most likely due to a …Run Code Online (Sandbox Code Playgroud) python annotations circular-dependency python-3.x python-typing
我正在围绕 boto3 编写自己的包装器,以实现快速触发功能。
我正在尝试输入注释boto3.session().client('ec2')返回的内容。
调试器说它是<class 'botocore.client.EC2'>,但如果我这样写下来,python 会因运行时错误而崩溃
ec2: botocore.client.EC2
AttributeError: module 'botocore.client' has no attribute 'EC2'
Run Code Online (Sandbox Code Playgroud)
删除类型注释适用于运行时,但它使 linting 非常有限。
有没有一种相当快速的方法或技巧来使用这个 boto3 案例进行打字?
我正在谈论的代码如下:
class AWS_Client:
# debugger says it's <class 'botocore.client.EC2'>,
# but mypy says this class does not exist
ec2: botocore.client.EC2
asg: botocore.client.AutoScaling
region: str
instance_id: str
def __init__(self,
profile_name: Optional[str] = None,
instance_id: str = '',
region_name: str = '',
**kwargs) -> None:
global config
self.instance_id = instance_id or ec2_meta('instance-id').text
self.region = region_name or …Run Code Online (Sandbox Code Playgroud) 我喜欢 Pylance 中的类型检查器(VS Code),但似乎有一种情况我必须在忽略 Pylance 警告和类变量声明的最佳实践之间进行选择。很多时候,类变量是使用None类构造函数中的类型来初始化的,然后再设置该变量。例如:
class Person:
def __init__(self) -> None:
self.name:str = None
def setName(self, name:str) -> None:
self.name = name
Run Code Online (Sandbox Code Playgroud)
在这种情况下,Pylance 在作业中给出以下错误self.name:str = None:
Cannot assign member "name" for type "Person"
Expression of type "None" cannot be assigned to member "name" of class "Person"
Type "None" cannot be assigned to type "str"
Run Code Online (Sandbox Code Playgroud)
有没有什么方法可以self.name在构造函数中声明不需要值并且Pylance 满意的方式?
编辑:一些人建议使用typing.Optional来抑制此 Pylance 警告。但是,如果创建另一个成员函数来返回self.name并保证它返回 的实例str,则会生成另一个 Pylance 错误。请参见以下示例:
class Person:
def …Run Code Online (Sandbox Code Playgroud) 我有一个数据类,它可以采用枚举的一部分的值。
class MyEnum(Enum):
A = "valueA"
B = "valueB"
@dataclass
class MyDataclass:
value: MyEnum
Run Code Online (Sandbox Code Playgroud)
创建我的数据类时,类型不匹配,因为它正在考虑str!= MyEnum.A。
param = MyDataclass(value="valueA")
Run Code Online (Sandbox Code Playgroud)
MyDataclass关于如何输入有什么建议吗?
编辑:数据类正在使用我从另一个 API 收到的字符串值进行初始化
我有 Pandas lambda 函数,我将其与.apply.
此函数将输出一个字典,其中包含字符串键和值为字符串或pd.NA.
当我尝试输入提示函数时,出现错误:
def _the_function(x: str) -> dict[str, str | pd.NA]:
...
Run Code Online (Sandbox Code Playgroud)
ERROR: Expected class type but received "NAType"
Run Code Online (Sandbox Code Playgroud)
如何pd.NA在不必导入 numpy 并使用其NaN类型提示的情况下告诉它可能的值?我的项目不需要导入numpy。
有时,在 Python 函数的开头,我会检查是否使用了正确的变量类型,或者是否将某些内容作为None. 例如:
def fails_with_none(x: int):
if x is None:
raise TypeError('Function fails with None!')
return x + 1
Run Code Online (Sandbox Code Playgroud)
我正在犹豫是否x应该输入 asint或 as Optional[int]。使用 just 的原因int是,从语义上讲,该函数需要一个int. 但是,如果我从编程的角度考虑这一点,该函数会处理整数和None输入。
有推荐的方法吗?
例如,根据这个答案,提示Optional意味着“要么需要特定类型的对象,要么None需要”。
然而,问题仍然存在:什么需要?如果我们将其理解为“函数逻辑所需要的”,那么它应该被输入为int. 如果我们将其理解为“正在执行的代码需要”,那么由于我们检查了 是否x is None,因此它应该作为可能的类型提示包含在内。
我尝试从 API 接受数据,然后使用 Pydantic 基础模型验证响应结构。但是,我遇到的情况是,有时某些字段不会包含在响应中,而有时会包含在响应中。问题是,当我尝试验证结构时,Pydantic 开始抱怨这些字段“丢失”,尽管它们有时可能会丢失。我真的不明白如何将一个字段定义为“missible”。文档提到仅定义为名称和类型的字段被认为是这种方式,但我没有任何运气
这是我想要实现的目标的一个简单示例
# Response: {a: 1, b: "abc", c: ["a", "b", "c"]}
response: dict = json.loads(request_response)
# Pydantic Base Model
from pydantic import BaseModel
class Model(BaseModel):
a: int
b: str
c: List[str]
d: float
# Validating
Model(**response)
# Return: ValidationError - Missing "d" field
Run Code Online (Sandbox Code Playgroud)
如何使“d”不会导致验证抛出错误?我尝试将“d”切换为d: Optional[float]和d: Optional[float] = 0.0,但没有任何作用。
谢谢!
我有一个单例的 Python (3.8) 元类,如下所示
我尝试添加如下类型:
from typing import Dict, Any, TypeVar, Type
_T = TypeVar("_T", bound="Singleton")
class Singleton(type):
_instances: Dict[Any, _T] = {}
def __call__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T:
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
Run Code Online (Sandbox Code Playgroud)
在行中:
_instances: Dict[Any, _T] = {}
Run Code Online (Sandbox Code Playgroud)
MyPy 警告:
Mypy: Type variable "utils.singleton._T" is unbound
我已经尝试了不同的迭代,但没有成功;我很难弄清楚如何输入这个字典。
此外,该行:
_instances: Dict[Any, _T] = {}
Run Code Online (Sandbox Code Playgroud)
生产:
Mypy: The erased type of self "Type[golf_ml.utils.singleton.Singleton]" is not a supertype of its class …
我不明白应该如何在代码中使用 ArrayLike。如果检查 mypy,当我尝试在不调用强制转换的情况下使用变量进行任何操作时,我会不断收到错误。我正在尝试定义与 ndarray 以及常规列表一起使用的函数签名。
例如下面的代码
import numpy.typing as npt
import numpy as np
from typing import Any
def f(a: npt.ArrayLike) -> int:
return len(a)
def g(a: npt.ArrayLike) -> Any:
return a[0]
print(f(np.array([0, 1])), g(np.array([0, 1])))
print(f([0, 1]), g([0, 1]))
Run Code Online (Sandbox Code Playgroud)
给我 f() 和 g() 的这些错误:
Argument 1 to "len" has incompatible type "Union[_SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], bool, int, float, complex, str, bytes, _NestedSequence[Union[bool, int, float, complex, str, bytes]]]"; expected "Sized" [arg-type]
Value of type "Union[_SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], bool, int, float, complex, str, bytes, …Run Code Online (Sandbox Code Playgroud) python-typing ×10
python ×9
mypy ×2
python-3.x ×2
type-hinting ×2
typing ×2
annotations ×1
boto3 ×1
enums ×1
metaclass ×1
nan ×1
numpy ×1
pandas ×1
pydantic ×1
pylance ×1
pytorch ×1