Import modules with proper initialization in Python

4k Views Asked by At

I have a file test.py:

import logging

def func():
    logger.info('some info')

if __name__ == '__main__':
    logger = logging.getLogger()
    func()

Which runs well. When I from test import func in another file and call the func() method, it gives me global name 'logger' is not defined error.

from test import func
def another_fun():
    func()

Even if I put logger = logging.getLogger() in another_func() before calling func(), it still gives me such error. I'm wondering in situations like this, what is the standard way of importing functions from other files with proper initialization. Thanks a lot.

2

There are 2 best solutions below

6
On BEST ANSWER
#!/usr/bin/env python3
import logging
logger = logging.getLogger("funclogger") # all modules importing this get access to funclogger log object

def func():    
    logger.info('some info')

if __name__ == '__main__':
    func()

Other process calling another_func():

#!/usr/bin/env python3
import logging
logger = logging.getLogger("funclogger") # May not be needed if this module doesn't log
from test import func

def another_fun():
    func()

It's as @Kevin mentioned.

another_fun() calls the method in test.py, but since your logger variable is ONLY initialized when you run it as a script (that's the __main__ portion), it's NOT initialized when func() is called and therefore can not recognize the variable. That also means when another_fun() calls func(), no logger object is found since another_fun() doesn't call __main__ in your test.py module.

1
On

Don't initialize things in if __name__ == '__main__'. That's for the code that will run when your file is executed as a script. Ideally, it should consist of a single function call and nothing else.

You can't define globals in a different module, either. Each module has its own separate set of globals. You have to initialize logger in the test.py module.