Dragon

The Standard Library: Overview

A language is only as useful as the day-one things you can do without writing them yourself: read a file, parse some JSON, hash a password, open a socket, sort a list, format a date. Dragon's standard library is where those things live. This chapter is the map - what the library is, how it's shaped, and which chapter to turn to for each module. The chapters that follow are the territory.

What "standard library" means in Dragon

Three properties distinguish Dragon's stdlib from the libraries you may be used to.

It ships with the compiler, statically linked. There is no pip install, no npm, no lockfile, no runtime dependency to ship next to your binary. You write import json and the code is already on disk, compiled into your executable alongside your own. The bundled native libraries a few modules lean on - PCRE2 for re, SQLite for the database layer, mbedTLS for TLS and hashing, zlib and zstd for compression - are linked the same way. Nothing is fetched at build time.

It's written mostly in Dragon itself. The library is dogfooded: the rule across the project is that anything expressible in Dragon is written in Dragon, and C++ is reserved for what genuinely can't be - raw syscalls, codegen primitives, refcount intrinsics, runtime data structures. So the great majority of stdlib modules (textwrap, csv, json, datetime, urllib.parse, the entire http server, the Postgres and MySQL drivers, and many more) are ordinary .dr source you can read, and they compile to native code at exactly the speed your own code does.

It matches Python's names where it can - but it is not Python. Dragon is inspired by Python, not a superset of it: the CPython C API and the dynamic ecosystem (numpy, pandas, Flask) do not work and never will. Within the subset Dragon does implement, the goal is that import names, function signatures, and semantics read identically to CPython - so your muscle memory transfers - except where matching Python would cost speed or force a workaround. Speed wins those ties. The result is a deliberate subset: not the whole CPython stdlib, and within each module not every function or flag.

Because Dragon is statically typed and compiled ahead of time, a handful of modules wear that subset on their sleeve. The compiler can't dispatch on a value's runtime type the way CPython does, so APIs that are one generic function in Python sometimes appear as a small family of typed functions in Dragon. You'll meet these as you go - the most prominent are:

  • json's generic loads returns Any (a boxed value you narrow with isinstance), not a dict/list; the typed decoders and encoders are monomorphized (loads_int, dumps_list_str, …) for the hot path. It also ships a JSON Schema validator (the Schema class: register named schemas, validate by name, compose with $ref) with no CPython-stdlib counterpart.
  • re.match/re.search return an int index (or -1), not a Match object; captures come from a Pattern API.
  • csv exposes parse_row/format_row with an explicit delimiter, not Python's reader/writer objects.
  • tomllib.loads returns a typed TomlDoc with dotted-key accessors, not a plain dict.

These divergences are documented module-by-module in the chapters that follow, and each chapter leads with what the code actually exposes - never with what Python would do.

Importing a module

Imports work the way they do in Python. Bring in the whole module and qualify each call:

import math

print(math.pi)   # 3.141592653589793

Or pull specific names into your namespace with from:

from textwrap import shorten

s: str = shorten("Dragon ships its standard library with the compiler", width=24)
print(s)   # Dragon ships its [...]

Packages use dotted paths. A submodule is imported by its full dotted name, and from … import … reaches into it:

from os.path import join
from urllib.parse import urlencode

print(join("/etc", "hosts"))   # /etc/hosts

That's the whole import story - import X, from X import f, and dotted names for submodules. There is no import *, and no install step stands between the line you write and the code it names.

The module index

The rest of Part 14 walks the library by category. Each row below links to the chapter that covers the module in depth. (For a single alphabetical list of everything, see the Standard Library Index appendix.)

Files and the filesystem

How a program reads, writes, and reasons about files, paths, and the process around it.

ModulePurposeChapter
ioRead and write files - a File class with with-block supportFiles
osThe OS interface: directory listings, environment, processesFiles
os.pathPure path-string surgery: join, basename, splitext, existence checksFiles
pathlibObject-oriented paths - a Path class with / joiningFiles
globUnix-style pathname expansion to a list of matchesFiles
shutilHigh-level file ops: copyfile, copytree, …Files
tempfileTemporary files and directoriesFiles
statInterpret os.stat mode bits (S_ISDIR, …)Files
sysProcess exit, the command line via argv(), system limitsFiles

Text

Tools for building, wrapping, matching, and pulling apart strings.

ModulePurposeChapter
stringString constants (ascii_lowercase, digits, …) and helpersText
textwrapWrap, fill, dedent, indent, and shorten textText
reRegular expressions, backed by bundled PCRE2Text
fnmatchGlob-style filename matching (*, ?, [abc])Text
shlexShell-like lexical splitting with POSIX quotingText
difflibSequence similarity - common blocks and ratiosText
htmlHTML escape/unescape, tag stripping, entity codecsText

Data formats

Reading and writing structured data: JSON, CSV, INI, TOML, and binary.

ModulePurposeChapter
jsonJSON encode/decode/validate (loadsAny; typed dumps_*; the Schema registry)Data Formats
csvCSV parse_row/format_row with explicit delimiterData Formats
configparserINI files - sections, key-values, commentsData Formats
tomllibRead-only TOML, returning a typed TomlDocData Formats
base64RFC 4648 Base64, plus URL-safe variantsData Formats
binasciihexlify/unhexlify and CRC32 over bytesData Formats
structPack/unpack primitives to/from bytesData Formats
gzipgzip compress/decompressData Formats
zipfilePKWARE ZIP archive read/writeData Formats
tarfilePOSIX USTAR tar, composing with gzip/zstdData Formats
zstandardZstandard compress/decompress (beyond Python)Data Formats

Dates, times, and math

Clocks, calendars, numeric functions, and number theory.

ModulePurposeChapter
timeCurrent time, monotonic clocks, sleepDates & Math
datetimetimedelta/date/time/datetime (UTC-only)Dates & Math
calendarPure date math and formattingDates & Math
mathlibm functions and constants (pi, e, tau)Dates & Math
statisticsMean, median, variance, … over listsDates & Math
fractionsExact rational arithmetic via FractionDates & Math
randomPseudo-random floats, ints, sequence ops (not secure)Dates & Math

Functional tools and collections

Iterator building blocks, higher-order helpers, and ordered/priority structures.

ModulePurposeChapter
itertoolsaccumulate, chain, islice, pairwise, …Functional Tools
functoolsreduce and friends (monomorphic subset)Functional Tools
operatorPython operators as plain functionsFunctional Tools
bisectBinary search over a sorted list[int]Functional Tools
heapqMin-heap / priority-queue ops on list[int]Functional Tools
enumEnum/IntEnum/StrEnum base classesFunctional Tools

Crypto and hashing

Digests, MACs, secure randomness, password hashing, and TLS.

ModulePurposeChapter
hashlibSHA-256/SHA-1/MD5 with update/copy, plus pbkdf2_hmacCrypto
hmacRFC 2104 keyed-hash MAC (mbedTLS)Crypto
cryptoSuperset surface: asymmetric sign/verify and AEAD ciphersCrypto
secretsOS-CSPRNG randomness - token_urlsafe, compare_digestCrypto
argon2idArgon2id password hashing (beyond Python's stdlib)Crypto
totpRFC 6238/4226 TOTP/HOTP (beyond Python's stdlib)Crypto
sslTLS over statically-linked mbedTLS (modern-only policy)Crypto
uuidUUID v4 generation and string utilities (not secure)Crypto

Networking

Sockets, addresses, and the HTTP and URL stacks.

ModulePurposeChapter
socketTCP/UDP BSD-socket wrappersNetworking
ipaddressIPv4/IPv6 parse, equality, CIDR membershipNetworking
http.serverPure-Dragon HTTP server (Router, Request, Response)Networking
http.clientHTTP/1.1 client over socket.TcpStreamNetworking
http.cookiesParse and render cookie headersNetworking
urllib.parseURL parsing and percent-encoding (urlsplit, urlencode, …)Networking
urllib.requestHigh-level urlopen over http.clientNetworking

Processes and the OS

Spawning children, signals, logging, arguments, and platform facts.

ModulePurposeChapter
subprocessSpawn child processes with pipe captureProcesses & OS
signalPOSIX signal numbers and delivery helpersProcesses & OS
argparseCommand-line parsing (ArgumentParser, add_argument)Processes & OS
loggingA Logger plus debug/info/warning/error/criticalProcesses & OS
platformsystem/node/release/version/…Processes & OS
getpassNo-echo password input and current-user lookupProcesses & OS

A few areas live outside Part 14 because they have their own home in the book: the concurrency primitives (threading, collections.concurrent) are covered in Concurrency, the database package in Databases, and unittest in Testing.

At a glance

If you need to…Reach forCovered in
Read or write a fileio, os.pathFiles
Match or reshape textre, textwrap, stringText
Parse JSON / CSV / TOMLjson, csv, tomllibData Formats
Do math or handle datesmath, datetime, statisticsDates & Math
Chain or reduce iterablesitertools, functoolsFunctional Tools
Hash a password or sign datahashlib, argon2id, cryptoCrypto
Open a socket or call HTTPsocket, http.client, urllib.parseNetworking
Spawn a process or parse argssubprocess, argparseProcesses & OS
Look something up alphabetically-Stdlib Index

With the shape of the library in hand, the natural place to start is the one every program eventually reaches for: Files and the Filesystem.