'Python global variables : too global for me
Below, I would like the s var be global to the f function, but local to the principal function.
It seems global means "The Most Global in the Module".
How can I make one less global scope ?
s="what the hell"
print(s)
def principal():
s ="hey"
def f():
global s
if len(s) < 8:
s += " !"
f()
f()
return s
print(principal())
what the hell
hey
Solution 1:[1]
I'm not sure if this is what you are going for, since global has an unambiguous meaning in Python. If you want to modify the variable s as defined in principal() within f() you can use nonlocal:
s="what the hell"
print(s)
def principal():
s = "hey"
def f():
nonlocal s
if len(s) < 8:
s += " !"
f()
f()
return s
print(principal())
But the real goal here would probably be, to avoid constructs like that altogether and pass the respective variables as arguments and return the modified values from (pure) functions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Richard Neumann |
