Juha-Matti Santala
Community Builder. Dreamer. Adventurer.

Here's my current startup script that Python runs everytime it starts a REPL session.

"""
PYTHONSTARTUP is an environment variable that can be defined
to point to a Python script. This script is then loaded
into every REPL session.

See: https://docs.python.org/3/using/cmdline.html#envvar-PYTHONSTARTUP

This file is my annotated startup script.

Written for Python 3.14.
"""

# When running ruff, don't complain about unused or un-sorted imports.
# ruff: noqa: F401
# ruff: noqa: I001

# It's good to have all the most commonly used modules imported.
import builtins
import csv
import hashlib
import json
import math
import os
import pprint
import random
import re
import shelve
import subprocess
import sys
import tempfile

# Normally, "import *" is not a great idea but for 
# the REPL sessions, it helps out so much.
from collections import *
from datetime import date, datetime, timedelta, timezone
from functools import *
from inspect import getmembers, ismethod, stack
from itertools import *
from math import *
from uuid import uuid4

# ~~~ Copy-paste helpers ~~~ 

# I don't expect needing typing or other definitions
# that often in the REPL session but they are handy to
# impoort so that copy-pasting code doesn't break.
import asyncio
from dataclasses import dataclass, field
from typing import *

# These redefinitions make copy-pasting valid JSON
# possible, turning it into a valid Python dict.
null = None
true = True
false = False

# ~~~ Quality of life stuff

# Many of these use a __truediv__ definition. It defines
# what happens when you try to divide the object with 
# something else (ie. p / 5)
# In this case, it's used to provide quick shorthands for
# various helper functions.

# readline enables tab completion in the shell
try:
    import readline

    readline.parse_and_bind("tab: complete")
    print('QOL: tab autocomplete loaded')
except ImportError:
    pass

# path literal helps us shortcutting to paths with
## p/"/etc/local" -> PosixPath('/etc/local')

from pathlib import Path

class PathLiteral:
    def __truediv__(self, other):
        try:
            return Path(other.format(**stack()[1][0].f_globals))
        except KeyError as e:
            raise NameError(f"name {e} is not defined")

    def __call__(self, string):
        return self / string

p = PathLiteral()

## I like to print my custom helper "commands" so I'm
## reminded of them when I start a shell
print('QOL: p/"path/to/file" -> Path("/path/to/file")')


class Printer(pprint.PrettyPrinter):
    def __call__(self, *args, **kwargs):
        super().pprint(*args, **kwargs)

    def __truediv__(self, other):
        super().pprint(other)

    def __rtruediv__(self, other):
        super().pprint(other)

    def __repr__(self):
        return repr(pprint)

try:
    pp = Printer(expand=True, indent=2)
except TypeError:
    pp = Printer(indent=2)
print('QOL: pp/obj == pprint(obj)')


# Date helpers

def now():
    return datetime.now(tz=timezone(timedelta(hours=3)))


def today():
    return now().date()



# ~~~ External libraries ~~~ 

# I have a set of external libraries that I like to have 
# easy access to if they are installed in the project
# or brought in with `uv run --with` command

# All of these need to be wrapped in try/except so
# the script doesn't break if they are not installed.

## requests for making HTTP calls
try:
    import requests
except ImportError:
    pass

# faker is a library to generate fake data,
# great for testing and prototyping

try:
    import faker
except ImportError:
    pass
else:
    from faker.providers import geo, internet

    def get_faker(locale="en"):
        fake = faker.Faker(locale)
        fake.add_provider(internet)
        fake.add_provider(geo)
        return fake

    class Fake:

        factory = get_faker()

        def __getattr__(self, name):
            faker_provider = self.factory.__getattr__(name)
            return lambda count=1: self.call_faker(faker_provider, count)

        def call_faker(self, faker_provider, count=1):

            if count == 1:
                return faker_provider()
            else:
                return [faker_provider() for _ in range(count)]

    fake = Fake()

    print('QOL: fake => faker')

# BeautifulSoup is my favourite xml/html parser and I do
# a lot of html parsing.

try:
    from bs4 import BeautifulSoup
except ImportError:
    pass

# If I'm in a Django shell, I want quick access to these helpers
try:
    from django.db.models import Avg, Count, F, Max, Min, Q, Sum, Value
except ImportError:
    pass