mschrimpf
mschrimpf

Reputation: 559

Import variable that changes after import

I have a module that takes care of logging and provides a logger variable to a bunch of other modules:

log_module.py

my_logger = None

def init_var(program_args):
    my_logger = logging.getLogger(program_args.something)

The logger is initially None but will be initialized very early in the program (after all the imports though).

When other modules import the logger, it has not been initialized and thus is None

from log_module import my_logger
print(my_logger) // None

When my_logger is changed from within the log_module, it does not affect the imported variable since that resides in the importing module's global namespace.

I could import log_module and then write log_module.my_logger.log("...") but that would get quite lengthy.

Is there another way to use a variable from a module that will change after it has been imported?

Upvotes: 0

Views: 86

Answers (2)

user707650
user707650

Reputation:

When using a logger configured in module A in module B, you simply obtain that logger with the right name, at the point in your program where you need it. Inside module B:

logging.getLogger(program_args.something)

Don't reimport the logger from module A.

If you don't have access to program_args.something, you may want to think up a better name: your logger probably doesn't need to have that much of a flexible name.

Also think about logger namespacing within a package: a logger named 'module.submodule.subsubmodule' will still pick up the configuration from a logger named 'module', for example.

Upvotes: 1

Amit Shah
Amit Shah

Reputation: 4164

I think you would be best of changing your approach. Perhaps have some class which is a singleton, storing the value of the variable, so that when the variable is actually needed, it is fetched from the class, rather than the import.

Upvotes: 1

Related Questions