I\'m trying to understand Python\'s approach to variable scope. In this example, why is f()
able to alter the value of x
, as perceived within
You've got a number of answers already, and I broadly agree with J.F. Sebastian, but you might find this useful as a shortcut:
Any time you see varname =
, you're creating a new name binding within the function's scope. Whatever value varname
was bound to before is lost within this scope.
Any time you see varname.foo()
you're calling a method on varname
. The method may alter varname (e.g. list.append
). varname
(or, rather, the object that varname
names) may exist in more than one scope, and since it's the same object, any changes will be visible in all scopes.
[note that the global
keyword creates an exception to the first case]