Python 键入将字符串附加到类成员

问题描述

假设我有一个这样的类型提示类:

class Foo:
  one: str
  two: int
  three: str

是否可以声明一个类型,使其具有与 Foo 相同的属性,但具有例如_a 附加到静态类型检查器可见的末尾?即

class Bar:
  one_a: str
  two_a: int
  three_a: str

换句话说,我想单独声明 Foo,然后自动生成类型 Bar,以便 Bar 类型的任何变量都有 one_a 等。在代码完成期间出现。来自 TypeScript 背景,这很容易实现,但我不确定 Python 的类型系统是否具有足够的表现力。

解决方法

我不知道这是否会让它们像您想要的那样在代码完成期间出现,因为这取决于您的 IDE 的智能程度,但这里是如何使用元类将所需的类型提示注释添加到另一个班级:

class MyMetaClass(type):
    """ Create class that with annotations from a template class whose
        name have all had a suffix added to them.
    """
    def __new__(metaclass,classname,bases,classdict):

        _template = classdict.get('_template',None)
        _suffix = classdict.get('_suffix',None)

        if not (_template and _suffix):
            raise RuntimeError(f'_template or _suffix not defined in class {classname!r}')

        __annotations__ = {name+_suffix: type
                                for name,type in _template.__annotations__.items()}
        classdict['__annotations__'] = __annotations__

        return type.__new__(metaclass,classdict)


class Foo:
    one: str
    two: int
    three: str


class Bar(metaclass=MyMetaClass):
    _template = Foo
    _suffix = '_a'


print(f'{Bar.__annotations__}')  # -> {'one_a': <class 'str'>,'two_a': <class 'int'>,'three_a': <class 'str'>}