Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
157: The import Statement and Its Variants
By now, you've probably been using import for a while, but if you're just doing import math or import os, you're missing out on some of the nuance that makes large projects manageable. When a project grows from one file to fifty, how you bring in your dependencies determines whether your code is a clean map or a tangled web of naming conflicts.
Let's build a simple "Expense Reporter." I've already written a helper module called finance_utils.py that contains a few functions for currency formatting and tax calculation. Here is what that file looks like:
# finance_utils.py
def format_to_usd(amount):
return f"${amount:,.2f}"
def calculate_vat(amount, rate=0.20):
return amount * rate
def clear_screen():
print("\n" * 50)
Bringing in the whole toolbox
The most straightforward way to use this is the basic import statement. I'll start my main script, report.py, like this:
import finance_utils
price = 1200.50
print(finance_utils.format_to_usd(price))
This is the safest approach. It creates a clear namespace. Whenever I see finance_utils.something(), I know exactly where that function came from. However, if I'm calling these functions twenty times in one file, typing finance_utils over and over gets tedious and clutters the line.
Plucking specific tools with from
Since I know I only really need the currency formatter for this specific report, I can use the from ... import ... variant. This brings the function directly into my local scope.
from finance_utils import format_to_usd
price = 1200.50
# Now I don't need the module prefix
print(format_to_usd(price))
This reads much more like natural English. But here is where I usually make my first mistake when I'm rushing. Watch what happens when I try to use another function from that same module without importing it explicitly.
from finance_utils import format_to_usd
price = 1200.50
print(format_to_usd(price))
print(calculate_vat(price)) # NameError: name 'calculate_vat' is not defined
I forgot that from finance_utils import format_to_usd doesn't import the module; it only imports that one specific object. I've basically told Python, "Just give me this one tool and ignore the rest of the shed." To fix this, I can either import both from finance_utils import format_to_usd, calculate_vat or just go back to import finance_utils.
The danger of the wildcard
You'll see some tutorials use from module import *. It looks tempting because it imports everything at once. Let's see why I avoid this in professional code.
from finance_utils import *
# Imagine I already had a function in this file called clear_screen
def clear_screen():
print("My custom local clear screen logic")
# Now, because of the wildcard import,
# the version in finance_utils.py has overwritten my local one!
clear_screen()
This is called "namespace pollution." When you use *, you're blindly dumping every function and variable from another file into your current one. If both files have a function with the same name, the last one imported wins, and you'll spend an hour debugging why your function is behaving strangely.
Shortening names with aliases
Finally, there's the as keyword. This is a lifesaver when you're dealing with modules that have long names or when you want to avoid conflicts. I use this constantly with libraries like Pandas (import pandas as pd) or NumPy. For our project, let's say I want the safety of the full module but without the typing fatigue.
import finance_utils as fu
import datetime as dt
price = 1200.50
today = dt.date.today()
print(f"Report Date: {today}")
print(f"Total: {fu.format_to_usd(price)}")
Now I have the best of both worlds: the code is concise, but the fu. prefix still tells me exactly where format_to_usd lives.
📋 Practical Task
Exercise: Refactoring the Geometry Calculator Imports
You have been given a file called geometry_helpers.py containing the following code:
# geometry_helpers.py
import math
def calculate_circle_area(radius):
return math.pi * (radius ** 2)
def calculate_rectangle_area(width, height):
return width * height
def get_pi_constant():
return math.pi
Your task is to create a new file called main.py that does the following:
- Imports the
geometry_helpersmodule using an alias calledgh. - Imports the
mathmodule using an alias calledm. - Uses the
ghalias to callcalculate_circle_areawith a radius of 5. - Uses the
malias to print the value ofm.sqrt(144). - Uses a
from ... import ...statement to bringcalculate_rectangle_areadirectly into the namespace and call it with a width of 10 and height of 20.
Ensure your output clearly labels each result.
There are no comments for now.