在Any上调用__new__

我正在尝试为自定义 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

如果我绑定T到输入的东西,比如intstr或者自定义类,它就会通过。我对此感到困惑,因为这些重载都与__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)的__ class __,我们就会得到<class 'type'>:

>>> 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 获取 __ class __ 而不是使用 type(x),它通常无论如何都会返回 __ class __(参见上面的链接)。三是利用__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)


以上是在Any上调用__new__的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>