Discussion:
Use of statement 'global' in scripts.
(too old to reply)
Popov, Dmitry Yu
2024-05-08 01:32:32 UTC
Permalink
Dear Sirs.

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? If there are any differences, I would really appreciate any comments on this.

Regards,
Dmitry Popov

Lemont, IL
USA
Greg Ewing
2024-05-08 08:56:00 UTC
Permalink
Post by Popov, Dmitry Yu
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
Popov, Dmitry Yu
2024-05-08 18:52:57 UTC
Permalink
Thank you!
________________________________
From: Python-list <python-list-bounces+dpopov=***@python.org> on behalf of Greg Ewing via Python-list <python-***@python.org>
Sent: Wednesday, May 8, 2024 3:56 AM
To: python-***@python.org <python-***@python.org>
Subject: Re: Use of statement 'global' in scripts.

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,
ZjQcmQRYFpfptBannerStart
This Message Is From an External Sender
This message came from outside your organization.

ZjQcmQRYFpfptBannerEnd
Post by Popov, Dmitry Yu
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
--
https://urldefense.us/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!G_uCfscf7eWS!airWCCS1QeLAhk0AfN3VxhuV9MZkx80000YBhs5Vjf89K2WZP
Loading...