python - Decorator that adds a keyword parameter -
i'm trying define decorator adds 1 keyword argument decorated function f. f might have combination of (positional, keyword, etc) parameters. tried this:
def capture_wrap(f): def captured(name=false, *args, **kwargs): """name can false, true or str. if str, use name.""" print (name, f, args, kwargs) inner = f(*args, **kwargs) if name false: return inner elif name true: return capture(inner) else: return capture(inner, name=name) return captured if try use function accepts single argument:
@capture_wrap def any_of(s): """s must in right format. see https://docs.python.org/3/library/re.html#regular-expression-syntax .""" return wrap('[', dinant(s, escape=false), ']') 0-9a-fa-f <function any_of @ 0x7fb370548a60> () {} traceback (most recent call last): file "./dinant.py", line 222, in <module> hex = one_or_more(any_of('0-9a-fa-f')) file "./dinant.py", line 116, in captured inner = f(*args, **kwargs) typeerror: any_of() missing 1 required positional argument: 's' i error because argument becomes name parameter in captured(). how should correctly?
you can make name keyword-only argument achieve this. issue is positional argument , when you're doing any_of('foo') 'foo' being passed name argument.
def capture_wrap(f): def captured(*args, name=false, **kwargs): """name can false, true or str. if str, use name.""" print(name, f, args, kwargs) inner = f(*args, **kwargs) return inner return captured @capture_wrap def any_of(s1, s2, s3, **kwargs): return "i something" demo:
>>> any_of('0-9a-fa-f', 1, 2) false <function any_of @ 0x1041daea0> ('0-9a-fa-f', 1, 2) {} 'i something' >>> any_of('0-9a-fa-f', 2, 3, a=1, b=2, name='some-name') some-name <function any_of @ 0x1041daea0> ('0-9a-fa-f', 2, 3) {'a': 1, 'b': 2} 'i something'
Comments
Post a Comment