I am trying to make two decorators with parameters. First
creates a list
with element x
and calls func
. second
is simply calling the first
by passing a parameter from a dict.
def first(x=1):
def wrapped(func):
l = [x]
func(l)
print(l)
return wrapped
def second(d={'x':10}):
return first(x=d['x'])
third
function simply modifies the list passed in.
I want to make any of the four decorators below possible by simply calling third()
. How should I modify my code?
##@second
##@second({'x':100})
##@first
##@first(x=10)
def third(l):
l.append(-1)
third()
For example:
## With @first,
## I am expecting to get [1, -1].
## With @first(x=10),
## I am expecting to get [10, -1].
## With @second,
## I am expecting to get [10, -1].
## With @second({x:100}),
## I am expecting to get [100, -1].
The upper code is an abstraction of my problem. My real problem is that I want a decorator that handles opening and closing connection for me, so that I only need to write code for handling the connection.
And the connection needs parameters, which is first
. I want the parameters to be passed in a different way, which is the second
. third
is what I am gonna do with the connection. I want third
to be called like a normal function, and it also handles the opening and closing connection using a decorator. Sorry if decorator should not be used this way, but I really want to practice using it.
---Update---
What I want to achieve is basically the following:
def context_manager(username='user', password='password'):
conn = OpenConnection()
func(conn)
CloseConnection()
def context_manager2(d={'username': 'user', 'password': 'password'}):
content_manager(username=d['username'], password=d['password'])
# @context_manager
# @context_manager('username', '123456')
# @context_manager2
# @context_manager2(d={'username': 'username', 'password': '123456'})
def execute(conn):
pass
I want to make any of the four decorators possible and still be able to call execute
in a way like execute()