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
nonlocal myvarinsidedef runbefore assignment.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 yourrunfunction return the value ofmyvar, and then simply capture the resulting value in the caller