One of the great things about Python is that we can import functions from one package into a file. We can also import functions and classes from one file into another file. This gives us a powerful way to structure larger projects without having to put everything into one file.
We'll experiment with this style of import by writing a function in a file, and then importing it from another file.
If there's a file named utils.py
,
we can import it from another file in the same directory usingimport
utils
. All the functions and classes defined in utils.py
will
then be available using dot notation. If there's a function calledkeep_time
in utils.py
,
we can access it withutils.keep_time()
after
importing it.
Instructions
Create a file called utils.py
that
contains the following code:
def print_message():
print("Hello from another file!")
Modify the original script.py
file
to instead contain this code:
import utils
if __name__ == "__main__":
utils.print_message()
Both script.py
and utils.py
should
be in the same folder.
Finally, run python script.py
to
print out the message
~$ echo -e 'def print_message():\n print("Hello from another
file!")' > utils.py~$ echo -e 'import utils\n\nif __name__ == "__main__":\n utils.print_message()' > script.py~$ python script.py