Scope of variables in python decorators - changing parameters

前端 未结 1 807
滥情空心
滥情空心 2021-01-13 11:16

I have the following decorator with parameters:

from functools import wraps
def pdecor(p):
    def decorator(fn):
        @wraps(fn)
        def wrapper(*arg         


        
相关标签:
1条回答
  • 2021-01-13 11:46

    Because you assign to p inside wrapper, Python treats the p inside wrapper as local to wrapper. In Python 3 you can use nonlocal p to mark p as referenced from an outer scope. In Python 2 there is no way to assign to the intermediate p, although you can get a reference to the same value by passing it into the nested functions as a keyword argument (e.g., def decorator(fn, p=p)).

    However, it's not clear what you're getting at with this anyway. p is already only local to pdecor. No code outside pdecor can access p, so decrementing it won't have any effect on any code elsewhere. So whether you can decrement p or not, it won't really accomplish anything.

    0 讨论(0)
提交回复
热议问题