Python coding
π Python Tip #85: functools.reduce() Sometimes you have a list of values and want to repeatedly combine them into one final result. That's where reduce() comes in. It applies a function to the first two items, then uses the result with the next item, andβ¦
π Python Tip #86:
When you create decorators in Python, there's a small problem that can easily be overlooked: the decorator can replace the original function's name and documentation.
---
Importing
from functools import wraps
---
The Problem Without
def my_decorator(func):
def wrapper():
print("Before function")
func()
return wrapper
@my_decorator
def greet():
"""Say hello to the user."""
print("Hello!")
print(greet.name)
print(greet.doc)
Output:
wrapper
None
The original function's metadata has been replaced by the wrapper's metadata.
---
Using
from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper():
print("Before function")
func()
return wrapper
@my_decorator
def greet():
"""Say hello to the user."""
print("Hello!")
print(greet.name)
print(greet.doc)
Output:
greet
Say hello to the user.
Now Python knows that the wrapped function is still
---
Why Is This Useful?
Decorators are common in real Python projects.
They're used for things like:
β Logging
β Authentication
β Timing functions
β Caching
β Validation
β Permission checks
β Framework features
Using
---
A More Practical Example
from functools import wraps
import time
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
print(f"{func.name} took {end - start:.6f} seconds")
return result
return wrapper
@timer
def calculate():
return sum(range(100000))
print(calculate())
The decorator measures the function's execution time while
---
Quick Rule
When writing your own decorators, a good habit is:
@wraps(func)
Put it directly above the wrapper function.
---
Challenge:
Create a decorator called
1. Prints
2. Runs the original function.
3. Prints
4. Uses
Then decorate a function called
It should still print:
hello
functools.wraps()When you create decorators in Python, there's a small problem that can easily be overlooked: the decorator can replace the original function's name and documentation.
functools.wraps() fixes that by preserving important information about the original function.---
Importing
wrapsfrom functools import wraps
---
The Problem Without
wraps()def my_decorator(func):
def wrapper():
print("Before function")
func()
return wrapper
@my_decorator
def greet():
"""Say hello to the user."""
print("Hello!")
print(greet.name)
print(greet.doc)
Output:
wrapper
None
The original function's metadata has been replaced by the wrapper's metadata.
---
Using
wraps()from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper():
print("Before function")
func()
return wrapper
@my_decorator
def greet():
"""Say hello to the user."""
print("Hello!")
print(greet.name)
print(greet.doc)
Output:
greet
Say hello to the user.
Now Python knows that the wrapped function is still
greet.---
Why Is This Useful?
Decorators are common in real Python projects.
They're used for things like:
β Logging
β Authentication
β Timing functions
β Caching
β Validation
β Permission checks
β Framework features
Using
@wraps(func) makes your decorators behave more like the original functions.---
A More Practical Example
from functools import wraps
import time
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
print(f"{func.name} took {end - start:.6f} seconds")
return result
return wrapper
@timer
def calculate():
return sum(range(100000))
print(calculate())
The decorator measures the function's execution time while
@wraps() preserves the original function's metadata.---
Quick Rule
When writing your own decorators, a good habit is:
@wraps(func)
Put it directly above the wrapper function.
---
Challenge:
Create a decorator called
logger that:1. Prints
"Function started" before running a function.2. Runs the original function.
3. Prints
"Function finished" afterward.4. Uses
@wraps(func).Then decorate a function called
hello() and check its __name__.It should still print:
hello
Python coding
π Python Tip #86: functools.wraps() When you create decorators in Python, there's a small problem that can easily be overlooked: the decorator can replace the original function's name and documentation. functools.wraps() fixes that by preserving importantβ¦
π Python Tip #87:
Ever needed to work with multiple dictionaries as if they were one?
---
Importing
from collections import ChainMap
---
Basic Example
from collections import ChainMap
defaults = {
"theme": "light",
"language": "English"
}
user_settings = {
"theme": "dark"
}
settings = ChainMap(user_settings, defaults)
print(settings["theme"])
print(settings["language"])
Output:
dark
English
Python checks the dictionaries from left to right.
So if a key exists in
---
Why Is This Useful?
Imagine an application has:
1. User settings
2. Project settings
3. Default settings
Instead of copying everything into one dictionary, you can use:
settings = ChainMap(
user_settings,
project_settings,
defaults
)
If the user has a custom value, it takes priority.
If not, Python checks the next dictionary.
---
Adding a New Dictionary
You can add another mapping with
from collections import ChainMap
defaults = {"color": "blue"}
user = {"name": "Ali"}
settings = ChainMap(user, defaults)
temporary = settings.new_child(
{"color": "red"}
)
print(temporary["color"])
Output:
red
The new dictionary gets the highest priority.
---
Updating Values
If you change a value:
settings["name"] = "Sara"
the change is made in the first dictionary in the chain.
It keeps references to the original mappings.
---
Real-World Example
from collections import ChainMap
system_config = {
"debug": False,
"language": "English"
}
app_config = {
"debug": True
}
config = ChainMap(app_config, system_config)
print(config["debug"])
print(config["language"])
Output:
True
English
This pattern can be useful for configuration systems where different levels of settings override each other.
---
Why use
β Combines multiple dictionaries without copying them
β Useful for configuration systems
β Supports priority-based lookups
β Keeps the original dictionaries separate
β Useful when working with layered settings
---
Challenge:
Create three dictionaries:
defaults = {"theme": "light", "font": "Arial"}
user = {"theme": "dark"}
temporary = {"font": "Courier"}
Use
1.
2.
3.
Then print the values of:
theme
font
Expected output:
dark
Courier
collections.ChainMapEver needed to work with multiple dictionaries as if they were one?
ChainMap from the collections module lets you combine multiple dictionaries into a single view without actually merging or copying them.---
Importing
ChainMapfrom collections import ChainMap
---
Basic Example
from collections import ChainMap
defaults = {
"theme": "light",
"language": "English"
}
user_settings = {
"theme": "dark"
}
settings = ChainMap(user_settings, defaults)
print(settings["theme"])
print(settings["language"])
Output:
dark
English
Python checks the dictionaries from left to right.
So if a key exists in
user_settings, that value is used first.---
Why Is This Useful?
Imagine an application has:
1. User settings
2. Project settings
3. Default settings
Instead of copying everything into one dictionary, you can use:
settings = ChainMap(
user_settings,
project_settings,
defaults
)
If the user has a custom value, it takes priority.
If not, Python checks the next dictionary.
---
Adding a New Dictionary
You can add another mapping with
new_child():from collections import ChainMap
defaults = {"color": "blue"}
user = {"name": "Ali"}
settings = ChainMap(user, defaults)
temporary = settings.new_child(
{"color": "red"}
)
print(temporary["color"])
Output:
red
The new dictionary gets the highest priority.
---
Updating Values
If you change a value:
settings["name"] = "Sara"
the change is made in the first dictionary in the chain.
ChainMap doesn't merge everything into one new dictionary.It keeps references to the original mappings.
---
Real-World Example
from collections import ChainMap
system_config = {
"debug": False,
"language": "English"
}
app_config = {
"debug": True
}
config = ChainMap(app_config, system_config)
print(config["debug"])
print(config["language"])
Output:
True
English
This pattern can be useful for configuration systems where different levels of settings override each other.
---
Why use
ChainMap?β Combines multiple dictionaries without copying them
β Useful for configuration systems
β Supports priority-based lookups
β Keeps the original dictionaries separate
β Useful when working with layered settings
---
Challenge:
Create three dictionaries:
defaults = {"theme": "light", "font": "Arial"}
user = {"theme": "dark"}
temporary = {"font": "Courier"}
Use
ChainMap so that:1.
temporary has the highest priority.2.
user comes next.3.
defaults is the fallback.Then print the values of:
theme
font
Expected output:
dark
Courier
Python coding
π Python Tip #87: collections.ChainMap Ever needed to work with multiple dictionaries as if they were one? ChainMap from the collections module lets you combine multiple dictionaries into a single view without actually merging or copying them. --- Importingβ¦
π Python Tip #88:
Ever needed a variable whose value is local to the current task or execution context?
Python's
---
Importing
import contextvars
---
Creating a Context Variable
import contextvars
user = contextvars.ContextVar("user")
user.set("Yehya")
print(user.get())
Output:
Yehya
---
Using a Default Value
import contextvars
language = contextvars.ContextVar(
"language",
default="English"
)
print(language.get())
Output:
English
If you haven't assigned a value yet, the default is returned.
---
Changing the Value
import contextvars
username = contextvars.ContextVar(
"username",
default="Guest"
)
print(username.get())
username.set("Yehya")
print(username.get())
Output:
Guest
Yehya
---
Using
import contextvars
current_user = contextvars.ContextVar(
"current_user",
default="Guest"
)
def show_user():
print("Current user:", current_user.get())
current_user.set("Ali")
show_user()
current_user.set("Sara")
show_user()
Output:
Current user: Ali
Current user: Sara
---
Why Is This Useful?
β Async applications
β Web servers
β Request-specific data
β Logging context
β User/session information
β Code where multiple tasks need separate values
For example, a web application might store a request ID in a
---
Important Difference
A normal global variable is shared:
current_user = "Ali"
A
This becomes especially useful with
---
Challenge:
Create a
current_user
Give it a default value of:
"Guest"
Then:
1. Print the default value.
2. Change it to
3. Create a function that prints the current user.
4. Call the function.
Expected output:
Guest
Yehya
contextvarsEver needed a variable whose value is local to the current task or execution context?
Python's
contextvars module is especially useful in asynchronous applications where multiple tasks can be running at the same time.---
Importing
contextvarsimport contextvars
---
Creating a Context Variable
import contextvars
user = contextvars.ContextVar("user")
user.set("Yehya")
print(user.get())
Output:
Yehya
ContextVar stores a value that belongs to the current execution context.---
Using a Default Value
import contextvars
language = contextvars.ContextVar(
"language",
default="English"
)
print(language.get())
Output:
English
If you haven't assigned a value yet, the default is returned.
---
Changing the Value
import contextvars
username = contextvars.ContextVar(
"username",
default="Guest"
)
print(username.get())
username.set("Yehya")
print(username.get())
Output:
Guest
Yehya
---
Using
ContextVar in Functionsimport contextvars
current_user = contextvars.ContextVar(
"current_user",
default="Guest"
)
def show_user():
print("Current user:", current_user.get())
current_user.set("Ali")
show_user()
current_user.set("Sara")
show_user()
Output:
Current user: Ali
Current user: Sara
---
Why Is This Useful?
ContextVar is commonly useful in:β Async applications
β Web servers
β Request-specific data
β Logging context
β User/session information
β Code where multiple tasks need separate values
For example, a web application might store a request ID in a
ContextVar so different parts of the application can access it without passing the ID through every function.---
Important Difference
A normal global variable is shared:
current_user = "Ali"
A
ContextVar is designed so different execution contexts can have different values.This becomes especially useful with
asyncio and other concurrent code.---
Challenge:
Create a
ContextVar called:current_user
Give it a default value of:
"Guest"
Then:
1. Print the default value.
2. Change it to
"Yehya".3. Create a function that prints the current user.
4. Call the function.
Expected output:
Guest
Yehya
Python coding
π Python Tip #88: contextvars Ever needed a variable whose value is local to the current task or execution context? Python's contextvars module is especially useful in asynchronous applications where multiple tasks can be running at the same time. --- β¦
π Python Tip #89:
Sometimes you have a few related values and want to access them with dot notation instead of dictionary brackets.
---
Importing
from types import SimpleNamespace
---
Basic Example
from types import SimpleNamespace
user = SimpleNamespace(
name="Yehya",
age=16,
language="Python"
)
print(user.name)
print(user.age)
print(user.language)
Output:
Yehya
16
Python
Instead of:
user["name"]
you can use:
user.name
---
Changing Values
The attributes can be changed normally:
user.age = 17
print(user.age)
Output:
17
You can also add new attributes:
user.country = "Ethiopia"
print(user.country)
Output:
Ethiopia
---
Creating One From a Dictionary
You can also convert dictionary data into a namespace:
from types import SimpleNamespace
data = {
"name": "Sara",
"score": 95
}
student = SimpleNamespace(**data)
print(student.name)
print(student.score)
Output:
Sara
95
---
Converting Back to a Dictionary
Use
data = vars(student)
print(data)
Output:
{'name': 'Sara', 'score': 95}
---
When Is It Useful?
β Small data containers
β Configuration objects
β Temporary structured data
β Making dictionary data easier to access
β Quick prototypes
It's not a replacement for
---
Real Example
from types import SimpleNamespace
server = SimpleNamespace(
host="localhost",
port=8000,
debug=True
)
print(f"Server: {server.host}:{server.port}")
print("Debug:", server.debug)
Output:
Server: localhost:8000
Debug: True
---
Challenge:
Create a
name = "Yehya"
grade = 11
subject = "Python"
Then:
1. Print the student's name.
2. Change the grade to 12.
3. Add a new attribute called
4. Print all the information.
Can you do it without using a dictionary?
types.SimpleNamespaceSometimes you have a few related values and want to access them with dot notation instead of dictionary brackets.
SimpleNamespace from Python's types module gives you a simple object for storing attributes.---
Importing
SimpleNamespacefrom types import SimpleNamespace
---
Basic Example
from types import SimpleNamespace
user = SimpleNamespace(
name="Yehya",
age=16,
language="Python"
)
print(user.name)
print(user.age)
print(user.language)
Output:
Yehya
16
Python
Instead of:
user["name"]
you can use:
user.name
---
Changing Values
The attributes can be changed normally:
user.age = 17
print(user.age)
Output:
17
You can also add new attributes:
user.country = "Ethiopia"
print(user.country)
Output:
Ethiopia
---
Creating One From a Dictionary
You can also convert dictionary data into a namespace:
from types import SimpleNamespace
data = {
"name": "Sara",
"score": 95
}
student = SimpleNamespace(**data)
print(student.name)
print(student.score)
Output:
Sara
95
---
Converting Back to a Dictionary
Use
vars():data = vars(student)
print(data)
Output:
{'name': 'Sara', 'score': 95}
---
When Is It Useful?
SimpleNamespace can be handy for:β Small data containers
β Configuration objects
β Temporary structured data
β Making dictionary data easier to access
β Quick prototypes
It's not a replacement for
dataclass when you need a more structured data model.---
Real Example
from types import SimpleNamespace
server = SimpleNamespace(
host="localhost",
port=8000,
debug=True
)
print(f"Server: {server.host}:{server.port}")
print("Debug:", server.debug)
Output:
Server: localhost:8000
Debug: True
---
Challenge:
Create a
SimpleNamespace called student with:name = "Yehya"
grade = 11
subject = "Python"
Then:
1. Print the student's name.
2. Change the grade to 12.
3. Add a new attribute called
score.4. Print all the information.
Can you do it without using a dictionary?
Python coding
π Python Tip #89: types.SimpleNamespace Sometimes you have a few related values and want to access them with dot notation instead of dictionary brackets. SimpleNamespace from Python's types module gives you a simple object for storing attributes. --- Importingβ¦
π Python Tip #90:
If a function keeps receiving the same arguments and doing the same expensive calculation again and again, caching can save a lot of work.
Python's
---
Importing
from functools import cache
---
Basic Example
from functools import cache
@cache
def square(number):
print("Calculating...")
return number ** 2
print(square(5))
print(square(5))
print(square(10))
Output:
Calculating...
25
25
Calculating...
100
Notice that
The second
---
A More Useful Example
from functools import cache
@cache
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(10))
Output:
55
Without caching, recursive Fibonacci calculations repeat many of the same calculations.
With
---
Checking the Cache
You can inspect the cache with:
fibonacci.cache_info()
For example, you might see:
CacheInfo(hits=8, misses=11, maxsize=None, currsize=11)
---
Clearing the Cache
If you want to remove all stored results:
fibonacci.cache_clear()
After that, the function will calculate the results again when called.
---
Important Note
That means stored results can continue growing as new arguments are used.
If you need a limited cache size,
---
Why use
β Avoids repeating expensive calculations
β Extremely useful with recursive functions
β Simple to add with
β Can make repeated function calls much faster
β Part of Python's standard library
---
Challenge:
Create a cached function:
@cache
def factorial(n):
It should calculate:
5! = 120
Then call:
factorial(5)
factorial(5)
factorial(6)
Finally, use:
factorial.cache_info()
and check how many cache hits you get.
functools.cache()If a function keeps receiving the same arguments and doing the same expensive calculation again and again, caching can save a lot of work.
Python's
functools.cache() automatically remembers previous results and reuses them when the same arguments appear again.---
Importing
cachefrom functools import cache
---
Basic Example
from functools import cache
@cache
def square(number):
print("Calculating...")
return number ** 2
print(square(5))
print(square(5))
print(square(10))
Output:
Calculating...
25
25
Calculating...
100
Notice that
"Calculating..." only appears once for 5.The second
square(5) gets the stored result instead of running the function again.---
A More Useful Example
from functools import cache
@cache
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(10))
Output:
55
Without caching, recursive Fibonacci calculations repeat many of the same calculations.
With
@cache, previously calculated results are reused.---
Checking the Cache
You can inspect the cache with:
fibonacci.cache_info()
For example, you might see:
CacheInfo(hits=8, misses=11, maxsize=None, currsize=11)
hits = results retrieved from the cache.misses = calculations that had to actually run.currsize = number of stored results.---
Clearing the Cache
If you want to remove all stored results:
fibonacci.cache_clear()
After that, the function will calculate the results again when called.
---
Important Note
@cache is basically an unlimited cache.That means stored results can continue growing as new arguments are used.
If you need a limited cache size,
functools.lru_cache() is usually more appropriate.---
Why use
cache()?β Avoids repeating expensive calculations
β Extremely useful with recursive functions
β Simple to add with
@cacheβ Can make repeated function calls much faster
β Part of Python's standard library
---
Challenge:
Create a cached function:
@cache
def factorial(n):
It should calculate:
5! = 120
Then call:
factorial(5)
factorial(5)
factorial(6)
Finally, use:
factorial.cache_info()
and check how many cache hits you get.