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, callee1.py…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 caller1.py which will call and execute callee1.py instead of rewriting the same code for word input and validation. If the word is valid (as computed by callee1.py) the caller1.py will take other actions, such as start a round of game or other calculations. So, you need a way for caller1.py to “know” if the word was valid as set by callee1.py. 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 callee1.py. Since the codes are in completely different files or modules, we have to find a way to access the variable x from caller1.py as well from a single program. One of the solutions is to use the config module.
First, you create a config.py file with the line:
x = 0
Or whatever the default value or name you want. Then in both the callee1.py and calller2.py, we need to import the config file with:
In this example, your caller1.py will also need to either import the callee1.py module or just execute it using exec() as:
Back in the callee1.py 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):
After you’ve executed callee1.py and it set config.x, it’s time to check its value in the caller1.py. You can access the same variable the same way since you’ve imported config module in caller1.py also. It can be something like:
# start round 1 of a guessing game or hangman etc.
# invalid word entered, do something else
The whole process can be visualized as below:
Note that you can indeed have more than one variable in config.py and of any data type. This whole x variable exchange occurs in memory so it’s very fast. You may also notice that the config.py file content, such as the values assigned by callee1.py 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!