To avoid code execution in your source module during import, you can do two things:
- Remove any code execution from the file and make sure it only defines functions, classes, and variables without doing anything else.
- Use the
__name__namespace and nest your code execution there.
If you nest your code execution in a specific indented block, you'll still be able to run the file directly and have it produce output but avoid unexpected code execution when importing some values from the module.
Dunder Name
To avoid executing code during imports but leaving it in the original module file, you can add the following code to the bottom of your module:
if __name__ == "__main__":
# your code execution goes here
For example, when you want to keep checking for cooked potatoes in ingredients.py, but you don't want to cook when you're just importing the carrot in soup.py, you can change the code in ingredients.py like so:
# ingredients.py
def prepare(ingredient):
return f"cooked {ingredient}"
carrot = "carrot"
salt = "salt"
potato = "potato"
if __name__ == "__main__":
print(prepare(potato))
If you add this line of code and indent the code execution underneath it, you can run ingredients.py as you normally would and receive your cooked potato:
python ingredients.py # OUTPUT: cooked potato
At the same time, if you now head back to soup.py and run the code, you'll see that Python won't cook your potato and instead, it'll only print back the carrot that you wanted to:
# soup.py
from ingredients import carrot
print(carrot) # OUTPUT: carrot
So what happened here? When you add the line if __name__ == "__main__:", you give the following instructions to Python:
if you run this program directly instead of importing it as a module, do the following:
Then, in the indented code block in the next line, you're calling the prepare() function and print its result.
Additional Resources Don't worry if this is confusing; there is no need to break your head with it. If you're interested to learn more, check out the linked resources below.
- Effbot: What is
if name == "main"for? - Mr Fooz on StackOverflow: What does
if name == "main":do? - Joe Sacher: Python: Dunder Name
Summary: Python Dunder Methods
- By adding
if __name__ == "__main__:"to the bottom of your script and indenting any code execution below it, you achieve the following:- Running the module directly executes the nested code logic
- Importing the module in another file skips that code logic
- When you're working with different files and larger programs, this code snippet can come in handy.