Getting parent variables in nested functions - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Getting parent variables in nested functions (/thread-32250.html) |
Getting parent variables in nested functions - wallgraffiti - Jan-30-2021 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? RE: Getting parent variables in nested functions - buran - Jan-30-2021 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. |