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 inrange(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)deffibonacci(n:int)->int:if n <2:return n
returnfibonacci(n -1)+fibonacci(n -2)print(fibonacci(30))print(fibonacci.cache_info())# partial: pre-fill argumentsdefpower(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: [email protected] or [email protected]"
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)ifmatch: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.