Skip to content
Snippets·Free

Python snippets

20 Python snippets for scripts and tests: an argparse entry point, dataclasses, pathlib and JSON files, logging setup, decorators, context managers, asyncio.gather and pytest fixtures. Type a prefix such as argmain or dcls in a .py file.

Free to install.

If PocketCode is installed on your Android device, this opens the page in the app.

Preview

5 of 20

Script with argparseargmain

Command-line script with a positional argument and a --verbose flag

import argparse


def main() -> None:
    parser = argparse.ArgumentParser(description="${1:What the script does}")
    parser.add_argument("${2:path}", help="${3:Input file}")
    parser.add_argument("-v", "--verbose", action="store_true")
    args = parser.parse_args()
    $0


if __name__ == "__main__":
    main()

Dataclassdcls

Dataclass with a typed field and a list default

from dataclasses import dataclass, field


@dataclass
class ${1:Item}:
    ${2:name}: ${3:str}
    ${4:tags}: list[str] = field(default_factory=list)

Enumenumc

Enum with string values

from enum import Enum


class ${1:Color}(Enum):
    ${2:RED} = "${3:red}"
    ${4:GREEN} = "${5:green}"

Read a text file with pathlibreadp

Read a whole file as UTF-8 text

from pathlib import Path

${1:text} = Path("${2:data.txt}").read_text(encoding="utf-8")

Load JSON from a filejload

Parse a JSON file into Python objects

import json

with open("${1:data.json}", encoding="utf-8") as f:
    ${2:data} = json.load(f)

Changes in 1.0.0

First version.

Related