In python we can declare a global variable which will be accessible by other functions.
my_global_var = 2
# foo can only access the variable for reading
def foo():
print(my_global_var)
# bar can also write into the global variable
def bar():
global my_global_var
print(my_global_var)
This works, however suppose that I don't want to create the global variable outside foo
and bar
, but instead I want foo
to create a local variable and extend the scope of this variable to bar (and any other function) without passing it as a parameter.
Something like
def foo():
# the scope of this variable is only foo. Can I make it global?
my_global_var = 4
# bar wants to be able to access (and maybe modify) the variable created by foo
def bar():
global my_global_var
print(my_global_var)
PD: For the comments I think my question is not understood.
It is clearly not a duplicate of that other question, since I know how to use global variables (the first example in the question uses them).
And I'm also not asking for suggestions about passing the variables as parameters or not using global variables.
My question is very specific. Can I extend the scope of a local variable into a global variable?
It's either yes, it can be done this way or No, this cannot be done. And if the answer is yes I would like to know how can be done.