Python Forum

Full Version: Getting parent variables in nested functions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I made my own custom assembly language in Python for fun, and want to implement it into a GUI. I am in the process of creating a library version of it which allow for giving it functions as input and output devices. I have run into a problem, though. Here's a simplified version of the problem:
def layer1():
  parentvariable='Info'
  print(parentvariable)
  def layer2():
    parentvariable='New Info'
  layer2()
  print(parentvariable)
Of course, this wouldn't work and would give me an error. How do I get around this? this is quite crucial to the function of the language. Is there something like global except for a parent function?
def layer1():
  parentvariable='Info'
  print(parentvariable)
  def layer2():
    nonlocal parentvariable
    parentvariable='New Info'
  layer2()
  print(parentvariable)

layer1()
Note, I am not sure exactly why you want this and thus there might be better approach overall to what you try to do. It's very likely a XY problem.