Use of “global” keyword in Python

What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to use global.

I’m using Python 2.7 and I tried this little test

>>> sub = ['0', '0', '0', '0']
>>> def getJoin():
...     return '.'.join(sub)
...
>>> getJoin()
'0.0.0.0'

It seems things are working fine even without global. I was able to access global variable without any problem.

Am I missing anything? Also, following is from Python documentation:

Names listed in a global statement
must not be defined as formal
parameters or in a for loop control
target, class definition, function
definition, or import statement.

While formal parameters and class definition make sense to me, I’m not able to understand the restriction on for loop control target and function definition.

11 Answers
11

Leave a Comment