【问题标题】:Use metaclass to allow forward declarations使用元类允许前向声明
【发布时间】:2016-09-10 21:36:08
【问题描述】:

我想做一些绝对不符合 Python 的事情。我想创建一个允许前向声明其类属性的类。 (如果你必须知道,我正在尝试为解析器组合器制作一些甜美的语法。)

这就是我想做的事情:

a = 1
class MyClass(MyBaseClass):
    b = a  # Refers to something outside the class
    c = d + b  # Here's a forward declaration to 'd'
    d = 1  # Declaration resolved

我当前的方向是创建一个元类,这样当找不到d 时,我会捕获NameError 异常并返回一个我将调用ForwardDeclaration 的虚拟类的实例。我从AutoEnum 中获得了一些灵感,它使用元类魔法来声明带有裸标识符且没有赋值的枚举值。

以下是我目前所拥有的。缺少的部分是:我如何继续正常的名称解析并捕获NameErrors:

class MetaDict(dict):
    def __init__(self):
        self._forward_declarations = dict()
    def __getitem__(self,  key):
        try:
            ### WHAT DO I PUT HERE ??? ###
            # How do I continue name resolution to see if the
            # name already exists is the scope of the class
        except NameError:
            if key in self._forward_declarations:
                return self._forward_declarations[key]
            else:
                new_forward_declaration = ForwardDeclaration()
                self._forward_declarations[key] = new_forward_declaration
                return new_forward_declaration

class MyMeta(type):
    def __prepare__(mcs, name, bases):
        return MetaDict()

class MyBaseClass(metaclass=MyMeta):
    pass

class ForwardDeclaration:
    # Minimal behavior
    def __init__(self, value=0):
        self.value = value
    def __add__(self, other):
        return ForwardDeclaration(self.value + other)

【问题讨论】:

  • 你不能通过使用默认参数(在这种情况下为属性)来解决这个问题吗?
  • 除非我误解了你,否则那是行不通的,因为我在定义MyBaseClass 时不知道MyClass 的属性是什么。如果我这样做了,那你就是对的;我可以在基类中像d = ForwardDeclaration() 一样声明它们。
  • 这听起来非常恶心!做得好!目前尚不清楚具体问题/问题是什么?

标签: python python-3.x metaclass


【解决方案1】:

开始:

    def __getitem__(self,  key):
        try:
            return super().__getitem__(key)
        except KeyError:
             ...

但这不允许您检索类主体之外的全局变量。 您还可以使用专门为 dict 子类保留的 __missin__ 方法:

class MetaDict(dict):
    def __init__(self):
        self._forward_declarations = dict()

    # Just leave __getitem__ as it is on "dict"
    def __missing__(self,  key):
        if key in self._forward_declarations:
            return self._forward_declarations[key]
        else:
            new_forward_declaration = ForwardDeclaration()
            self._forward_declarations[key] = new_forward_declaration
            return new_forward_declaration

正如您所看到的,这并不是“非 Pythonic”——SymPy 和 SQLAlchemy 等高级 Python 东西必须借助这种行为来发挥它们的神奇作用——只要确保对其进行充分记录和测试即可。

现在,为了允许全局(模块)变量,您需要做一些事情 - 并且可能在所有 Python 实现中都不可用 - 即:内省类主体所在的框架获取它的全局变量:

import sys
...
class MetaDict(dict):
    def __init__(self):
        self._forward_declarations = dict()

    # Just leave __getitem__ as it is on "dict"
    def __missing__(self,  key):
        class_body_globals = sys._getframe().f_back.f_globals
        if key in class_body_globals:
             return class_body_globals[key]
        if key in self._forward_declarations:
            return self._forward_declarations[key]
        else:
            new_forward_declaration = ForwardDeclaration()
            self._forward_declarations[key] = new_forward_declaration
            return new_forward_declaration

现在你在这里 - 你的特殊字典足以避免 NameErrors,但你的 ForwardDeclaration 对象还不够聪明 - 运行时:

a = 1
class MyClass(MyBaseClass):
    b = a  # Refers to something outside the class
    c = d + b  # Here's a forward declaration to 'd'
    d = 1 

发生的情况是c 变成了ForwardDeclaration 对象,但求和为d 的即时值,即为零。在下一行,d 简单地被值1 覆盖,不再是惰性对象。所以你不妨声明 c = 0 + b

为了克服这个问题,ForwardDeclaration 必须是一个以智能方式设计的类,以便它的值总是被延迟评估,并且它的行为类似于“反应式编程”方法:即:对值的更新将级联更新到依赖它的所有其他值。我认为给你一个工作的“反应性”感知 FORrwardDeclaration 类的完整实现不属于这个问题的范围。 - 不过,我有一些玩具代码可以在 github 上的 https://github.com/jsbueno/python-react 上执行此操作。

即使使用适当的“反应式”ForwardDeclaration 类,您也必须再次修复您的字典,以便 d = 1 类起作用:

class MetaDict(dict):
    def __init__(self):
        self._forward_declarations = dict()

    def __setitem__(self, key, value):
        if key in self._forward_declarations:
            self._forward_declations[key] = value
            # Trigger your reactive update here if your approach is not
            # automatic
            return None
         return super().__setitem__(key, value)
    def __missing__(self,  key):
        # as above

最后,有一种方法可以避免实现完全反应式感知类 - 您可以在元类的 __new__ 方法上解决所有待处理的 FORrwardDependencies - (以便您的 ForwardDeclaration 对象在课堂上手动“冻结”创建时间,不用再担心-)

一些东西:

from functools import reduce

sentinel = object()
class ForwardDeclaration:
    # Minimal behavior
    def __init__(self, value=sentinel, dependencies=None):
        self.dependencies = dependencies or []
        self.value = value
    def __add__(self, other):
        if isinstance(other, ForwardDeclaration):
             return ForwardDeclaration(dependencies=self.dependencies + [self])
        return ForwardDeclaration(self.value + other)

class MyMeta(type):
    def __new__(metacls, name, bases, attrs):
         for key, value in list(attrs.items()):
              if not isinstance(value, ForwardDeclaration): continue
              if any(v.value is sentinel for v in value.dependencies): continue
              attrs[key] = reduce(lambda a, b: a + b.value, value.dependencies, 0) 

         return super().__new__(metacls, name, bases, attrs)
    def __prepare__(mcs, name, bases):
        return MetaDict()

并且,根据您的类层次结构和您正在做什么,请记住还要使用在其祖先上创建的 _forward_dependencies 更新一个类的字典 _forward_dependencies。 并且,如果您需要+ 以外的任何运算符,正如您将注意到的,您将必须保留有关运算符本身的信息——此时,您不妨直接使用sympy

【讨论】:

  • 搜索现有名称需要包含__builtins__,在f_globals之后搜索。
  • 搜索现有名称还需要检查外部作用域的变量(如果MyClass 定义在函数中,它本身可能定义在函数中)。我查看了inspect,但不知道如何走框架的外部范围。
  • 与其搞乱f_globals__builtins__,你可以提出一个KeyError,这会自动发生。不允许您检查是否存在。我在文档中没有找到任何提及它的内容,但它位于 cpython's source code
  • @Kyuuhachi 我认为这在这里行不通。如果名称未在本地、非本地、全局或内置范围中定义,我希望能够运行代码(创建前向声明)。如果我提出KeyError,我会放弃控制权并且如果未定义名称则无法恢复。如果您知道如何在此处捕捉后续的NameError,我很乐意听到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 2011-05-08
相关资源
最近更新 更多