【问题标题】:How can I type hint a dynamically set class attribute in a metaclass?如何在元类中键入提示动态设置的类属性?
【发布时间】:2019-07-23 14:57:02
【问题描述】:

当我动态设置一个类的属性时:

from typing import TypeVar, Generic, Optional, ClassVar, Any

class IntField:
    type = int

class PersonBase(type):
    def __new__(cls):
        for attr, value in cls.__dict__.items():
            if not isinstance(value, IntField):
                continue
            setattr(cls, attr, value.type())
        return cls

class Person(PersonBase):
    age = IntField()

person = Person()

print(type(Person.age)) # <class 'int'>
print(type(person.age)) # <class 'int'>
person.age = 25 # Incompatible types in assignment (expression has type "int", variable has type "IntField")

age 属性的类型将是 int 类型,但 MyPy 不能遵循该类型。

有没有办法让 MyPy 理解?

Django 已经实现了:

from django.db import models

class Person(models.Model):
    age = models.IntegerField()

person = Person()
print(type(Person.age)) # <class 'django.db.models.query_utils.DeferredAttribute'>
print(type(person.age)) # <class 'int'>
person.age = 25  # No error

Django 是如何做到这一点的?

【问题讨论】:

  • 我不确定 Django,但这种模式经常使用 descriptors 实现。
  • type(Person.age) 在每种情况下是什么?
  • @jdehesa 我将打印结果放在评论中。在这两种情况下都是&lt;class 'int'&gt;
  • 不,我的意思是Person.age,是类属性,而不是实例。
  • 我的错。我添加到sn-ps。有趣的是,在我的例子中,它在实例化之前已经是一个 int 了。

标签: python python-3.x metaprogramming type-hinting


【解决方案1】:

Patrick Haugh 是对的,我正试图以错误的方式解决这个问题。描述符是要走的路:

from typing import TypeVar, Generic, Optional, ClassVar, Any, Type

FieldValueType = TypeVar('FieldValueType')


class Field(Generic[FieldValueType]):

    value_type: Type[FieldValueType]

    def __init__(self) -> None:
        self.value: FieldValueType = self.value_type()

    def __get__(self, obj, objtype) -> 'Field':
        print('Retrieving', self.__class__)
        return self

    def __set__(self, obj, value):
        print('Updating', self.__class__)
        self.value = value

    def to_string(self):
        return self.value

class StringField(Field[str]):
    value_type = str

class IntField(Field[int]):
    value_type = int

    def to_string(self):
        return str(self.value)


class Person:
    age = IntField()

person = Person()
person.age = 25
print(person.age.to_string())

MyPy 完全可以理解这一点。谢谢!

【讨论】:

  • 使用 mypy 0.670,它将age 推断为类型Any - 基本上没有类型。
【解决方案2】:

由于您在类上定义了字段,因此实用的方法是对字段进行类型提示。请注意,您必须告诉 mypy 不要检查线路本身。

class Person(PersonBase):
    age: int = IntField()  # type: ignore

这是最小的变化,但相当不灵活。


您可以使用带有假签名的辅助函数来创建自动键入的通用提示:

from typing import Type, TypeVar


T = TypeVar('T')


class __Field__:
    """The actual field specification"""
    def __init__(self, *args, **kwargs):
        self.args, self.kwargs = args, kwargs


def Field(tp: Type[T], *args, **kwargs) -> T:
    """Helper to fake the correct return type"""
    return __Field__(tp, *args, **kwargs)  # type: ignore


class Person:
    # Field takes arbitrary arguments
    # You can @overload Fields to have them checked as well
    age = Field(int, True, object())

这就是attrs 库提供其遗留提示的方式。这种风格允许隐藏注释的所有魔法/技巧。


由于元类可以检查注释,因此无需将类型存储在字段上。您可以将 Field 用于元数据,并为类型使用注释:

from typing import Any


class Field(Any):  # the (Any) part is only valid in a .pyi file!
    """Field description for Any type"""


class MetaPerson(type):
    """Metaclass that creates default class attributes based on fields"""
    def __new__(mcs, name, bases, namespace, **kwds):
        for name, value in namespace.copy().items():
            if isinstance(value, Field):
                # look up type from annotation
                field_type = namespace['__annotations__'][name]
                namespace[name] = field_type()
        return super().__new__(mcs, name, bases, namespace, **kwds)


class Person(metaclass=MetaPerson):
    age: int = Field()

这就是attrs 提供其 Python 3.6+ 属性的方式。它既通用又符合注释样式。请注意,这也可以用于常规基类而不是元类。

class BasePerson:
     def __init__(self):
         for name, value in type(self).__dict__.items():
             if isinstance(value, Field):
                 field_type = self.__annotations__[name]
                 setattr(self, name, field_type())


class Person(BasePerson):
    age: int = Field()

【讨论】:

    猜你喜欢
    • 2022-01-02
    • 1970-01-01
    • 2021-06-17
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 2013-02-18
    • 1970-01-01
    相关资源
    最近更新 更多