Supported subset and known differences¶
py2axum translates a closed subset of Python and of a list of libraries. Anything outside it is refused at
compile time with file:line (and counted by --report), so a construct is either translated with the
behaviour described in these pages or not translated at all. Method calls and attribute reads on values only
known at run time are checked by name: a name that no runtime type implements and that the project never
defines is refused (a name that exists on another type than the actual receiver is not detected). Each item of
these pages is covered by conformance cases that compare the binary with the Python application, response by
response.
"Differences" are the places where the binary is knowingly not identical to CPython; they are listed so you can decide whether they matter for your application.
New to py2axum? Start with the getting-started guide;
py2axum check tells you what these pages mean for your application, route by
route. To check the binary against your application, see Conformance and replay.
There is one backend since 0.4 (the statically-typed one was removed: it covered only simple CRUD handlers;
its list streaming moved to Large list responses). The
--backend option, which had no effect since then, was removed in 1.0.
Where each part is described¶
| Topic | Page |
|---|---|
| Supported versions | Versions |
Python 3.12 to 3.15: what each version changes, sys.version_info |
Python versions |
| Applications, routers, factories, imports, routing, mounts, raw ASGI routes | Bigger applications |
| Path, query and header parameters, timestamps | Parameters |
JSON bodies, JSON decoding, strict_content_type |
Request body |
Form(), File(), UploadFile |
Forms and files |
| Dependencies, the session dependency | Dependencies |
| Security schemes (OAuth2, HTTP Bearer, HTTP Basic) | Security |
Responses, response classes, status codes, StreamingResponse, generator endpoints (JSON Lines, Server-Sent Events) |
Responses |
BackgroundTasks |
Background tasks |
Exception handlers, HTTPException, Starlette's error layers |
Handling errors |
Middleware (BaseHTTPMiddleware, raw ASGI, GZip, starlette_context), request attributes, configure(app) |
Middleware |
CORSMiddleware |
CORS |
| Shutdown (SIGTERM, SIGINT) | Graceful shutdown |
logging, python-json-logger, loguru's logger, uvicorn's own lines (startup, access log, errors), tracebacks, uvicorn's command-line options |
Logging |
| WebSockets | WebSockets |
| Pydantic v2 | Models (Pydantic) |
| SQLAlchemy 2.0 (async and sync, PostgreSQL) | SQL databases |
| Python semantics, asyncio and threading | Python semantics |
| Lifespan | Lifespan events |
Sentry (sentry-sdk 2.x) |
Sentry |
Prometheus (prometheus_client 0.26) |
Prometheus metrics |
MCP servers (mcp 2.2) |
MCP servers |
Standard library, pickle |
Standard library |
| Libraries | Libraries |
Hybrid deployments, what --python-side auto leaves to Python (routes, lifespan, the whole application) |
Hybrid mode |
| Large list responses | Large list responses |
| Generated documents: spreadsheets (openpyxl), PDF (reportlab), temporary files | Generated documents |
Runtime environment¶
The binary takes uvicorn's command-line options and prints uvicorn's lines and the application's logging
and loguru records as Python does (Logging; a traceback holds the project's frames only).
It reads its configuration from the environment (the list);
it does not read .env files (pydantic-settings reads environment variables only, see
Models): export the variables, as an orchestrator does.
Limits on untrusted input (an optional body cap, the stack size) and the differences they imply are in
Security § Request input.
Object addresses in reprs (<X object at 0x...>) are the binary's own; their width matches CPython's on 64-bit
Linux, not on macOS, where a truncated repr in the logs is cut elsewhere (Python).
--python-side auto¶
A construct that does not translate in the lifespan, a middleware, an exception handler or module code no
longer stops the generation with --python-side auto: the lifespan alone, or the whole application, is left to
Python (Hybrid mode § What auto leaves to Python).
Known differences: the Python lifespan runs in its own process, not before the binary listens; its output
comes from that process; a whole application relayed still gets the binary's uvicorn lines and access log
(--no-access-log). WebSocket connections are relayed too; their handshake lines are the binary's, the
application's own lines (an error, a traceback) the Python process's.
Deeply nested JSON on Python 3.14+¶
From Python 3.14, json.loads is bounded by the C stack instead of the recursion limit: a document nested
beyond 10 000 levels decodes in CPython (up to roughly 50 000 levels on an 8 MiB stack, then
RecursionError: Stack overflow (used ... kB) while decoding a JSON array from a unicode string). The binary
keeps the 10 000-level limit of 3.12 and 3.13 on every Python (RecursionError: maximum recursion depth exceeded
while decoding a JSON array from a unicode string), a bound on untrusted input
(Security). Such a document usually exceeds the recursion limit later in Python
(FastAPI's jsonable_encoder when it is returned): the response is the same 500, the logged traceback differs
(where the exception is raised, and its message).
PyYAML¶
yaml.safe_load and the dump functions follow PyYAML 6.0's pure-Python implementation (its SafeLoader, which
safe_load always uses, even when libyaml is installed). Where the binary cannot follow it:
- An integer beyond 64 bits (
9223372036854775808,!!intof a long digit string) raisesOverflowError: py2axum: the YAML integer ... does not fit in 64 bits, asjson.loadsdoes; CPython returns a Python int. A digit string past 4 300 digits raises CPython's ownValueError(the int-conversion limit). - A
\uD800-\uDFFFescape in a double-quoted scalar (a lone surrogate) becomes U+FFFD: a Rust string cannot hold it (CPython keeps it in the str, which FastAPI then fails to encode as JSON: a 500). - The nesting depth at which the recursive steps raise
RecursionError: maximum recursion depth exceededis fixed: a collection nested 471 levels deep loads, one 472 deep does not; a list nested 316 deep dumps, one 317 deep does not. CPython's limit depends on the stack of the caller (those are its depths from an async endpoint under uvicorn with Python 3.12; a sync endpoint, another Python or a deeper call chain moves them). yaml.dump(the fullRepresenter) writes the builtin types as PyYAML does (!!python/tuple,!!python/complex,!!set,!!binary...); a value it would write as!!python/object...,!!python/name:...or!!python/object/apply:...(a project class, a Pydantic model, an ORM object, an Enum member,Decimal,UUID,time,timedelta...) raisesTypeError: py2axum: yaml.dump() of a ... object is not supported.yaml.safe_dumpraises PyYAML's ownRepresenterError('cannot represent an object', data)for them.- Anchors follow object identity: a list, dict, set or tuple met twice is written once with an anchor, as in
CPython; a
dateordatetimeobject met twice is not (the binary's dates are values, without identity), and an equal tuple written twice in the source is two objects in the binary where CPython may fold the constants into one. - The order of a
set(!!set,sort_keys=False) is its insertion order, not CPython's hash order (which varies from one process to the other for strings). encoding=accepts UTF-8, UTF-16, UTF-32 (with or without-le/-be), ASCII and Latin-1 (TypeErrorfor another codec); a text file read bysafe_loadis decoded as UTF-8 with universal newlines.
pytz¶
pytz 2026.5 is ported with its own zones (Libraries); what the binary does not reproduce:
all_timezonesandcommon_timezonesare alist, their_sets aset(pytz'sLazyListandLazySetsubclasses of them): the same contents and order.FixedOffset(minutes)with a fraction of a second (FixedOffset(0.01)) raises a py2axumTypeError; pickling a pytz tzinfo too.
python-dateutil¶
The parser and dateutil.tz are ported from dateutil 2.9 (Libraries); what the binary does
not reproduce:
- Library warnings are not printed (
UnknownTimezoneWarningof a time zone name the parser does not understand,DeprecatedTzFormatWarningof tzstr's old format), as for every library. - A UTC offset of a day or more cannot be a datetime's: dateutil builds the tzinfo and each later
utcoffset()raisesValueError; the binary raises thatValueErrorwhen the offset is made (parse("10:00 +9999")), and a py2axumTypeErrorfortzoffset(name, offset)andtzstr()/gettz()of such a string (gettz("iso3166.tab")of a file name holding digits). Atzstrwhose DST rule has a month outside 1..12 or a negative day (dateutil raises on each use) raises a py2axumTypeErrorwhen built.tzoffsetnames are astror None. gettzandtzstrkeep each instance for the process's lifetime (dateutil: while referenced, eight more in an LRU cache): each distinct zone file and TZ string a process reads stays in memory.tzlocal()reads the local zone (time.timezone,altzone,tzname) once, as CPython'stimemodule does at import (atime.tzset()is not followed).parse()of a stream (StringIO) raises a py2axumTypeError;isoparser().parse_isotime()of a time with an offset too (the binary'stimevalues are naive).datetime.dst()of azoneinfo.ZoneInfovalue is the tz database's saving: CPython infers it from the transitions, which differs during double summer times (1940s).
cachetools¶
cachetools 7.2 is ported from its source (Libraries); what the binary does not reproduce:
keys(),values()anditems()of a cache are lists (cachetools:MutableMapping's views), iterating a cache takes its keys first (a cache changed during the loop is not seen), and ahashkeykey is atuple(type_HashedTuple, with the samereprand hash).cachetools.func's caches serialize the concurrent calls of one key with athreading.Condition(the second caller waits and reads the first one's result): in the binary both may run the function.- A
lock=is not acquired: cachetools holds it around the cache's reads and writes only, which the binary does without interleaving them (cache.setdefault()is used when one is given, as cachetools does).
stripe¶
stripe-python 14.0–14.4 is ported (dynrt/stripe.rs, Libraries): the request each resource
classmethod sends (method, URL, form body, headers, retries), the objects built from the response (a StripeObject is
a dict subclass: attribute access to its keys, str as JSON, a list object iterating its data) and the errors
(classes, messages, attributes). What the binary does not reproduce:
Accept-Encodingisgzip, deflate(requests addsbrandzstdwhen brotli or zstandard is available).platformandunameinX-Stripe-Client-User-Agentare computed by the binary (on Linuxplatformhas no libc version);X-Stripe-Client-Telemetryreports the last request of the process (stripe-python: of the thread).- TLS checks the system's roots, not stripe-python's bundled
ca-certificates.crt. - The
(Network error: ...)detail of anAPIConnectionErroris requests' for a refused connection, a read timeout and a URL without a scheme or with another one; for other failures (DNS, TLS) it differs. auto_paging_iter()fetches every page when it is called: a loop that stops early has still made each request. The search results'auto_paging_iter()raises a py2axum RuntimeError.- A nested object without an
objectfield is aStripeObject(stripe-python: an inner class such asSubscription.TrialSettings, with the same keys);type(obj)of any StripeObject isdict. - An error's
headersis a dict with lowercase names (requests: a case-insensitive dict). - In a hybrid deployment,
stripe.api_key = ...set at run time applies to the process that runs it (the binary or the Python process). - Not translated: the
*_asyncmethods,StripeClient,stripe.default_http_client/proxy/verify_ssl_certs, multipart requests (File.create), streamed responses (PDF downloads) and the instance methods of an object (save(),refresh(),customer.delete()): refused at transpile time, or a py2axum RuntimeError when the method is only known at run time.
httpx¶
A response the server sends malformed (an invalid status line, broken headers) raises RemoteProtocolError as in
httpx, with hyper's message instead of h11's. A connection reset raises ReadError with an empty message, as anyio
reports it.
croniter¶
croniter 6.2 is ported line by line (Libraries); what the binary does not reproduce:
R(random) fields: Python draws a random number. A literal expression containing one is refused at compile time; one built at run time raisesNotImplementedError(py2axum) where Python would draw the number (after the errors croniter raises before it),is_validincluded.for x in croniter(...)andfor x in cron.all_next()/all_prev()(orlist()of them) raise a py2axumTypeError: these iterators are endless and iteration is materialised; read them withnext().croniter_range()is a lazy generator (next(),for,list()), but aforloop computes every value of the range before its first iteration.croniter.expand()of an expression holding an integer of more than 4300 digits: Python'sCroniterBadCronErrorcarries the formatted traceback of theValueError, the binary its message only.- The
CroniterUnsupportedSyntaxErrormessage prints each nth set with its numbers first, then'l'; Python's order of a set mixing both depends on the string hash seed (PYTHONHASHSEED). - Time zones:
datetime.timezoneandzoneinfo.ZoneInfo(the zone rules are the runtime's tz database, Python's those of the system or of thetzdatapackage), pytz zones (localize, pytz's own data) and dateutil zones (the system's files, as dateutil reads them). - A start time that
gmtimecannot represent raises the platform'sOSError([Errno 75]on Linux). croniter_range(_croniter=),croniter.expand(from_timestamp=)andis_valid(encoding=)other than UTF-8 are refused at compile time; a start time other than adatetime, anintor afloat, andcroniter_rangebounds other than datetimes and numbers raise a py2axumTypeError.
qrcode¶
qrcode 8.2 and the PNG Pillow 12.3 writes are ported (Libraries); what the binary does not reproduce:
- The PNG is the one of Pillow's PyPI wheels for the platform the binary is built for: their zlib is zlib 1.3.1 on
Linux (manylinux) and zlib-ng on macOS, and the binary compresses the same way on each. A Pillow built from
source against another zlib (a distribution package,
--no-binary) writes the same pixels with other compressed bytes. - A negative
error_correction: qrcode never returns (its BCH loop does not end on a negative number); the binary raises a py2axumTypeError. - An image of more than 2³¹ − 1 pixels a side raises
MemoryError(Pillow raises its own error earlier or later, depending on memory).
email.message.EmailMessage¶
The header parser and folder of email.policy.default are ported with the behaviour of each supported CPython
release (standard library); what the binary does not reproduce:
msg[name]returns the header's text as astr, not a header object (.addresses,.defects,.nameare not available; assigning one message's header to another parses its text again).- An encoded word (
=?charset?q?...?=) in a header value whose charset is not UTF-8, Latin-1 or ASCII, or whose bytes do not decode with it, raises a py2axumTypeError: Python keeps undecodable bytes as surrogate escapes. - Header values are
str,None, or for address headers a list ofstr; other values (header andAddressobjects, numbers) raise a py2axumTypeError.
dnspython¶
dnspython 2.8's stub resolver is ported (Libraries); what the binary does not reproduce:
- Names are ASCII: a non-ASCII name (dnspython encodes it with IDNA 2008, or 2003 without the
idnapackage) raises a py2axumTypeError. - Records of other types than MX, TXT, A, AAAA, CNAME and NS are skipped when a response is read: a response
holding a malformed record of such a type is accepted where dnspython drops it (and waits for another one);
an answer of such a type raises a py2axum
TypeError. - The exceptions carry their message only (
NXDOMAIN.qnames(),NoAnswer.response(),kwargs... are not available). An answer'srrset,responseandexpirationare not available. - Durations in
LifetimeTimeout's message and the order ofrotatefollow the clock and the random generator, as in Python, not Python's own draws.
pgpy¶
pgpy 0.6.0's PGPKey.from_blob() is ported (Libraries): the parsing of a public or secret
key block, armored or binary, to the same objects, the same order of the user ids and the same exceptions, checked
against pgpy on the inputs of fixtures/pgpyapp (keys of pgpy and GnuPG, armor, base64, packet and user id edge
cases, mutations of valid keys). Nothing is encrypted, decrypted, signed or verified: those parts of pgpy (and
PGPMessage, PGPSignature, PGPKeyring, PGPKey.new()...) are refused at transpile time. What the binary does
not reproduce:
- A CompressedData packet compressed with bzip2 whose stream holds a block (pgpy decompresses it) raises a py2axum
NotImplementedError; empty, truncated or invalid bzip2 data behave as in Python. zlib and raw deflate data are decompressed by zlib, as in CPython (the error messages are zlib's own). type()of the tuple's second element and ofkey.subkeysisdict(pgpy:OrderedDict, same order and contents).- The warnings are written on stderr as CPython's default filters write them (once per text and line), naming the
path pgpy had where the project was translated. The address in
Warning: Orphaned packet detected! <... at 0x...>is not CPython's: CPython prints that warning again only when the packet's address differs from an earlier one's, the binary every time. - pgpy's
PGPKey.parsegroups packets byid(): when CPython reuses the address of a freed packet for the next one of the same class, the two may be read as one group. The binary never does. - Inputs that make pgpy loop for minutes (a flags subpacket declaring a length of several gigabytes) answer at once, with pgpy's eventual result.
- The
__cause__of aPGPErroris an exception of the original class and message (binascii, pyasn1, struct and zlib errors included), without their own attributes.
OpenTelemetry (FastAPI 0.142+)¶
FastAPI 0.142 traces requests, records metrics and logs through OpenTelemetry when its SDK is configured (a global
provider, or exporters added from the OTEL_* environment variables). Known difference: the binary emits no
OpenTelemetry data and does not read OTEL_*. FastAPI(telemetry={...}) is accepted with its switches
(tracing, metrics, logs, operation_spans, auto_configure) as literals; a provider (tracer_provider=...),
exclude= and the opentelemetry SDK calls are refused.
SQLModel¶
SQLModel classes are rewritten into SQLAlchemy mapped classes and Pydantic models at translation (see Libraries). Known differences:
- A table instance dumped as itself (a table class as the return type or
response_model=, or returned without one): CPython lists its keys in the order of its__dict__, which after a load from the database depends on Python's string hashing (it changes from one process to the next); the binary lists the fields in their declaration order. A response model without a table (HeroPublic) has the same output on both sides. - A table class as a route's body, a required field left out: SQLModel leaves the attribute unset (absent from the
dumped response), the binary reads it as
None.
SQLAlchemy's DBAPIError.connection_invalidated¶
True when the connection itself failed (refused, dropped or reset: an I/O, TLS or protocol error of the driver, raised
as OperationalError), false for an error the server answered (any SQLSTATE). SQLAlchemy asks psycopg's dialect,
whose test looks at the connection's state: a server that answers an error and then closes the connection
(57P01, administrator shutdown) is invalidated in Python and not in the binary. InterfaceError is a class
(isinstance, except); the binary raises OperationalError for every connection-level failure.
Not supported¶
An application wrapped in a project ASGI class at module level (app = Wrapper(api), refused: the
binary would serve api without it), mounted ASGI apps and routers of libraries (left to Python with
--python-side mount when registered last), libraries not listed, C extensions, eval/exec, metaclasses, multiple inheritance of
project classes, the synchronous subprocess module and asyncio.create_subprocess_shell, tempfile beyond NamedTemporaryFile/gettempdir, OpenAPI /docs in the binary, and assigning an attribute of the application at module level
other than app.state, app.dependency_overrides[f] = g and app.router.route_class = R (app.openapi = ...
is refused with file:line). Not native, counted apart in the
documentation coverage: what only changes the OpenAPI schema or the documentation pages
(/openapi.json, /docs, custom docs assets), OpenTelemetry providers in FastAPI(telemetry=...), GraphQL
routers, UJSONResponse.