2015-01-16 23 views
3

我有Python中的問題的列表,如果有人可以請幫助 這裏是例子,我有一個contextmanager如下獲取的蟒蛇在contextmanager定義的語句函數

from contextlib import contextmanager 

@contextmanager 
def main_func(name): 
    print("<%s>" % name) 
    yield 
    print("</%s>" % name) 
    # Retreive the list of function here : tag_func1 and tag_func2 then run the one I need to run 

然後使用它像下面

with main_func("h1"): 
    def tag_func1(): 
     print("foo1") 

    def tag_func2(): 
     print("foo2") 

我想知道的是可能中檢索的定義在這裏tag_func1tag_func1一個語句的功能列表d在代碼中動態地運行它們。

我需要執行這些操作到功能main_func實施 contextmanager

非常感謝您的幫助,

+2

不,這不是上下文管理員所做的。它們只定義了進入和退出塊時的行爲;他們無法訪問或控制塊內發生的情況。見[這個問題](http://stackoverflow.com/questions/21248103/is-it-possible-to-access-the-context-object-code-block-inside-the-exit-m)和[這一個](http://stackoverflow.com/questions/20767038/is-it-possible-to-access-enclosing-context-manager)。 – BrenBarn

+0

上下文管理器甚至不創建單獨的作用域,因此無論您在其中定義的是否在本地定義的範圍之外。 – poke

回答

0
class ContextManager(): 

    def __init__(self): 
     self.functions = [] 

    def func(self, f): 
     self.functions.append(f) 
     return f 

    def __enter__(self): 
     return self 

    def __exit__(self, exc_type, exc_val, exc_tb): 
     for f in self.functions: 
      print(f.__name__) 


with ContextManager() as cm: 

    @cm.func 
    def add(x, y): 
     return x + y 

    def foo(): 
     return "foo" 

    @cm.func 
    def subtract(x, y): 
     return x - y 


# this code prints "add" and "subtract" 

這個自定義上下文管理器可以訪問內部定義的所有功能與用func方法裝飾的聲明。

+0

太棒了,看起來像這個解決方案,它甚至比我想要做的更好。我現在會測試。非常感謝 - – skullomania

+0

經過測試,它與我的課程完美結合。非常感謝。簡單來說,有沒有辦法使用另一個名字cm.func? cm.go(example :)) – skullomania

+0

當然,在'class ContextManager'中只需將'def func(self,f)'改爲'def go(self,f)'即可。如果我的答案解決了您的問題,請接受它(單擊打勾),以便具有該問題的其他用戶知道我的解決方案有效。 –