3

我发现自己正在编写以下代码:

def dlt(translation):
    del translation.strands[translation.active][translation.locus]

我宁愿喜欢这样的东西:

def dlt(translation):
    *something*(translation):
        del strands[active][locus]

有没有办法做到这一点?

4

2 回答 2

4

命名空间只是 Python 对象,您可以将对象(包括属性查找的结果)分配给局部变量名称:

strands = translation.strands
active = translation.active
locus = translation.locus

或者,您必须将修改的上下文管理器组合在一起locals(),如this answer所示。

像这样的事情会这样做:

import inspect

class Namespace(object):
    def __init__(self, namespaced):
        self.namespaced = namespaced

    def __enter__(self):
        """store the pre-contextmanager scope"""
        ns = globals()
        namespaced = self.namespaced.__dict__
        # keep track of what we add and what we replace
        self.scope_added = namespaced.keys()
        self.scope_before = {k: v for k, v in ns.items() if k in self.scope_added}
        globals().update(namespaced)
        return self

    def __exit__(self):
        ns = globals()
        # remove what we added, then reinstate what we replaced
        for name in self.scope_added:
            if name in ns:
                del ns[name]
        ns.update(self.scope_before)

然后像这样使用它:

with Namespace(translation):
     del strands[active][locus]

在块中的所有项目translation.__dict__都可以在全局范围内使用while

请注意,这不是线程安全的,并且有可能给任何试图阅读将来使用它的代码的人(包括您自己)造成很多混乱。就个人而言,我不会使用这个。

于 2012-11-09T17:17:29.557 回答
2

您可能应该使用 Martijn 的答案。但是如果你真的想做你所要求的,我认为这个(未经测试的)片段可以做到:

exec "del strands...", translation.__dict__

如果你不喜欢:很好,你有品味。:-)

这是另一种选择:

def within(obj, func):
    return func(**obj.__dict__)

像这样称呼它:

def dostuff(strands, active, locus, **ignored):
    del ...
within(translation, dostuff)
于 2012-11-09T17:31:21.630 回答