Suppose I define a package mypkg.py
as follows:
import logging
class A:
logger = logging.getLogger ('mylogger')
def __init__(self):
logger.warning ('initializing class A')
def someMethod(self)
logger.info ('about to do something useful')
if '__main__' == __name__:
logger = logging.getLogger ('mylogger')
a = A()
Sure enough, this works when I run it directly:
$ python3 mypkg.py
initializing class A
However, when I try to use the class from within an interactive session, the symbol logger
is not available:
$ python3
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging
>>> logger = logging.getLogger ('mylogger')
>>> import mypkg
>>> a = mypkg.A()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/tmp/mypkg.py", line 9, in __init__
logger.warning ('initializing class A')
NameError: name 'logger' is not defined
I can 'fix' this by forcing logger
to the global namespace:
import logging
class A:
def __init__(self):
global logger
logger = logging.getLogger ('mylogger')
logger.warning ('initializing class A')
pass
now this works:
$ python3
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import mypkg
>>> a = mypkg.A()
initializing class A
But surely this is not the right way to do this? What am I missing here?
Thanks, Mons