Variable scope inside and outside functions - global statement being overridden by assignation unless preceded by reference

Cameron Simpson cs at cskk.id.au
Thu Mar 7 17:48:08 EST 2024


On 06Mar2024 15:12, Jacob Kruger <jacob.kruger.work at gmail.com> wrote:
>So, this does not make sense to me in terms of the following snippet 
>from the official python docs page:
>https://docs.python.org/3/faq/programming.html
>
>"In Python, variables that are only referenced inside a function are 
>implicitly global. If a variable is assigned a value anywhere within 
>the function’s body, it’s assumed to be a local unless explicitly 
>declared as global."
>
>So, I would then assume that if I explicitly include a variable name 
>inside the global statement, then even just assigning it a new value 
>should update the variable in the global context, outside the 
>function?

Yes. Note that the "global" namespace is the module in which the 
function is defined.

     x = 1

     def f(n):
         global x
         x += n

This updates the `x` global variable in the module where `f` was 
defined.

If you import `f` and use it in another module it will _still_ update 
`x` in the original module namespace.


More information about the Python-list mailing list