Python Forum
Getting parent variables in nested functions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Getting parent variables in nested functions
#1
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?
Reply
#2
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.
wallgraffiti likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  using variables with functions imported from different files. Scordomaniac 3 1,216 May-24-2022, 10:53 AM
Last Post: deanhystad
  Nested functions: calculation is not performed alexfrol86 4 1,621 Feb-24-2022, 05:32 PM
Last Post: alexfrol86
  Nested functions. Equation equal to zero works in a wrong way alexfrol86 6 1,884 Feb-22-2022, 02:57 PM
Last Post: alexfrol86
  Storing whole functions in variables dedesssse 3 2,052 Jul-29-2021, 09:17 PM
Last Post: deanhystad
  Nested Python functions (Dan Bader's book) Drone4four 4 2,522 Jun-26-2021, 07:54 AM
Last Post: ndc85430
Question Stopping a parent function from a nested function? wallgraffiti 1 3,613 May-02-2021, 12:21 PM
Last Post: Gribouillis
  module to store functions/variables and how to call them? mstichler 3 2,338 Jun-03-2020, 06:49 PM
Last Post: mstichler
  Getter/Setter : get parent attribute, but no Getter/Setter in parent nboweb 2 2,909 May-11-2020, 07:22 PM
Last Post: nboweb
  local/global variables in functions abccba 6 3,356 Apr-08-2020, 06:01 PM
Last Post: jefsummers
  Python 2.7 passing variables from functions zetto33 1 1,750 Mar-19-2020, 07:27 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020