2

1. Summary

I don't find, how I can overwrite variable in function from another file.


2. Example

2.1. Configuration

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!")

3. Steps to reproduce

I run in console:

python first.py

4. Expected behavior

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!

5. Actual behavior

Value of log variable from config.py file.

D:\PyfancyRefactoring>python first.py
[2018-01-25 16:54:25.469005] DEBUG: config: Sasha Champion!

6. Not helped

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.


7. Do not offer

  1. I know that I can define 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.
Саша Черных
  • 2,561
  • 4
  • 25
  • 71

1 Answers1

1

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__)
Danielle M.
  • 3,607
  • 1
  • 14
  • 31
  • Danielle M.: I add in `config.py` `log = logbook.Logger(__name__)` instead of `log = logbook.Logger("config")` → I run in console `python first.py` → I still get actual behavior, not expected behavior. Thanks. – Саша Черных Jan 25 '18 at 17:21
  • Do you understand why the program behaves the way it does? You need to tell the green_foreground function to use the logger defined in first.py. How might you do that? – Danielle M. Jan 25 '18 at 17:24
  • DanielleM.: `You need to tell the green_foreground function to use the logger defined in first.py. How might you do that? ` — this is the question, that I asked :-) . Thanks. – Саша Черных Jan 26 '18 at 06:59