0
Python decorator argument
How can i put an argument in a function with a decorator?: def decor(func): def wrap(): print("============") func() print("============") return wrap @decor def print_text(x): print(x) print_text(5); How can i make this work? func() dosnt take arguments
6 Réponses
+ 6
def func(**kw):print(kw)
func(a=1, b=2) # {"a": 1, "b": 2}
+ 3
It doesn't take arguments because you didn't allow it to do so.
If you read your tutoriual further, you'll see the detailed explanation of the problem you encountered.
You need to let wrapper take arguments and pass them to the wrapped function:
def decor(func):
def wrap(*args, **kwargs):
print("============")
func(*args, **kwargs)
print("============")
return wrap
@decor
def print_text(x):
print(x)
print_text('Sololearn')
------------------------------------------------
This will give you
============
Sololearn
============
+ 2
Asterisks are not pointers in Pythons. Think of them as of unpacking operators.
Single '*' is used for non-keyworded arguments to a function , double - for keyworded arguments.
This notation is used to allow a function to accept variable number of arguments (or none) in case you do not know how many and what type of arguments you are going to pass to the function. Consider we defined a function:
def a (*args, **kwargs):
print(locals())
Then with different arguments this function will work correctly like this:
>>> a(1)
{'args': (1,), 'kwargs': {}}
>>> a([1,2,3])
{'args': ([1, 2, 3],), 'kwargs': {}}
>>> a({1:1,2:2})
{'args': ({1: 1, 2: 2},), 'kwargs': {}}
>>> a(x=5, y=6)
{'args': (), 'kwargs': {'x': 5, 'y': 6}}
>>> a([1,2,3], x=5,y=6)
{'args': ([1, 2, 3],), 'kwargs': {'x': 5, 'y': 6}}
>>>
And, finally:
>>>a()
{'args': (), 'kwargs': {}}
0
thanks strawdog 🇷🇺
0
can u tell me what **kwargs means, and what is the use of the pointers,basiclly how this works?
0
thanks ,thats very helpful