Skip to main content
 首页 » 编程设计

python之比 locals() 或 dict(foo=foo) 更好的东西用于将上下文导出到模板引擎

2025年05月04日14Free-Thinker

所以,在关于#python 关于 why not to use locals 的简短讨论之后,我正在考虑如果没有 dict(foo=foo,bar=bar) 的重复性(即不干)(或使用文字语法( {})).

理想情况下,可以提交一份反射(reflect) this ecmascript harmony proposal 的 PEP(或已经存在的 PEP) . (我想强调它传达的 DRY 方面)。

那么,你有什么解决办法吗?我应该提交 PEP 吗?

请您参考如下方法:

以及元类/attrs 解决方案的变体:

def make_dict(name, bases, attrs): 
    attrs.pop('__module__') 
    attrs.pop('__metaclass__', None)  # not needed in python3 
    return attrs 

python 2:

class Context: 
    __metaclass__ = make_dict 

python 3:

class Context(metaclass=make_dict): 
    a = 1 
    b = 2 

真的,这个问题刚刚变成了我玩元类的沙箱