0

I'd like to define a class inside a function (for testing purpose) and put a value into a function variable:

def foo():
    myvar = None
    class myclass:
        def run(self):
            myvar = 5

    mm = myclass()
    mm.run()
    print(myvar)

The above prints None

Is there any way other than global to make the myvar variable accessible from the class? The correct answer would print 5

4
  • 3
    Nope, and that's isn't a good practive to do so. Don't try tricky manipulation Commented Nov 25, 2020 at 18:50
  • Add nonlocal myvar inside def run before assignment. Commented Nov 25, 2020 at 19:04
  • Why would you want to do this? This defeats the entire purpose of a class, which is to encapsulate state. As stated above though, you can use nonlocal myvar, which makes it assign to the closest enclosing scope, in this case, the local scope of the function. More reasonably, you should just have your run function return the value of myvar, and then simply capture the resulting value in the caller Commented Nov 25, 2020 at 19:06
  • @juanpa.arrivillaga this is not a helpful answer. Please answer the question first and then provide your opinion. Commented Nov 26, 2020 at 14:52

1 Answer 1

1

It's not possible to assign a value to a variable outside the current scope without global. If you need to persist the value within the class you can define class variables instead. Example:

def foo():
    class Class:
        var_to_change = None
        def run (self):
            self.var_to_change = 5
    print (Class.var_to_change)
    instance = Class()
    instance.run()
    print (Class.var_to_change)

I haven't tested the above code but it should work in theory.

Sign up to request clarification or add additional context in comments.

2 Comments

this will also print None. Also, in this case, it is possible with nonlocal.
I had no idea there was something like nonlocal. Wow!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.