Globals and the Global Statement

The word “global” strikes fear in the hearts of object-oriented programmers (and structured programmers, for that matter). That's because global variables—variables that are in a global namespace (one that's available to all modules, functions, and classes)—are usually a bad thing and should be avoided.

In fact, there aren't any real global variables in Python. All variables have to be in the context of a module, class, or function. However, Python does have a global statement, which allows you to share variables between functions in the same module.

Here's an example that has two functions and a module-level variable:

 var = "hi" #module level variable def sayHi1(): print var def sayHi2(): print var def sayHiMom(): ...

Get Python Programming with the Java™ Class Libraries: A Tutorial for Building Web and Enterprise Applications with Jython now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.