Modules and Imports
Consider the following example, where we are defining a utility function called enlarge
in a given file, and importing that function for use in other files.
The “main conditional” (if __name__ == "__main__":
) prevents anything nested inside from being executed when we import code from this file. Without this in place, in the example below, we wouldn’t be able to import from this file because it would be waiting for a user input. So instead we place the user input inside the conditional:
# this is the "app/utils.py" file...
def enlarge(n):
return float(n) * 100
if __name__ == "__main__":
# this "main conditional" says:
# only run the code below if this file is run from the command line
# but not when importing from this file
= input("Please input a number")
x = enlarge(x)
result print(result)
With the “main conditional” in place, we can import the function from here cleanly, for example in another file called “my_script.py”:
# this is the "app/my_script.py" file...
from app.utils import enlarge
= enlarge(9)
result print(result)
If a Python module is located in a subdirectory like this, we can reference it using dot notation, like import directory_name.file_name
.
When the file we are running imports code from another file, we must run them using “modular style invocation” (python -m directory_name.file_name]
).
Running the files:
python -m app.utils
python -m app.my_script
Notice the “main conditional” allows us to run the “utils.py” file from the command line, while still being able to import from it cleanly.