Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

python - How can I get the same/to pass parameters between decorator and decorated function?

In this case I want to pass _source_dir_abs:str into decorator.

I tried to mimic the same process that Flask has for routing to pass parameter from decorator to function it is decorated. But this makes the parameter interpreted as a literal string and not as a variable.

@dec_check_abs("<_source_dir_abs>")
def walk_return_dir_nofolder(_source_dir_abs:str) -> list:
    w = walk(_source_dir_abs)
    d = [d for d, fol, fil in w if len(fol) == 0]
    return d

I tried with @dec_check_abs(_source_dir_abs) it returns an error of NameError: name 'source_dir_abs' is not defined

def dec_check_abs(*args_1):
    def decorator(_func:FT):
        def wrapper(*args_2, **kwargs):
            for i in args_1:
                if not check_abs(i):
                    """Raise warning."""
                    napw()

                    if _func.__annotations__["return"] == bool:
                        return False
                    else:
                        return None

            return _func(*args_2, **kwargs)
        return wrapper
    return decorator
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You've missed the point of decorators. You don't pass the argument in the decorator declaration; the function returned by that decorator accepts the arguments and can pass it on to the wrapped function if necessary.

So the decorator would look something like this:

def dec_check_abs(func):
    def wrapper(*args):
        if ... do your check on args here...:
            return func(*args)
        else:
            print('No, bad caller.')
    return wrapper

and you would just use it as:

@dec_check_abs
def walk_return_dir_nofolder(_source_dir_abs:str) -> list:
    ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...