from collections import deque, OrderedDict, ChainMap
example
from collections import deque, ChainMap
# deque: efficient append/pop from both ends
buffer = deque(maxlen=3)
for n in range(5):
buffer.append(n)
print(list(buffer))
# ChainMap: layered dict lookup
defaults = {"color": "blue", "size": 10}
overrides = {"color": "red"}
config = ChainMap(overrides, defaults)
print(config["color"], config["size"])
output
[2, 3, 4]
red 10
Note deque with maxlen auto-discards oldest items when full (ring buffer). ChainMap searches dicts in order, first match wins. Both are in collections.
dequeChainMapcollectionsring bufferlayered config
functools Module
syntax
from functools import lru_cache, partial, reduce
example
from functools import lru_cache, partial
@lru_cache(maxsize=128)
def fibonacci(n: int) -> int:
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(30))
print(fibonacci.cache_info())
# partial: pre-fill argumentsdef power(base, exp):
return base ** exp
square = partial(power, exp=2)
print(square(7))
Note lru_cache requires hashable arguments. For unhashable args, consider cachetools or a manual cache. partial is great for adapting callback signatures.
import re
re.search(pattern, string)
re.findall(pattern, string)
example
import re
text = "Contact: alice@mail.com or bob@work.org"
emails = re.findall(r"[\w.]+@[\w.]+\.\w+", text)
print(emails)
# Named groups
log = "2026-04-04 ERROR: Connection timeout"
match = re.match(r"(?P<date>[\d-]+) (?P<level>\w+): (?P<msg>.+)", log)
if match:
print(match.group("level"), match.group("msg"))
Note Always use raw strings (r'...') for regex patterns. For repeated use, compile with re.compile() for performance. Use re.VERBOSE for readable multi-line patterns.
Note Prefer pathlib.Path for path manipulation in new code. os.environ provides direct access to environment variables. Use os.getenv() for safe access with defaults.
os moduleenvironment variablefile pathos.pathworking directory