Overriding a global

MRAB python at mrabarnett.plus.com
Sat Dec 10 16:07:18 EST 2011


On 10/12/2011 20:47, Roy Smith wrote:
> I've got a code pattern I use a lot.  In each module, I create a logger
> for the entire module and log to it all over:
>
> logger = logging.getLogger('my.module.name')
>
> class Foo:
>     def function(self):
>        logger.debug('stuff')
>        logger.debug('other stuff')
>
> and so on.  This works, but every once in a while I decide that a
> particular function needs a more specific logger, so I can adjust the
> logging level for that function independent of the rest of the module.
> What I really want to do is:
>
>     def function(self):
>        logger = logger.getChild('function')
>        logger.debug('stuff')
>        logger.debug('other stuff')
>
> which lets me not have to change any lines of code other than inserting
> the one to redefine logger.  Unfortunately, that's not legal Python (it
> leads to "UnboundLocalError: local variable 'logger' referenced before
> assignment").
>
> Any ideas on the best way to implement this?

You could use a different name:

     def function(self):
         logger2 = logger.getChild('function')
         logger2.debug('stuff')
         logger2.debug('other stuff')

or use 'globals':

     def function(self):
         logger = globals()['logger'].getChild('function')
         logger.debug('stuff')
         logger.debug('other stuff')



More information about the Python-list mailing list