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

Liste des GroupesRevenir à cl python 
Sujet : Re: Variable scope inside and outside functions - global statement being overridden by assignation unless preceded by reference
De : cs (at) *nospam* cskk.id.au (Cameron Simpson)
Groupes : comp.lang.python
Date : 07. Mar 2024, 23:48:08
Autres entêtes
Message-ID : <mailman.62.1709851700.3452.python-list@python.org>
References : 1 2
User-Agent : Mutt/2.2.7 (2022-08-07)
On 06Mar2024 15:12, Jacob Kruger <jacob.kruger.work@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.

Date Sujet#  Auteur
8 Mar 24 o Re: Variable scope inside and outside functions - global statement being overridden by assignation unless preceded by reference1Cameron Simpson

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal