Sujet : Re: Use of statement 'global' in scripts.
De : greg.ewing (at) *nospam* canterbury.ac.nz (Greg Ewing)
Groupes : comp.lang.pythonDate : 08. May 2024, 09:56:00
Autres entêtes
Message-ID : <la0t13F1s8iU1@mid.individual.net>
References : 1 2
User-Agent : Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:91.0) Gecko/20100101 Thunderbird/91.3.2
On 8/05/24 1:32 pm, Popov, Dmitry Yu wrote:
The statement 'global', indicating variables living in the global scope, is very suitable to be used in modules. I'm wondering whether in scripts, running at the top-level invocation of the interpreter, statement 'global' is used exactly the same way as in modules?
The 'global' statement declares a name to be module-level, so there's no
reason to use it at the top level of either a script or a module, since
everything there is module-level anyway.
You only need it if you want to assign to a module-level name from
within a function, e.g.
spam = 17
def f():
global spam
spam = 42
f()
# spam is now 42
A script is a module, so everything that applies to modules also
applies to scripts.
-- Greg