惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 叶小钗
雷峰网
雷峰网
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Martin Fowler
Martin Fowler
MyScale Blog
MyScale Blog
博客园 - 聂微东
有赞技术团队
有赞技术团队
The Cloudflare Blog
T
Tailwind CSS Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
月光博客
月光博客
T
The Blog of Author Tim Ferriss
D
Docker
L
LangChain Blog
Vercel News
Vercel News
C
Check Point Blog
博客园 - Franky
博客园 - 三生石上(FineUI控件)
Recent Announcements
Recent Announcements
H
Hackread – Cybersecurity News, Data Breaches, AI and More
量子位
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
V2EX
人人都是产品经理
人人都是产品经理

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
🐍 Python Power Moves: 5 Tricks to Level Up Your Code Today
leechon · 2026-06-16 · via DEV Community

leechon

Python is famous for its readability, but there’s a big gap between “working code” and “elegant, efficient code.” Whether you're a beginner or a seasoned developer, these five practical tricks will help you write cleaner, faster, and more Pythonic code.


🚀 1. Leverage List Comprehensions for Speed and Clarity

The Problem: You often write loops to create lists, which is verbose and slower.

The Trick: Use list comprehensions – they’re more concise and run faster because they avoid append overhead.

# BAD
squares = []
for i in range(10):
    squares.append(i**2)

# GOOD
squares = [i**2 for i in range(10)]

Pro Tip: You can add conditionals:

even_squares = [i**2 for i in range(20) if i % 2 == 0]

Benchmark: List comprehensions are roughly 2x faster than equivalent for-loops in CPython.


🧰 2. Use enumerate and zip Like a Pro

The Problem: You need to loop over a list with index, or combine multiple lists.

The Trick: enumerate gives you (index, value) tuples; zip pairs iterables easily.

# Instead of:
for i in range(len(items)):
    print(i, items[i])

# Do:
for i, item in enumerate(items):
    print(i, item)

# Combining lists:
names = ['Alice', 'Bob', 'Charlie']
scores = [95, 87, 92]
for name, score in zip(names, scores):
    print(f"{name}: {score}")

Bonus: enumerate accepts a start parameter. Great for numbering output starting from 1.


⚡ 3. Master Context Managers with with

The Problem: You manually open and close files, or handle resources, risking leaks.

The Trick: Use with statements that automatically call __enter__ and __exit__.

# Without context manager
file = open('data.txt', 'r')
data = file.read()
file.close()  # Don't forget!

# With context manager
with open('data.txt', 'r') as file:
    data = file.read()
# Automatically closed even if exception occurs

Custom Context Manager: Use contextlib.contextmanager for simple cases:

from contextlib import contextmanager

@contextmanager
def tag(name):
    print(f"<{name}>")
    yield
    print(f"</{name}>")

with tag('h1'):
    print('Hello, World!')
# Output: <h1> Hello, World! </h1>


🎯 4. Write Readable Code with Structural Pattern Matching (Python 3.10+)

The Problem: Long if-elif chains are hard to maintain and read.

The Trick: Use match-case for pattern matching, inspired by functional languages.

def handle_command(command):
    match command.split():
        case ['quit']:
            print('Goodbye!')
            sys.exit(0)
        case ['hello', name]:
            print(f'Hello, {name}!')
        case _:
            print('Unknown command')

Advanced: Match on data structures:

def process_point(point):
    match point:
        case (0, 0):
            print('Origin')
        case (x, 0):
            print(f'On X-axis at {x}')
        case (0, y):
            print(f'On Y-axis at {y}')
        case (x, y):
            print(f'At ({x}, {y})')

This replaces tedious if isinstance() checks.


🔮 5. Use __slots__ to Save Memory in Classes

The Problem: Python classes store attributes in an underlying dictionary (dict) consuming extra memory.

The Trick: Define __slots__ to tell Python exactly which attributes the class has. This eliminates dict, reducing memory usage by 40-60% per instance.

# Without slots
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

# With slots
class Point:
    __slots__ = ('x', 'y')
    def __init__(self, x, y):
        self.x = x
        self.y = y

Caveats:

  • You cannot add new attributes not listed in __slots__.
  • Inheritance requires care (child must define its own __slots__ or a dict is added).

Benchmark: For a class with 2 attributes, memory per instance drops from ~56 bytes to ~32 bytes.


📦 Putting It All Together

Here’s a real example combining several tricks:

from sys import getsizeof

class DataPoint:
    __slots__ = ('x', 'y', 'value')
    def __init__(self, x, y, value):
        self.x = x
        self.y = y
        self.value = value

# Load data from file
with open('data.csv') as f:
    lines = f.readlines()[1:]  # skip header

# Parse with list comprehension and structural pattern matching
points = []
for line in lines:
    match line.strip().split(','):
        case [x, y, v]:
            points.append(DataPoint(int(x), int(y), float(v)))
        case _:
            print(f'Skipping bad line: {line}')

print(f'Total points: {len(points)}')
print(f'Size of one point: {getsizeof(points[0])} bytes')


✅ Conclusion

These five tricks can dramatically improve your Python code:

  1. List comprehensions for speed and clarity.
  2. enumerate and zip for clean loops.
  3. Context managers for safe resource handling.
  4. Structural pattern matching for readable conditionals.
  5. __slots__ for memory efficiency.

Your Turn: Pick one trick you haven't used before and refactor an existing script. You'll be amazed at the difference!

If you found this helpful, follow me for more Python tips and tutorials. Drop a comment with your favorite Python trick – I’d love to learn from you too! 🐍✨


🔧 Want free AI tools? Check out AI Toolbox — text improver, translator, code generator, and more. No signup needed.