Python Snippets

A collection of useful code snippets for Python.

Basic API Route

Nextjs
nextjs
basic
next.js
basic-api-route.py
// app/api/hello/route.ts
import { NextResponse } from 'next/server'
 
export async function GET(request: Request) {
  return NextResponse.json({ message: 'Hello, World!' })
}

Decorator Example

Python
decorator
decorator-example.py
# A decorator is a function that takes another function and
# extends its behavior without explicitly modifying it.

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_whee():
    print("Whee!")

say_whee()

Flexible Functions (*args, **kwargs)

Python
flexible
flexible-functions-args-kwargs.py
# Use *args and **kwargs to accept a variable number of arguments.

def flexible_function(*args, **kwargs):
    print("Positional arguments (*args):", args)
    print("Keyword arguments (**kwargs):", kwargs)

# Example call
flexible_function(1, "hello", 3.14, name="CodeWebX", version=1.0)

# Output:
# Positional arguments (*args): (1, 'hello', 3.14)
# Keyword arguments (**kwargs): {'name': 'CodeWebX', 'version': 1.0}

Hello World

Python
hello
hello-world.py
# This is a basic Python snippet
print("Hello, Python World!")

List Comprehension

Python
list
list-comprehension.py
# Create a list of squares from 0 to 9
squares = [x**2 for x in range(10)]
print(squares)

# Create a list of even numbers
evens = [x for x in range(20) if x % 2 == 0]
print(evens)

Pythonic Looping (zip & enumerate)

Python
pythonic
pythonic-looping-zip-enumerate.py
# Use enumerate to get both index and value
letters = ['a', 'b', 'c']
for index, value in enumerate(letters):
    print(f"Index: {index}, Value: {value}")

# Use zip to iterate over multiple sequences at once
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(f"{name} is {age} years old.")
Page 1 of 2