Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading