Reputation: 2823
I don't find, how I can overwrite variable in function from another file.
I use logbook and pyfancy modules.
I have 2 files — config.py
and first.py
:
config.py
:
import logbook
import sys
from pyfancy.pyfancy import pyfancy
log = logbook.Logger("config")
logbook.StreamHandler(sys.stdout,
level=logbook.DEBUG).push_application()
def green_foreground(coloredtext):
log.debug(pyfancy().green().bold(coloredtext))
first.py
:
import logbook
from config import green_foreground
log = logbook.Logger("first")
green_foreground("Sasha Champion!")
I run in console:
python first.py
I want, that log
variable:
log = logbook.Logger("first")
— in first.py
,log = logbook.Logger("second")
— in second.py
and so on.D:\PyfancyRefactoring>python first.py
[2018-01-25 16:54:25.469005] DEBUG: first: Sasha Champion!
Value of log
variable from config.py
file.
D:\PyfancyRefactoring>python first.py
[2018-01-25 16:54:25.469005] DEBUG: config: Sasha Champion!
For example, I add to config.py
:
if __name__ == 'config':
log = logbook.Logger("config")
else:
log = logbook.Logger("first")
I get actual behavior, not expected behavior.
green_foreground
function in each file, but it will be a lot of duplicate code and I think, that it a not a good practice.Upvotes: 2
Views: 225
Reputation: 3662
The config file creates a logger, named config
, and the function green_foreground logs to that logger. It is hard coded that way - at no point do you tell the green_foreground function to log anywhere else, it has no idea about the log created in first.py.
When you run first.py, python creates two different log
instances. You can modify the green_foreground function to accept a log
instance as an argument and default to the one creatd in config
, or:
change config.py
to log this instead:
log = logbook.Logger(__name__)
Upvotes: 1