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.
Other process calling
another_func()
:It's as @Kevin mentioned.
another_fun()
calls the method intest.py
, but since yourlogger
variable is ONLY initialized when you run it as a script (that's the__main__
portion), it's NOT initialized whenfunc()
is called and therefore can not recognize the variable. That also means whenanother_fun()
callsfunc()
, no logger object is found sinceanother_fun()
doesn't call__main__
in yourtest.py
module.