Python examples / cookbook

Practical, runnable Python snippets: list & dict comprehensions, decorators, dataclasses, f-strings, regex and more. Click any example to open it in the interactive Python playground and run it in your browser.

from dataclasses import dataclass, field

# Simple dataclass
@dataclass
class Point:
  x: int
  y: int

p = Point(1, 2)
print(p)  # Outputs: Point(x=1, y=2)

# Dataclass with default values
@dataclass
class Rectangle:
  width: int = 0
  height: int = 0

r = Rectangle()
print(r)  # Outputs: Rectangle(width=0, height=0)

# Dataclass with methods
@dataclass
class Circle:
  radius: float

  def area(self) -> float:
      return 3.14 * (self.radius ** 2)

c = Circle(5.0)
print(c.area())  # Outputs: 78.5


# Dataclass with default list field
@dataclass
class MyClass:
    my_list: list[int] = field(default_factory=list)

obj1 = MyClass()
obj1.my_list.append(1)
print(obj1)

Python dataclasses example

Open in Python playground
import urllib.parse
import json

def build_diagram():
  result = ["digraph {"]
  for i in range(10):
    result.append(f"  n{i} -> n{i+1}")
  result += "}"
  return "\n".join(result)

diagram = build_diagram()
print(diagram)

params = {"dot" : diagram}
query = urllib.parse.quote(json.dumps(params))

domain = "https://devtoolsdaily.com"

f"{domain}/graphviz/?#{query}"

Example constructing graphviz markup using python

Open in Python playground
example = {
    "intField": 1,
    "strField": "hello",
    "boolField": False
}

print("default python representation")
print(example)

import json

# to json
example_json = json.dumps(example, indent=2)
print("json:")
print(example_json)

# load json
parsed_obj = json.loads(example_json)
assert parsed_obj['intField'] == example['intField']

example_json

Example converting to and from JSON string using python

Open in Python playground
import re

def is_valid_email(email):
  """Returns True if the given email address is valid, False otherwise"""
  pattern = r'^[a-zA-Z0-9._%+-]+@([a-zA-Z0-9.-]+.[a-zA-Z]{2,})$'
  return bool(re.match(pattern, email))

# Example usage:
print("is example@email.com valid - ", is_valid_email("example@email.com")) # True
print("is invalid.email@com valid - ", is_valid_email("invalid.email@com")) # False

# example using match groups
def extract_email_domain(email):
  pattern = r'^[a-zA-Z0-9._%+-]+@([a-zA-Z0-9.-]+.[a-zA-Z]{2,})$'
  match = re.match(pattern, email)
  if match:
    return match.group(1)
  return None

print("email domain for example@email.com is - ", extract_email_domain("example@email.com")) # True
print("email domain for invalid.email@com is - ", extract_email_domain("invalid.email@com")) # False

# example using named match groups
def parse_date(date_string):
  """Parses a date string in the format 'DD/MM/YYYY' and returns a dictionary with the day, month, and year"""
  pattern = r'(?P<day>d{2})/(?P<month>d{2})/(?P<year>d{4})'
  match = re.match(pattern, date_string)
  if match:
    return match.groupdict()
  else:
    return None

date_string = '18/03/2023'
date_dict = parse_date(date_string)
print(date_dict)

Python regular expressions example

Open in Python playground
print("example squared numbers")
numbers = [1, 2, 3, 4, 5]
squared_numbers = [x**2 for x in numbers]
print(squared_numbers)

print("example odd numbers")
numbers = [1, 2, 3, 4, 5]
odd_numbers = [x for x in numbers if x % 2 != 0]
print(odd_numbers)

print("example produce list of tuples")
numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
combined_list = [(x, y) for x in numbers for y in letters]
print(combined_list)

print("example convert strings to uppercase")
words = ['hello', 'world', 'python']
upper_words = [x.upper() for x in words]
print(upper_words)

print("example construct a list from range")
numbers = [x for x in range(10)]
print(numbers)

Python list comprehensions example

Open in Python playground
# primitives
def func(a: int, b: float) -> str:
  a: str = f"{a}, {b}"
  return a
 
# complex types and collections
from typing import List

class Person:
  name: str
  age: int

def get_names(people: List[Person]) -> List[str]:
  return [person.name for person in people]
 
# map/dict
from typing import Dict

def get_counts(words: List[str]) -> Dict[str, int]:
  counts = {}
  for word in words:
    if word in counts:
      counts[word] += 1
    else:
      counts[word] = 1
  return counts

Python type hints example

Open in Python playground
import functools

def my_decorator(func):
  @functools.wraps(func)
  def wrapper(*args, **kwargs):
    print(f"Calling function {func.__name__} with args {args} and kwargs {kwargs}")
    return func(*args, **kwargs)
  return wrapper

@my_decorator
def my_function(a, b):
  pass

my_function(1, b=2)

Python decorators example

Open in Python playground
import random

# Example 1
customers = ['John', 'Sara', 'Tim', 'Mia']
discounts = {customer: random.randint(1, 100) for customer in customers}
print(discounts)

# Example 2
temperatures = {'Monday': 20, 'Tuesday': 22, 'Wednesday': 25, 'Thursday': 23, 'Friday': 19, 'Saturday': 18, 'Sunday': 21}
fahrenheit_temperatures = {day: (temp * 9/5) + 32 for (day, temp) in temperatures.items()}
print(fahrenheit_temperatures)

Python dict comprehensions example

Open in Python playground
class Animal:
  def __init__(self, name, species):
    self.name = name
    self.species = species

class Dog(Animal):
  def __init__(self, name):
    super().__init__(name, "Dog")

charlie = Dog("charlie")
charlie.__dict__

Python inheritance example

Open in Python playground
from datetime import datetime

date_str = "2022-01-01 12:00:00"
date_obj = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
print(f"Formatted date: {date_obj.strftime('%B %d, %Y at %I:%M %p')}")

Python datetime format example

Open in Python playground
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

Python f-strings example

Open in Python playground