2013-10-18 59 views
0

我寫過一個既可以作爲上下文管理器又可以作爲函數的函數。什麼是用裝飾器和上下文管理器的函數來改變dir最Pythonic的方式?

我的功能工作在Python 2.6和作品對這個測試:

@cd('/') 
def test_cd_decorator(): 
    assert os.getcwd() == '/' 

def test_cd(): 
    old = os.getcwd() 
    with cd('/'): 
     assert os.getcwd() == '/' 
    assert os.getcwd() == old 
    test_cd_decorator() 
    assert os.getcwd() == old 

test_cd() 

什麼是最Python的解決方案?

+0

你的失敗是什麼? –

+0

@WayneWerner沒有失敗。我有一個解決方案,但想知道別人如何解決它。 – guettli

+0

我編輯了你的問題,以清楚表明你只是尋找最Pythonic的解決方案。 –

回答

2

我不知道有這樣的庫,可以做你所需要的。所以我創建了一個。

import functools 
import os 

class cd: 
    def __init__(self, path): 
     self.path = path 
    def __enter__(self): 
     self.old = os.getcwd() 
     os.chdir(self.path) 
     return self 
    def __exit__(self, exc_type, exc_value, tb): 
     os.chdir(self.old) 
    def __call__(self, func): 
     @functools.wraps(func) 
     def wrapper(*args, **kwargs): 
      with self: 
       return func(*args, **kwargs) 
     return wrapper 
相關問題