Importing Modules with the import Statement
The most common way to use a module is to import it using the import statement. This makes all the code in the module available to your current script.
In the file explorer, you will find an empty file named main.py. This will be our main script for the rest of the lab.
Open main.py and add the following line to import the hello module:
import hello
print("The main.py script has finished.")
Save the file. Now, run main.py from the terminal:
python3 main.py
Observe the output carefully:
This code runs on import or direct execution.
The main.py script has finished.
Notice that only the first print statement from hello.py was executed. The code inside the if __name__ == "__main__": block was skipped. This is because when main.py imports hello, the __name__ variable within the hello.py context is set to "hello" (the module's name), not "__main__". This feature is essential for creating reusable modules that don't produce unwanted side effects upon import.
Now, let's work with a module that contains more than just print statements. Open the module_a.py file. It contains a variable, a function, and a class.
PI = 3.14159
def greet(name):
print(f"Hello, {name} from module_a!")
class Calculator:
def add(self, x, y):
return x + y
Modify main.py to import module_a and use its members. To access a member of an imported module, you use the syntax module_name.member_name.
Replace the content of main.py with the following:
import module_a
## Access the PI variable
print(f"The value of PI is {module_a.PI}")
## Call the greet function
module_a.greet("LabEx")
## Create an instance of the Calculator class and use its method
calc = module_a.Calculator()
result = calc.add(5, 3)
print(f"5 + 3 = {result}")
Save the file and run it:
python3 main.py
The output will be:
The value of PI is 3.14159
Hello, LabEx from module_a!
5 + 3 = 8
This demonstrates how the import statement loads an entire module, and you access its contents using the module's name as a prefix.