Wednesday, April 17, 2024
Coding STEM

Share variables across different modules – Python

There are several ways we can share a variable’s value or multiple variables’ values set across different modules or code files. One of the easiest and efficient way is taking advantage of config module in Python. In this post, I demonstrate exactly how it’s done.

Imagine the scenario where you have a python module that you wrote that allows user inputs for a word. The code file is, say,…it checks for valid inputs, required length of the word, and also checks the input against an canonical dictionary file and gives feedback to the user if the word is valid or not.

You have another Python program called which will call and execute instead of rewriting the same code for word input and validation. If the word is valid (as computed by the will take other actions, such as start a round of game or other calculations. So, you need a way for to “know” if the word was valid as set by Maybe you decide to set a variable called x and set it to 0 if the word is invalid, and to 1 if the word is valid…set by Since the codes are in completely different files or modules, we have to find a way to access the variable x from as well from a single program. One of the solutions is to use the config module.

First, you create a file with the line:

x = 0

Or whatever the default value or name you want. Then in both the and, we need to import the config file with:

import config

In this example, your will also need to either import the module or just execute it using exec() as:


Back in the of course, you need to set the value for x. For example if word is found, you set it to 1, otherwise 0. The actual assignment can be done simply as below (the conditions are up to you):

if (wordfound):

After you’ve executed and it set config.x, it’s time to check its value in the You can access the same variable the same way since you’ve imported config module in also. It can be something like:

if (config.x):
   # start round 1 of a guessing game or hangman etc.
   # invalid word entered, do something else

The whole process can be visualized as below:

Figure 1

Note that you can indeed have more than one variable in and of any data type. This whole x variable exchange occurs in memory so it’s very fast. You may also notice that the file content, such as the values assigned by does not change. The values are only valid during the application session but the variable name is persisted after exit.

Hope you found this tip useful.

Interested in creating programmable, cool electronic gadgets? Give my newest book on Arduino a try: Hello Arduino!

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top