Reputation: 10558
I have two files...
utils.py
:
def decorator(connection):
def _decorator(f):
def wrapper(*args, **kwargs):
print(f'Connected to {connection}:')
f(*args, **kwargs)
return wrapper
return _decorator
@decorator(db)
def do_thing(*args):
for arg in args:
print(arg)
run.py
:
from utils import do_thing
db = 'db_connection'
do_thing('A', 'B', 'C')
utils.py
contains a decorator that connects to a database.
The problem: run.py
imports utils.py
, but utils.do_thing
is decorated with an argument I ultimately want to pass in from run.py
.
How can I adjust things to A) make this work and B) avoid circular referencing.
Upvotes: 0
Views: 161
Reputation: 2711
You could use a third file, e.g. shared.py
, in which you define db
.
Then you can import that from both files:
shared.py:
# prepare db stuff here
db = …
utils.py:
from shared import db
def decorator():
…
@decorator(db)
def do_thing(*args):
…
run.py:
from utils import do_thing
do_thing(…)
Upvotes: 1