From 2d527fc07e274b71637146f97e3cc7dc3b3e760c Mon Sep 17 00:00:00 2001 From: jkjack Date: Sun, 22 Mar 2026 18:00:41 -0300 Subject: [PATCH] FIX: prevent my_classes.py from executing on import --- src/modules.py | 2 +- src/my_classes.py | 15 +++++++++------ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/modules.py b/src/modules.py index 57d1d9a..a381597 100644 --- a/src/modules.py +++ b/src/modules.py @@ -3,7 +3,7 @@ from my_classes import MyAge my_age = MyAge("1985-01-01", "Mr James") -my_age.show_me_my_age() +print(my_age.show_me_my_age()) # > 'Mr James, you are so young, only 41 years old!' # additional learexample with the import as command diff --git a/src/my_classes.py b/src/my_classes.py index 6cdb0d8..05f5d88 100644 --- a/src/my_classes.py +++ b/src/my_classes.py @@ -14,9 +14,12 @@ def __init__(self, date_of_birth, my_name): # create print function def show_me_my_age(self): return f"{self.__my_name}, you are so young, only {self.__my_age_years} years old!" - - -# instantiate the class and execute the print function -age = MyAge("1982-08-04", "Mr James") -print(age.show_me_my_age()) -# > 'Mr James, you are so young, only 39 years old!' \ No newline at end of file +# Fix for the issue shown in training video "Python for data engineers > Advanced Python > Modules": +# Without this guard, importing this file from modules.py would also execute the block below, +# printing the hardcoded date instead of the date passed by the caller. +# if __name__ == "__main__" ensures this block only runs when this file is executed directly. +if __name__ == "__main__": + # instantiate the class and execute the print function + age = MyAge("1982-08-04", "Mr James") + print(age.show_me_my_age()) + # > 'Mr James, you are so young, only 46 years old!' \ No newline at end of file