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

Grant Edwards grant.b.edwards at gmail.com
Tue Mar 5 17:46:32 EST 2024


On 2024-03-05, Cameron Simpson via Python-list <python-list at python.org> wrote:

> Because there are no variable definitions in Python, when you write
> a function Python does a static analysis of it to decide which
> variables are local and which are not. If there's an assignment to a
> variable, it is a local variable.  _Regardless_ of whether that
> assignment has been executed, or gets executed at all (eg in an
> if-statement branch which doesn't fire).

Unfortunately, crap "information" sites like geeksforgeeks often
describe this either incorrectly or so vaguely as to be worthless.
>From the page https://www.geeksforgeeks.org/global-local-variables-python/

     Python Global variables are those which are not defined inside
     any function and have a global scope whereas Python local
     variables are those which are defined inside a function and their
     scope is limited to that function only.

Since "define" (in this context) isn't a term of art in Python, and
it's never defined on the page in question, the quoted paragraph is
not meaningful: it simply says that "global variables are global and
local variables are local".

That page goes on to say:

     In other words, we can say that local variables are accessible
     only inside the function in which it was initialized

This is equally crap. It doesn't matter whether the variable is
initialized or not. As Cameron correctly stated, if a function
contains an assignment to a variable, and that variable is not
declared global, then that variable is local.  For example:

    def foo():
        print(s)
        if 0:
            s = "there"
        print(s)

In the function above s _is_not_ initialized in the function foo().
However, foo() does contain an assignment to s, therefore s is local
unless declared global/nonlocal.  [And the first print() will throw an
exception even if there is a value bound to the global name 's'.]

Unfortunately (presumably thanks to SEO) the enshittification of
Google has reached the point where searching for info on things like
Python name scope, the first page of links are to worthless sites like
geeksforgeeks.



More information about the Python-list mailing list