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.

By David Blaikie
September 8, 2016
Screenshot from "Creating a global variable within a function in Python" Screenshot from "Creating a global variable within a function in Python"

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.

Click here to grow your Python skills with our Python Learning Path.

Learn faster. Dig deeper. See farther.

Join the O'Reilly online learning platform. Get a free trial today and find answers on the fly, or master something new and useful.

Learn more

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.

Post topics: Software Engineering
Post tags: Questions
Share: