Саша Черных
Саша Черных

Reputation: 2823

Overwrite variable in function from another file

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:

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.

Upvotes: 2

Views: 225

Answers (1)

Danielle M.
Danielle M.

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

Related Questions