Global variable is undefined at the module level

Pieter van Oostrum pieter-l at vanoostrum.org
Sat Nov 23 07:41:15 EST 2019


jacksonhaenchen at gmail.com writes:

> This is not accurate. I just tested this in python3 and using the global
> keyword allowed me to declare a variable inside the function that was
> then visible from the outer scope.

What do you mean by that?
Anything other than what was said here?

> On Tuesday, September 13, 2016 at 6:50:39 AM UTC-5, dieter wrote:

>> In order to define "VVV", you must assign a value to it -- either
>> directly in the "global" (i.e. module) namespace or in your function
>> (together with a "global VVV" declaration).

Without assignment the variable will not exist in the module namespace:
>>> def testfunc():
...     global globvar
...     pass
... 
>>> globvar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'globvar' is not defined
>>> testfunc()
>>> globvar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'globvar' is not defined

>>> def testfunc():
...     global globvar
...     globvar = 1
... 
>>> globvar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'globvar' is not defined
>>> testfunc()
>>> globvar
1


-- 
Pieter van Oostrum
www: http://pieter.vanoostrum.org/
PGP key: [8DAE142BE17999C4]


More information about the Python-list mailing list