Within a Python scope, any assignment to a variable not already declared within that scope creates a new local variable unless that variable is declared earlier in the function as referring to a globally scoped variable with the keyword
Let's look at a modified version of your pseudocode to see what happens:
# Here, we're creating a variable 'x', in the __main__ scope.
x = 'None!'
# The below declaration lets the function know that we
# mean the global 'x' when we refer to that variable, not
# any local one
x = 'A'
# Here, we are somewhat mislead. We're actually involving two different
# variables named 'x'. One is local to func_B, the other is global.
# By calling func_A(), we do two things: we're reassigning the value
# of the GLOBAL x as part of func_A, and then taking that same value
# since it's returned by func_A, and assigning it to a LOCAL variable
# named 'x'.
x = func_A() # look at this as: x_local = func_A()
# Here, we're assigning the value of 'B' to the LOCAL x.
x = 'B' # look at this as: x_local = 'B'
return x # look at this as: return x_local
In fact, you could rewrite all of
func_B with the variable named
x_local and it would work identically.
The order matters only as far as the order in which your functions do operations that change the value of the global x. Thus in our example, order doesn't matter, since
func_A. In this example, order does matter:
foo = 'A'
foo = 'B'
# prints 'A' because a() was the last function to modify 'foo'.
global is only required to modify global objects. You can still access them from within a function without declaring
Thus, we have:
x = 5
# This returns whatever the global value of 'x' is
x = 'modified'
# This function makes the global 'x' equal to 'modified', and then returns that value
x = 'local!'
# This function creates a new local variable named 'x', and sets it as 'local',
# and returns that. The global 'x' is untouched.
Note the difference between
access_only is accessing the global x despite not calling
global, and even though
create_locally doesn't use
global either, it creates a local copy since it's assigning a value.
The confusion here is why you shouldn't use global variables.