Search code examples
pythonvariablesscope

How to access a variable outside of a class function if it wasn't passed to the function


I have been tasked to modify the behavior of a function in one of our Python classes.

Our function takes a few parameters, one being a debug flag. Currently the if the debug flag is not specified then we assume it to be False. What we need it to do is when debug is not specified, check the variable "debug" from the calling code and use that value, if it exists.

I would simply change the name of the debug parameter in the function declaration, except that we have a lot of legacy code that uses that flag.

This is in Jupyter Lab, if it makes any difference.

Sample code:

class MyClass:
    
    @classmethod
    def fn(self, debug=None):

        if debug is None:
            try:
                debug = parent.debug
            except Exception as e:
                print(e)
                debug = "BAD"
        return debug

debug = True

x = myClass
print( x.fn() )

I would want the output to be "True" but it ends up being:

global name 'parent' is not defined  
BAD

Is what I am trying to do possible? If so, how?


Solution

  • Use globals()['debug'] instead.

    Or replace your fn() method to:

    @classmethod
    def fn(self, debug=None):
    
        if debug is None:
            debug = globals().get('debug', 'BAD')
    
        return debug