简体   繁体   中英

How can I use the same parameters in a decorator with that in the functions in Python?

I want use a same param in decorater and function like:

def outer(deco_param):
    def decorator(func):
        print("param:%s" % deco_param)
        return func
    return decorator


@outer(deco_param=s)    # problems here: 's' is unreferenced
def test(s):
    print("test:%s" % s)

I got this idea when using Flask but I didn't know how did they make it, which supports using a param of view function in its decorater like:

app.route(rule="/user/<int:uid>")
def access_user(uid):  # if I use any other name except from 'uid', IDE would raise a tip
    ...

What's more, Flask seems to make a static check . If I miss uid argument or use any other name, IDE(pycharm) would raise a tip of "Function 'access_user` doesn't have a parameter 'int:uid'". That's the effect I want.

Can anyone please give me some advice? Thanks

You don't need to pass the same parameter to both the outer function and the inner function. To call the parameters via decorator, you should add a wrapper function to pass the parameters (*args) from inner one to outer one.

You can write like this:

def outer():
    def decorator(func):
        def wrapper(*args):
            print("param:%s" % func.__param__)
            return func(*args)
        return wrapper
    return decorator


@outer
def test(s):
    print("test:%s" % s)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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