gpt4 book ai didi

python - 在 Any 上调用 __new__

转载 作者:行者123 更新时间:2023-12-03 21:43:13 26 4
gpt4 key购买 nike

我正在尝试实现 this answer用于自定义 deepcopy,但带有类型提示,mypy 对 Any 不满意我从第三方库中使用的类型。这是我可以失败的最小代码

# I'm actually using tensorflow.Module, not Any,
# but afaik that's the same thing. See context below
T = TypeVar("T", bound=Any)

def foo(x: T) -> None:
cls = type(x)
cls.__new__(cls)
我懂了
 error: No overload variant of "__new__" of "type" matches argument type "Type[Any]"
note: Possible overload variants:
note: def __new__(cls, cls: Type[type], o: object) -> type
note: def __new__(cls, cls: Type[type], name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type
如果我绑定(bind) T,它就会通过键入的内容,例如 int , str或自定义类。我对此感到困惑,因为这些重载都不匹配 __new__ docs .我的知识 __new__是相当基本的。
我正在寻求修复,或者如果它是 mypy 中的限制/错误,请解释这是什么。
上下文
实际功能是
import tensorflow as tf

T = TypeVar("T", bound=tf.Module) # tf.Module is untyped

def my_copy(x: T, memo: Dict[int, object]) -> T:
do_something_with_a_tf_module(x)

cls = type(x)
new = cls.__new__(cls)
memo[id(self)] = new

for name, value in x.__dict__.items():
setattr(new, name, copy.deepcopy(value, memo))

return new
奇怪的是,如果我把它变成一种方法
class Mixin(tf.Module):
def __deepcopy__(self: T, memo: Dict[int, object]) -> T:
... # the same implementation as `my_copy` above
没有错误

最佳答案

您从 mypy 获得的 __ new __ 建议是针对类型类本身的。您可以看到构造函数完美匹配:
https://docs.python.org/3/library/functions.html#type

class type(object)
class type(name, bases, dict)
mypy 的提示在技术上是有道理的,因为您正在从 type() 返回的对象调用 __new __。如果我们得到这样一个对象(如 cls)的 __ 类 __,我们将得到 :
>>> x = [1,2,3,4]
>>> type(x)
<class 'list'>
>>> type(x).__class__
<class 'type'>
当 T 无界(即在编译时未指定)时,这可能是 mypy 的绊脚石。如果您在一个类中,正如您所注意到的,并且如 PEP 484 ( https://www.python.org/dev/peps/pep-0484/#annotating-instance-and-class-methods) 中所述,mypy 可以将类型识别为 self 类,这是明确的。
对于独立功能,有三种方法。一种是直接使用注释 # type:ignore 使 mypy 静音。第二种是直接从 x 中获取 __ 类 __ 而不是使用 type(x),它通常无论如何都会返回 __ 类 __(参见上面的链接)。三是利用__new__是一个类方法这一事实,并用x本身来调用它。
只要你想使用 Any,就没有办法向 mypy 澄清 type(x) 不是 Type[T`-1] 的任何东西,同时保持通用性(例如,你可以用一些东西来注释 cls = type(x) 行像 # type: List[int] ,但这会破坏目的),并且它似乎正在使用 type() 命令的返回类型解决歧义。
此编码适用于列表(带有愚蠢的元素列表副本),并防止我收到任何 mypy 错误:
from typing import TypeVar, Any, cast
T = TypeVar("T", bound=Any)

def foo(x: T) -> T:
cls = type(x)
res = cls.__new__(cls) # type: ignore
for v in x:
res.append(v)
return res

x = [1,2,3,4]
y = foo(x)
y += [5]
print(x)
print(y)
打印:
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
或者:
def foo(x: T) -> T:
cls = x.__class__
res = cls.__new__(cls)
for v in x:
res.append(v)
return res
第三种方法:
from typing import TypeVar, Any
T = TypeVar("T", bound=Any)

def foo(x: T) -> T:
res = x.__new__(type(x))
for v in x:
res.append(v)
return res

x = [1,2,3,4]
y = foo(x)
y += [5]
print(x)
print(y)

关于python - 在 Any 上调用 __new__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66121127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com