In Python, can I create a global variable inside a function and then use it in a different function?
Learn to make variables globally available from within a function, as well as the associated risks and caveats.
Python’s function scoping mechanism allows for the separation of variables and code blocks to aid in the modularization and organization of Python code. However, programmers sometimes need to subvert this mechanism and make variables defined within a function available to be used globally by other functions. In this hands-on tutorial David Blaikie explains the creation of global variables within functions, as well as the associated risks and caveats. Python beginners with a basic knowledge of variable assignment will further their understanding of variable scoping, which is essential to proper code design in Python.
David Blaikie is a New York City-based engineer and trainer. He has taught Python, Advanced Python, Perl, and Advanced Perl at New York University’s School of Professional Studies, and has conducted corporate Python training for companies such as Google, Cisco, and Bloomberg, as well as for the U.S. Navy. David has been a release engineer at Google and a software developer for AppNexus, Conde Nast, and several startups. He is also the author of the bestselling O’Reilly book “Python Beyond the Basics: Object-Oriented Programming.” David’s contact information can be found at www.clearpython.com.