You could define the variables outside of the function first and then use the global modifier as in the second example. In this simple case however it would probably make more sense to just pass the variables to f2()
(example 1).
You could also take a look at Access a function variable outside the function without using `global` if this is what you are looking for?
You generally also don't want to have code that checks what the caller function is as in this example. In any case your code must not be able to reach a state where a
and b
do not (yet) exist.
example 1
def f1():
a = 10
b = 20
f2(a, b)
def f2(a, b):
print(a)
print(b)
As stated in the comments this is not what you were looking for, so that's why you also have this possibility:
example 2
a=5
b=5
def f1():
global a
global b
a = 10
b = 20
f2()
def f2():
print(a)
print(b)
Calling f1()
will print 10 and 20.