SyncAI.news, a Varaisys broadcasting
7 Advanced Python Tricks to Level Up Your Coding Skills
ND

Nahla Davies

· 1 min read

EngineeringKDnuggets

7 Advanced Python Tricks to Level Up Your Coding Skills

At some point every Python developer writes a while True loop with a break, or a teetering stack of nested with blocks, and feels vaguely certain there's a better way. There usually is. The standard library already solved these problems; it just solved them in corners most tutorials never visit. KDnuggets has covered advanced tricks for data scientists before, with pandas and NumPy doing the heavy lifting.

This list is different. Every item here is a built-in or standard-library contract, no dependencies, and each comes with the caveat that keeps it from being misused. Leveling up rarely means new syntax. It means learning what the language already promised you.

1. Turn a Callable into an Iterator with a Sentinel

iter() has a second form almost nobody uses. Hand it a zero-argument callable plus a sentinel value. Python then calls the function over and over, stopping the moment a return value equals the sentinel:

for chunk in iter(lambda: stream.read(64), b""):
    process(chunk)

That replaces the classic while True / break read loop entirely. Feed it a 200-byte stream and out come chunks of 64, 64, 64 and 8. Then it simply stops, because read() returned the empty-bytes sentinel. The same form handles anything pull-shaped, from database cursor batches to queue messages. The catch is the zero-argument part. iter() won't pass arguments for you, so anything that needs them gets wrapped in a lambda or a partial first.

2. Manage a Runtime-Sized Set of Resources with ExitStack

Nested with blocks work beautifully until the number of resources is decided at runtime. Opening a list of files chosen by the user doesn't fit a fixed syntax, and that's the gap ExitStack fills:

with ExitStack() as stack:
    files = [stack.enter_context(open(p)) for p in paths]
    merge(files)

3. Slice Binary Data Without Copying It

packet = bytearray(16)
header = memoryview(packet)[:4]
header[0] = 0xFF      # packet[0] is now 0xFF

Original source

This story was published by KDnuggets and written by Nahla Davies. SyncAI.news shows a preview; the complete article is on the publisher's site.

Read the full story on kdnuggets.com

Similar News