To load any module, whether a built-in module or a custom module you create, use the import statement. Then after importing the module, you can reference code contained within.
To see this concept in action, create a new directory on your computer called "modules-overview" and place inside the following two files...
Script:
# modules-overview/my_script.pyimport my_moduleprint("IMPORTING MY MODULE ...")my_module.my_message()
Module:
# modules-overview/my_module.py# anything in the global scope of this file will be executed immediately when the module is imported.# ... so we generally wrap all the code inside separate functions, which can later be invoked as desired.defmy_message():print("HELLO FROM A MODULE")defother_message():print("GREETINGS EARTHLING")# but if we want something to happen when the module is invoked directly from the command line (as a script)# ... we can use this special conditional to detect that use case and perform instructions as desired.if__name__=="__main__":print("INVOKING MY MODULE AS A SCRIPT...")my_message()
Then execute the script to prove it has access to code in the module:
pythonmy_script.py#> IMPORTING MY MODULE ...#> HELLO FROM A MODULE
It is also possible to execute the module directly:
pythonmy_module.py#> INVOKING MY MODULE AS A SCRIPT...#> HELLO FROM A MODULE
Modules in Subdirectories
If your python file is located in a subdirectory, you can reference it using the [directory name].[file name]. Like this:
# modules-overview/things/robot.pydefrobot_message():print("HELLO I'M A ROBOT")
# modules-overview/robot_script.pyimport things.robot as botbot.robot_message()