1

I've three different modules, let's call ModuleA, ModuleB and Common. The Common module contains some helper methods that are required by both ModuleA and ModuleB.

I wanted to have separate log files maintained for each modules, that means, there should be ModuleA.log and ModuleB.log. So in each module I've created a logger object with file handler and with the corresponding file names.

Now the problem is, if I call a method in Common from ModuleA, the log events in Common should be added to ModuleA.log and if I call a method from ModuleB, the log events in Common should be appended to ModuleB.log. For this, currently I'm passing a corresponding logger object as a parameter on the method from Common module which I feel is not a good solution.

Is there any way / patter to handle this scenario?

3
  • This may not be ideal depending on what the files contain, but if you can turn the important parts of Common into a class to inherit from, I guess you could override self.logger in each of the other two classes. Commented Mar 5, 2019 at 11:06
  • @Peter I got you. But what if I have some common decorators and wanted to use those decorators in the ModuleA or ModuleB? Commented Mar 6, 2019 at 4:43
  • That actually gave me an idea, I'll put an answer :) Commented Mar 6, 2019 at 10:22

1 Answer 1

1

You could have a cache dict in Common that the other modules will be able to import and modify.

Here's a quick example with strings:

Common.py

CACHE = {'logger': None}

def func():
    print(CACHE['logger'])

ModuleA.py

from Common import CACHE, func

CACHE['logger'] = 'mod a'

func()
#mod a

ModuleB.py

from Common import CACHE, func

CACHE['logger'] = 'mod b'

func()
#mod b

If it feels a bit messy using a dict, I think you could potentially make a class to deal with the specific bits you need, it just needs to update in place instead of setting new values.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.