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 Answers 2
#!/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.
6 Comments
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.
func()is not recognizingloggeras a global variable because you didn't told it to do it. Have you tried adding aglobal loggerline before? Take a look at this: stackoverflow.com/questions/423379/…loggerin yourmainsection, so it is never imported.