Python File as an Isolated Module
🏷️ Modules and Imports / What is a Module?
🌱 Context Introduction
When you write Python code, every .py file you create is automatically a module. Think of a module as a self-contained container of code — like a toolbox that holds related functions, classes, and variables. The key idea is isolation: each module has its own namespace, meaning variables and functions inside one module won't accidentally interfere with another module unless you explicitly choose to share them.
This isolation makes your code organized, reusable, and easier to debug. Instead of writing one giant script, you break your program into smaller, focused files that each handle a specific responsibility.
🧱 What Makes a Python File an Isolated Module?
- Every .py file is a module — no special declaration needed.
- The filename (without .py) becomes the module name.
- Variables, functions, and classes defined in the file are private by default — they only exist within that module's namespace.
- To use code from another module, you must import it, which brings only what you explicitly request into your current namespace.
- This isolation prevents name collisions — you can have a function called calculate() in multiple modules without conflict.
⚙️ How Isolation Works in Practice
When Python runs a module, it creates a separate namespace for that file. Consider two files:
File: calculator.py - Contains a function called add(a, b) that returns a + b - Contains a variable PI = 3.14159
File: main.py - Contains its own variable PI = 3.14 - Imports calculator and calls calculator.add(5, 3)
Even though both files have a variable named PI, they are completely separate. Changing PI in main.py does not affect PI in calculator.py, and vice versa. This is the core benefit of module isolation.
🛠️ Key Benefits of Module Isolation
- Reusability: Write a module once and use it across many projects
- Maintainability: Fix or update code in one module without touching others
- Testability: Test each module independently
- Collaboration: Multiple engineers can work on different modules simultaneously
- Encapsulation: Hide internal implementation details from other parts of the program
🕵️ Understanding Namespace Isolation
| Concept | Explanation |
|---|---|
| Module namespace | Each module has its own dictionary of names (variables, functions, classes) |
| Global scope | Names defined at the top level of a module belong to that module's namespace |
| Import behavior | Importing a module does not merge namespaces — it creates a reference to the module object |
| Name collision prevention | Two modules can define the same name without conflict because they live in separate namespaces |
📦 How to Use a Module from Another File
To use code from one module in another, you use the import statement. The module name is the filename without the .py extension.
Example scenario: - You have a file named helpers.py that contains a function format_date() - In your app.py file, you want to use that function
You would write in app.py: import helpers and then call helpers.format_date()
The dot notation (module_name.function_name) is how you access isolated content from another module. This makes it clear where each piece of code comes from.
🧩 What Happens When a Module is Imported
When Python encounters an import statement, it does the following:
- Searches for the .py file in specific locations (current directory, installed packages, etc.)
- Executes the entire module file from top to bottom
- Creates a module object with its own namespace
- Makes that module object available in the importing file under the module name
This means any top-level code in the imported module runs immediately. If your module has print statements or variable assignments at the top level, those execute when the module is first imported.
🔒 Protecting Code from Running on Import
Sometimes you want code in a module to run only when that module is executed directly, not when it is imported. Python provides a built-in mechanism for this:
- Every module has a special variable called name
- When a module is run directly, name is set to "main"
- When a module is imported, name is set to the module's filename (without .py)
You can use this to create a guard that prevents certain code from executing during import:
In your module file, place code that should only run when executed directly inside a conditional block: if name == "main":
This pattern is extremely common and allows a file to serve dual purposes — as a reusable module and as a standalone script.
🧠 Best Practices for Module Isolation
- Keep each module focused on a single responsibility or related set of functions
- Use descriptive filenames that indicate the module's purpose
- Avoid circular imports (Module A imports Module B, and Module B imports Module A)
- Use the if name == "main" guard for test code or example usage
- Group related modules into packages (folders with an init.py file) for larger projects
- Import only what you need using from module import specific_item when appropriate
✅ Summary
A Python file as an isolated module is the fundamental building block of organized Python programs. Each .py file creates its own namespace, keeping its contents separate from other files. This isolation prevents naming conflicts, promotes code reuse, and makes large codebases manageable. By understanding how modules work and how to import them, you can structure your Python projects in a clean, scalable way.
A Python file becomes an isolated module when it contains reusable code that can be imported into other Python files without running its full contents.
🧱 Example 1: Creating a simple module file
This example shows how a single Python file acts as a module when it contains only definitions.
# Save this as: greetings.py
def say_hello():
return "Hello, engineer!"
def say_goodbye():
return "Goodbye, engineer!"
📤 Output: (no output — file is a module, not executed directly)
🔌 Example 2: Importing a module into another file
This example demonstrates importing the module and calling its functions from a separate file.
# Save this as: main.py
import greetings
result1 = greetings.say_hello()
result2 = greetings.say_goodbye()
print(result1)
print(result2)
📤 Output: Hello, engineer!
Goodbye, engineer!
🛡️ Example 3: Preventing module code from running on import
This example shows how to use if __name__ == "__main__" to isolate test code from the module.
# Save this as: calculator.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
if __name__ == "__main__":
print("Running calculator module directly")
print(add(3, 4))
# Save this as: use_calculator.py
import calculator
total = calculator.add(10, 20)
product = calculator.multiply(5, 6)
print(total)
print(product)
📤 Output: 30
30
🧩 Example 4: Module with variables and constants
This example shows a module that stores shared configuration values for other files to use.
# Save this as: config.py
PI = 3.14159
MAX_RETRIES = 5
DATABASE_NAME = "engineer_db"
def get_config():
return {"pi": PI, "max_retries": MAX_RETRIES, "db": DATABASE_NAME}
# Save this as: app.py
import config
print(config.PI)
print(config.MAX_RETRIES)
print(config.get_config()["db"])
📤 Output: 3.14159
5
engineer_db
📦 Example 5: Module with a class for reuse
This example demonstrates a module containing a class that engineers can instantiate in other files.
# Save this as: sensor.py
class TemperatureSensor:
def __init__(self, name):
self.name = name
self.temperature = 25.0
def read_temperature(self):
return self.temperature
def set_temperature(self, value):
self.temperature = value
# Save this as: monitor.py
from sensor import TemperatureSensor
sensor1 = TemperatureSensor("Engine Room")
sensor2 = TemperatureSensor("Cooling Unit")
sensor1.set_temperature(32.5)
sensor2.set_temperature(18.0)
print(sensor1.read_temperature())
print(sensor2.read_temperature())
📤 Output: 32.5
18.0
📊 Comparison: Direct Execution vs Module Import
| Behavior | Direct Execution (python file.py) |
Module Import (import file) |
|---|---|---|
| Code runs immediately | ✅ Yes | ❌ No (only definitions load) |
if __name__ == "__main__" block runs |
✅ Yes | ❌ No |
| Functions/classes available to other files | ❌ No | ✅ Yes |
| Variables persist for reuse | ❌ No | ✅ Yes |
| Best for | Testing, standalone scripts | Reusable libraries, shared code |
🌱 Context Introduction
When you write Python code, every .py file you create is automatically a module. Think of a module as a self-contained container of code — like a toolbox that holds related functions, classes, and variables. The key idea is isolation: each module has its own namespace, meaning variables and functions inside one module won't accidentally interfere with another module unless you explicitly choose to share them.
This isolation makes your code organized, reusable, and easier to debug. Instead of writing one giant script, you break your program into smaller, focused files that each handle a specific responsibility.
🧱 What Makes a Python File an Isolated Module?
- Every .py file is a module — no special declaration needed.
- The filename (without .py) becomes the module name.
- Variables, functions, and classes defined in the file are private by default — they only exist within that module's namespace.
- To use code from another module, you must import it, which brings only what you explicitly request into your current namespace.
- This isolation prevents name collisions — you can have a function called calculate() in multiple modules without conflict.
⚙️ How Isolation Works in Practice
When Python runs a module, it creates a separate namespace for that file. Consider two files:
File: calculator.py - Contains a function called add(a, b) that returns a + b - Contains a variable PI = 3.14159
File: main.py - Contains its own variable PI = 3.14 - Imports calculator and calls calculator.add(5, 3)
Even though both files have a variable named PI, they are completely separate. Changing PI in main.py does not affect PI in calculator.py, and vice versa. This is the core benefit of module isolation.
🛠️ Key Benefits of Module Isolation
- Reusability: Write a module once and use it across many projects
- Maintainability: Fix or update code in one module without touching others
- Testability: Test each module independently
- Collaboration: Multiple engineers can work on different modules simultaneously
- Encapsulation: Hide internal implementation details from other parts of the program
🕵️ Understanding Namespace Isolation
| Concept | Explanation |
|---|---|
| Module namespace | Each module has its own dictionary of names (variables, functions, classes) |
| Global scope | Names defined at the top level of a module belong to that module's namespace |
| Import behavior | Importing a module does not merge namespaces — it creates a reference to the module object |
| Name collision prevention | Two modules can define the same name without conflict because they live in separate namespaces |
📦 How to Use a Module from Another File
To use code from one module in another, you use the import statement. The module name is the filename without the .py extension.
Example scenario: - You have a file named helpers.py that contains a function format_date() - In your app.py file, you want to use that function
You would write in app.py: import helpers and then call helpers.format_date()
The dot notation (module_name.function_name) is how you access isolated content from another module. This makes it clear where each piece of code comes from.
🧩 What Happens When a Module is Imported
When Python encounters an import statement, it does the following:
- Searches for the .py file in specific locations (current directory, installed packages, etc.)
- Executes the entire module file from top to bottom
- Creates a module object with its own namespace
- Makes that module object available in the importing file under the module name
This means any top-level code in the imported module runs immediately. If your module has print statements or variable assignments at the top level, those execute when the module is first imported.
🔒 Protecting Code from Running on Import
Sometimes you want code in a module to run only when that module is executed directly, not when it is imported. Python provides a built-in mechanism for this:
- Every module has a special variable called name
- When a module is run directly, name is set to "main"
- When a module is imported, name is set to the module's filename (without .py)
You can use this to create a guard that prevents certain code from executing during import:
In your module file, place code that should only run when executed directly inside a conditional block: if name == "main":
This pattern is extremely common and allows a file to serve dual purposes — as a reusable module and as a standalone script.
🧠 Best Practices for Module Isolation
- Keep each module focused on a single responsibility or related set of functions
- Use descriptive filenames that indicate the module's purpose
- Avoid circular imports (Module A imports Module B, and Module B imports Module A)
- Use the if name == "main" guard for test code or example usage
- Group related modules into packages (folders with an init.py file) for larger projects
- Import only what you need using from module import specific_item when appropriate
✅ Summary
A Python file as an isolated module is the fundamental building block of organized Python programs. Each .py file creates its own namespace, keeping its contents separate from other files. This isolation prevents naming conflicts, promotes code reuse, and makes large codebases manageable. By understanding how modules work and how to import them, you can structure your Python projects in a clean, scalable way.
Interactive Views
You are currently in 📚 All-in-One mode. Use the tabs at the top to switch to 📖 Theory Only or 💻 Code Only views.
A Python file becomes an isolated module when it contains reusable code that can be imported into other Python files without running its full contents.
🧱 Example 1: Creating a simple module file
This example shows how a single Python file acts as a module when it contains only definitions.
# Save this as: greetings.py
def say_hello():
return "Hello, engineer!"
def say_goodbye():
return "Goodbye, engineer!"
📤 Output: (no output — file is a module, not executed directly)
🔌 Example 2: Importing a module into another file
This example demonstrates importing the module and calling its functions from a separate file.
# Save this as: main.py
import greetings
result1 = greetings.say_hello()
result2 = greetings.say_goodbye()
print(result1)
print(result2)
📤 Output: Hello, engineer!
Goodbye, engineer!
🛡️ Example 3: Preventing module code from running on import
This example shows how to use if __name__ == "__main__" to isolate test code from the module.
# Save this as: calculator.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
if __name__ == "__main__":
print("Running calculator module directly")
print(add(3, 4))
# Save this as: use_calculator.py
import calculator
total = calculator.add(10, 20)
product = calculator.multiply(5, 6)
print(total)
print(product)
📤 Output: 30
30
🧩 Example 4: Module with variables and constants
This example shows a module that stores shared configuration values for other files to use.
# Save this as: config.py
PI = 3.14159
MAX_RETRIES = 5
DATABASE_NAME = "engineer_db"
def get_config():
return {"pi": PI, "max_retries": MAX_RETRIES, "db": DATABASE_NAME}
# Save this as: app.py
import config
print(config.PI)
print(config.MAX_RETRIES)
print(config.get_config()["db"])
📤 Output: 3.14159
5
engineer_db
📦 Example 5: Module with a class for reuse
This example demonstrates a module containing a class that engineers can instantiate in other files.
# Save this as: sensor.py
class TemperatureSensor:
def __init__(self, name):
self.name = name
self.temperature = 25.0
def read_temperature(self):
return self.temperature
def set_temperature(self, value):
self.temperature = value
# Save this as: monitor.py
from sensor import TemperatureSensor
sensor1 = TemperatureSensor("Engine Room")
sensor2 = TemperatureSensor("Cooling Unit")
sensor1.set_temperature(32.5)
sensor2.set_temperature(18.0)
print(sensor1.read_temperature())
print(sensor2.read_temperature())
📤 Output: 32.5
18.0
📊 Comparison: Direct Execution vs Module Import
| Behavior | Direct Execution (python file.py) |
Module Import (import file) |
|---|---|---|
| Code runs immediately | ✅ Yes | ❌ No (only definitions load) |
if __name__ == "__main__" block runs |
✅ Yes | ❌ No |
| Functions/classes available to other files | ❌ No | ✅ Yes |
| Variables persist for reuse | ❌ No | ✅ Yes |
| Best for | Testing, standalone scripts | Reusable libraries, shared code |