11

以下是Richard Jones 博客中的一些代码:

with gui.vertical:
    text = gui.label('hello!')
    items = gui.selection(['one', 'two', 'three'])
    with gui.button('click me!'):
        def on_click():
            text.value = items.value
            text.foreground = red

我的问题是:他到底是怎么做到的?上下文管理器如何访问 with 块内的范围?这是尝试解决此问题的基本模板:

from __future__ import with_statement

class button(object):
  def __enter__(self):
    #do some setup
    pass

  def __exit__(self, exc_type, exc_value, traceback):
    #XXX: how can we find the testing() function?
    pass

with button():
  def testing():
    pass
4

2 回答 2

14

这是一种方法:

from __future__ import with_statement
import inspect

class button(object):
  def __enter__(self):
    # keep track of all that's already defined BEFORE the `with`
    f = inspect.currentframe(1)
    self.mustignore = dict(f.f_locals)

  def __exit__(self, exc_type, exc_value, traceback):
    f = inspect.currentframe(1)
    # see what's been bound anew in the body of the `with`
    interesting = dict()
    for n in f.f_locals:
      newf = f.f_locals[n]
      if n not in self.mustignore:
        interesting[n] = newf
        continue
      anf = self.mustignore[n]
      if id(newf) != id(anf):
        interesting[n] = newf
    if interesting:
      print 'interesting new things: %s' % ', '.join(sorted(interesting))
      for n, v in interesting.items():
        if isinstance(v, type(lambda:None)):
          print 'function %r' % n
          print v()
    else:
      print 'nothing interesting'

def main():
  for i in (1, 2):
    def ignorebefore():
      pass
    with button():
      def testing(i=i):
        return i
    def ignoreafter():
      pass

main()

编辑:更多的延伸代码,添加了一些解释......:

捕捉调用者的本地人__exit__很容易——更棘手的是避免那些在块之前已经定义的本地人,这就是为什么我添加了两个应该忽略with的主要本地函数。with我对这个解决方案不是 100% 满意,它看起来有点复杂,但是我无法用==or得到正确的相等性测试is,所以我采用了这种相当复杂的方法。

我还添加了一个循环(以更强烈地确保def正确处理之前/内部/之后的 s)和一个类型检查和函数调用,以确保正确的化身testing是被识别的那个(一切似乎工作正常)——当然,编写的代码只有在def内部用于不带参数的可调用函数时才有效,因此获得签名以防止这种with情况并不难(但因为我只是为了目的而进行调用inspect检查是否识别了正确的函数对象,我没有为最后的改进而烦恼;-)。

于 2009-08-10T17:02:58.140 回答
2

要回答您的问题,是的,这是框架内省。

但我会创建做同样的事情的语法是

with gui.vertical:
    text = gui.label('hello!')
    items = gui.selection(['one', 'two', 'three'])
    @gui.button('click me!')
    class button:
        def on_click():
            text.value = items.value
            text.foreground = red

在这里,我将实现gui.button一个装饰器,它在给定一些参数和事件的情况下返回按钮实例(尽管现在在我看来这button = gui.button('click me!', mybutton_onclick也很好)。

我也会gui.vertical保持原样,因为它可以在没有自省的情况下实现。我不确定它的实现,但它可能涉及设置gui.direction = gui.VERTICAL以便gui.label()其他人使用它来计算他们的坐标。

现在,当我看到这个时,我想我会尝试以下语法:

    with gui.vertical:
        text = gui.label('hello!')
        items = gui.selection(['one', 'two', 'three'])

        @gui.button('click me!')
        def button():
            text.value = items.value
            foreground = red

(这个想法类似于标签由文本组成,按钮由文本和功能组成)

于 2009-08-10T19:10:42.503 回答