2

Consider the programm:

x = 0
def f():
    c = 2      
    def g():
        c = 4
        print(c)
    print(c)

I want that the c in g() is the same as the c in f(). Normally one would use the keyword global within g(), but this is not possible, since global would refer to something outside f() and not within f().

I imagine it this way: the program is the 'first universe'. A function is a new 'second universe' in that big first universe. A function within a function is a 'third universe' within the second universe. And so on. But using global refer immediately to the first universe, no matter in which universe I am. But I want a keyword that goes few universes back and not every universe.

Is this possible? Some kind of using a local variable as a global variable in the smaller scope?

mozway
  • 194,879
  • 13
  • 39
  • 75
ZPlaya7
  • 31
  • 1
  • 4
  • 3
    sounds like you're looking for the `nonlocal` keyword – Robin Zigmond Nov 07 '21 at 11:29
  • I agree with Robin Zigmond. `nonlocal` is what you would use in this case. However, I am just curious: What you are trying to do here based on your description is easier achieved through class inheritance, especially if you go many layers deep. Is Is there any reason why these universes that you describe can't be actual objects inheriting and overriding the attributes rather than functions? – Marc-Alexandru Baetica Nov 07 '21 at 11:34
  • @Marc-AlexandruBaetica That's a nice new approach! I am just not really familiar with classes yet and interpreting functions as objects ^^ – ZPlaya7 Nov 07 '21 at 19:02
  • 1
    Ok. I would recommend finding a beginner HANDS ON tutorial on Python OOP and then another one but with special focus on class inheritance. The only way to learn is by following through and implementing some prototypes. Once you do so, not only will you be a significantly stronger developer but it will lay a foundation on how to build these kind of systems and how to think about problem solving in general :) Good luck. – Marc-Alexandru Baetica Nov 07 '21 at 21:41

0 Answers0