简体   繁体   English

Python装饰器,其参数取决于装饰函数

[英]Python decorator with arguments that depends on the decorated function

i have a function decorated like this: 我有这样装饰的功能:

@do_something(cache_key=CACHE_ID ,timeout=CACHE_ID_TIMEOUT)        
def get_something_from_cache():
    ...
    ...
    ...
    return result

my decorator: 我的装饰:

def do_something(function=None, cache_key='', timeout=300):

    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner(*args, **kwargs):
            ...
            ...
            ...
    return decorator if function is None else decorator(function) 

i want to be able to have different 'cache_key' depends the decorated function input. 我希望能够有不同的'cache_key'取决于修饰的功能输入。 something like: 就像是:

@do_something(cache_key=CACHE_ID.format(att) ,timeout=CACHE_ID_TIMEOUT)        
def get_something_from_cache(att):
    ...
    ...
    ...
    return result

is it possible?? 可能吗??

Nope. 不。

Function decorators are executed just after the decorated function is defined. 定义修饰的函数后立即执行函数修饰器。 att does not exist until the function is called, which may be long after definition, or never at all. 在调用该函数之前, att并不存在,这可能在定义之后很长时间,或者根本没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM