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

Time:05-18

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?

CodePudding user response:

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

CodePudding user response:

You access variable parent which us not defined in your code.

CodePudding user response:

Firstly, the MyClass in your code isn't inherited from any other class. Technically, the class doesn't have any parent(except the obj class by default), so it's impossible to access something that doesn't exist like 'parent.debug'. Secondly, as for your problem, I'm assuming that you want to access the debug variable that is initialized outside the class then you can easily do that by doing something like this:

global debug
class MyClass:
     @classmethod
     def fn(self, debug=None):
         if debug is None:
             try:
                 debug = debugOut
             except Exception as e:
                 print(e)
                 debug = "BAD"
     return debug
debugOut = True
x = MyClass()
print(x.fn())

The above code returns True

  • Related