Dans une étendue Python, toute affectation à une variable non déjà déclarée dans cette étendue crée une nouvelle variable locale à moins que cette variable ne soit déclarée plus tôt dans la fonction comme faisant référence à une variable de portée globale avec le mot clé global.
Regardons une version modifiée de votre pseudocode pour voir ce qui se passe:
# Here, we're creating a variable 'x', in the __main__ scope.
x = 'None!'
def func_A():
# The below declaration lets the function know that we
# mean the global 'x' when we refer to that variable, not
# any local one
global x
x = 'A'
return x
def func_B():
# 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
En fait, vous pourriez tout réécrire func_Bavec la variable nommée x_localet cela fonctionnerait de manière identique.
L'ordre n'a d'importance que dans la mesure où vos fonctions effectuent des opérations qui modifient la valeur du x global. Ainsi, dans notre exemple, l'ordre n'a pas d'importance, car les func_Bappels func_A. Dans cet exemple, l'ordre importe:
def a():
global foo
foo = 'A'
def b():
global foo
foo = 'B'
b()
a()
print foo
# prints 'A' because a() was the last function to modify 'foo'.
Notez que cela globaln'est nécessaire que pour modifier des objets globaux. Vous pouvez toujours y accéder depuis une fonction sans déclarer global. Ainsi, nous avons:
x = 5
def access_only():
return x
# This returns whatever the global value of 'x' is
def modify():
global x
x = 'modified'
return x
# This function makes the global 'x' equal to 'modified', and then returns that value
def create_locally():
x = 'local!'
return x
# This function creates a new local variable named 'x', and sets it as 'local',
# and returns that. The global 'x' is untouched.
Notez la différence entre create_locallyet access_only- access_onlyaccède au x global sans appeler global, et même s'il create_locallyn'utilise pas non globalplus, il crée une copie locale car il attribue une valeur.
La confusion ici est la raison pour laquelle vous ne devez pas utiliser de variables globales.