我有以下裝飾: 缺少參數
from decorator import decorator
def my_decorator(key=None, timeout=None, retry=0):
"""
My decorator
"""
import pdb; pdb.set_trace()
def _my_decorator(func):
import pdb; pdb.set_trace()
key = key or func.__name__
@decorator
def __my_decorator(f, *args, **kwargs):
result = "abc"
return result
return __my_decorator(func)
return _my_decorator
在第一PDB部分,的locals()
結果是:
>>> locals()
{'key': None, 'retry': 0, 'pdb': <module 'pdb' from '/opt/python/2.7/lib/python2.7/pdb.pyc'>, 'timeout': None}
在第二PDB部,結果locals()
是:
>>> locals()
{'timeout': None, 'retry': 0, 'pdb': <module 'pdb' from '/opt/python/2.7/lib/python2.7/pdb.pyc'>, 'func': <function get_items at 0x9e172cc>}
異常無PDB:
key = key or func.__name__
UnboundLocalError: local variable 'key' referenced before assignment
你有什麼想法,爲什麼key
說法走了嵌套函數_my_decorator?這更奇怪,因爲timeout
和retry
參數仍然可以訪問(儘管這是嵌套函數中的正常行爲)。
有一種變通方法:
def my_decorator(key=None, timeout=None, retry=0):
"""
My decorator
"""
key2 = key
def _my_decorator(func):
key = key2 or func.__name__
...
,但它不是一個解決方案(參數key
還在不在了在_my_decorator
,但key2
現在訪問)
Python版本:2.7.3
你如何使用'key'在裝飾者? – ecatmur