作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试实现 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__
是相当基本的。
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 类,这是明确的。
cls = type(x)
行像
# type: List[int]
,但这会破坏目的),并且它似乎正在使用 type() 命令的返回类型解决歧义。
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/
我是一名优秀的程序员,十分优秀!