PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 19, 2022

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

 May 19, 2022     python, scope, variables     No comments   

Issue

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


Answered By - Егор Зенкин
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing