Repository navigation
Releases
unpythonic 2.5.0 — "Turtles all the way down"
New:
- Update one item deep inside nested containers, like Clojure's
update-inandassoc-in. The path is a sequence of steps — keys, indices, and attribute names, in any mix — so dicts, lists,envs, named tuples, frozen dataclasses andfrozendicts can all be walked through in one call.mogrify_in_with(func, path, container)andmogrify_in_to(value, path, container)update in-place, withmogrify's semantics: every mutable container along the path keeps its identity, and an immutable one is rebuilt and stored back into its parent.fupdate_in_with(target, path, func)andfupdate_in_to(target, path, value)are the functional variants, which never mutate their input and share everything off the path with it.
Fixed:
- A shallow copy of an
env—copy.copy, orfupdategiven anenv— now has bindings of its own. It used to share them with the original, so rebinding a name in the copy rebound it in the original too. namedlambda's docstring now says it names a lambda bound in an env-assignment orletbinding in either spelling,:=or<<. It listed only<<, right after a bullet where:=meant Python's own named expression, so a reader could conclude the walrus form is not named.- The REPL documentation now says that the client reads piped stdin, running each line in the session namespace — so a shell script can drive a live app with nobody at the keyboard. The docs described only the interactive session, which is the smaller half of what the client does.
- It also names the trap that makes an automated check necessary: the session echoes the value of an expression and a statement has none, so a pipe made only of assignments prints nothing and looks identical whether it ran or not. Have such a script
printsomething and check for it;python3 -m unpythonic.net.serveris a throwaway host to test the pipe against first.
- It also names the trap that makes an automated check necessary: the session echoes the value of an expression and a statement has none, so a pipe made only of assignments prints nothing and looks identical whether it ran or not. Have such a script
unpythonic 2.4.0 — "'Tis but a scratch"
Python 3.15 support. The language grew two pieces of syntax that change the AST, and the macro layer needed no overhaul to take them — lazify, autocurry, tco and continuations all pass the new comprehension forms through untouched. The work here is the tests that establish that, rather than any change to what the macros do.
New:
- Python 3.15 is supported.
requires-pythonmoves from<3.15to<3.16, andmcpyrate4.3.0 or newer is now required, since earlier versions cannot import anything at all under 3.15.- The macros needed no changes for the new syntax.
lazify,autocurry,tcoandcontinuationsall pass comprehension unpacking ({**mapping for x in xs},[*items for item in xs], and the set and generator forms) through untouched. - There are now tests to keep it that way, and they check the properties rather than the results — laziness by leaving a
1 / 0unevaluated, currying by partially applying, TCO by recursing deeper than the stack allows. Alazifythat had quietly gone strict inside the new forms would return the right answer and fail these.
- The macros needed no changes for the new syntax.
Changed:
env.finalize()now returnsselfinstead ofNone, so it can be chained:e = env(x=42).finalize(). Matches the existing instance passthrough on<<.
See the changelog for the documentation fixes also included in this release.
unpythonic 2.3.0 — "Mind the gap"
New:
unpythonic.misc.si_prefix: new parametersseparatorandalways_separate, for callers that append a unit of measurement.separator(default" ", per SI) is what goes between the number and the prefix;separator=""gives the compact"1.50k"that some UIs prefer.always_separateemits the separator even where the magnitude needs no prefix, sof"{si_prefix(n, always_separate=True)}W"reads"1.50 kW"and"42.00 W"rather than"1.50 kW"and"42.00W". Without it the spacing depends on the magnitude, which is exactly what a caller appending a unit does not want.
unpythonic 2.2.0 — "Hail Eris"
Two new dialects, esoteric and qualitatively different.
The dialects
unpythonic.dialects.bf— Brainfuck as a dialect. Source-to-source transpiler with legible Python output (bf.compile(src)returns the generated code as a string for inspection). 8-bit wrapping tape viadefaultdict[int, int];bfsource comments preserved as Python comments;resetline clears the tape between programs.unpythonic.dialects.befunge— Befunge-93 as a dialect. Runtime interpreter for a strict 80×25 toroidal playfield with byte cells and an unbounded-int stack. All Befunge-93 commands supported, including?(random direction; seedable viarun(src, *, seed=...)for tests),p/g(self-modifying code), and&/~(integer/character input). Thebf/befungepair demonstratesmcpyrate'sDialect.transform_sourcehook in two qualitatively different modes: dialect-as-transpiler (bf) and dialect-as-reader (befunge — Befunge's 2D self-modifying control flow has no statically-soundable structure).
Other new
expect[]— new expr macro for declaring the tested expression insidewith test:. Replacesreturn expr, which still works but emits aDeprecationWarningand will be un-hijacked in 3.0.0 soreturnregains its standard Python meaning insidewith test:.unpythonic.excutil.withf—withas a function. Expression form completing theraisef/tryf/withfsuite. Single CM or tuple; body arity auto-detected.@multishot,myield,myield_from,MultishotIterator— multi-shot generators. A@multishotfunction is generator-shaped but everymyieldcaptures the execution state as a continuation, so it can be resumed from any earliermyieldarbitrarily many times.MultishotIteratorexposes a subset of the standard generator protocol pluscopy.copy(mi)forking. Only meaningful insidewith continuations:. Closes #80.Valuesunpacking inunpythonic.funutil.callandcallwith. EachValuesin positional args expands in place (left-to-right), splicingretsinto positional args and mergingkwretsinto kwargs. Mirrors Python's[*a, *b, c]/{**a, **b}semantics.FrozenAttributeError— compatibility shim multiply inheriting fromTypeError(legacy) anddataclasses.FrozenInstanceError(stdlib convention). Raised byconson attribute write/delete. TheTypeErrorbase will be dropped in 3.0.0.redirect_stdin— context manager feedingsys.stdinfrom a stream. The third sibling ofcontextlib.redirect_stdout/stderr, which the stdlib never shipped.
Fixed
unpythonic.misc.callsite_filenamenow usessys._getframeinstead ofinspect.stack(). Latent PyPy-3.11 / macOS / Windows bug:inspect.stack()raisedTypeErrorwhen any frame in the walk reportedf_lineno = None.unpythonic.llist.cons.__delattr__now raisesFrozenAttributeError. Latent bug:del c.carpreviously corrupted the cell.unpythonic.assignoncenow forbidsdel e.fooon a defined name. Latent bug: the assign-once contract could be bypassed viadel; rebind.
Changed
lispython,listhell,pytkelldialects propagate the Python 3.8+ source-location fieldsend_lineno/end_col_offsetthroughsplice_dialectalongsidelineno/col_offset. Tooling that consumes precise source ranges (debuggers, PEP 657 traceback formatters) gets richer information. Closes #83.- Requires
mcpyrate >= 4.2.0.
Docs
doc/macros.md: new "Topology of continuations" and "Scoping of locals in continuations" subsections. Closes #82.
Milestone 2.2.0 complete. Closes #35, #76, #80, #82, #83, #85 (step 1; step 2 milestoned to 3.0.0), #86.
v2.1.0 — "Cat-hedral" edition
2.1.0 (17 April 2026) — "Cat-hedral" edition:
New:
unpythonic.monads: subpackage of classical monads —Identity,Maybe,Either(withLeft/Right),List,Writer,State,Reader. PlusMonad/LiftableMonadbase classes andliftm/liftm2/liftm3helpers. Not re-exported at the top level; import asfrom unpythonic.monads import Maybe.monadic_do: do-notation macro over any monad.with monadic_do[M] as result:with body[bindings] in result << final_expr; supports:=(primary) and<<(legacy) for bindings; empty bindings allowed;_ := mexprfor sequencing. Always used as the innermostwith(body shape constraint), composes correctly withlazify/continuations/tco/autocurry/etc.environ_override: context manager to temporarily override OS environment variables within awithblock, restoring the previous state on exit.- Thread-safe (serialises concurrent overrides via
RLock); same-thread nesting supported. - New module
unpythonic.environ; the function is namedoverrideat the module level and re-exported asenviron_overrideat the top level.
- Thread-safe (serialises concurrent overrides via
maybe_open: context manager that opens a file when given a path, or yields a fallback stream (e.g.sys.stdin,sys.stdout) when givenNone.- Lets callers always use
withsyntax regardless of whether the target is a file or a standard stream.
- Lets callers always use
UnionFilter: alogging.Filterthat matches a log record if any of its sub-filters match.- This is an OR combinator that is oddly missing from the standard library.
si_prefix: format a number with SI decimal prefixes (k through Q, m through q) or IEC binary prefixes (Ki through Qi, mi through qi).- Handles negative numbers, zero, and sub-unity magnitudes.
- The
binary=Trueflag switches to base-1024 mode.
partial(type-checking wrapper overfunctools.partial) is now exported in the public API.- It was already implemented but missing from
fun.__all__.
- It was already implemented but missing from
Sliced,FupTarget,Fuppable: tag types inunpythonic.slicingfor annotating the return values ofisliceandfup.Slicedhas abstract__getitem__.FupTargethas abstract__getitem__returningFuppable.Fuppablehas abstract__lshift__.
slift1,slift2: lift scalar unary/binary operations to work termwise on iterables, returning imathified lazy generators. Accept optional extra arguments baked into each call (e.g.slift1(round, 2)). These are the mechanism behind all built-ins-prefixed operators, now exposed for user-defined functions.ConditionProtocol:typing.Protocolcapturing the call signature shared by error-handling protocols (signal,error,cerror,warn). Useful for annotating custom protocols.
Changed:
unpythonic.amb.MonadicList: the implementation was moved tounpythonic.monads.Listand renamed.MonadicListremains as a silent alias ofListfor name compatibility, scheduled for removal in 3.0.0. The constructor uses varargs (List(1, 2, 3)) — the class itself is the monadic unit (List(x)is a singleton list). Iterable-constructor use-cases go throughList.from_iterable(iterable).unpythonic.net(REPL server and client) now runs on MS Windows.- Previously the whole subsystem was POSIX-only because
unpythonic.net.ptyproxyrequiredtermios,tty, andos.openpty. - A new
socket.socketpair()-based backend stands in for the pty master/slave endpoints on Windows, plugged in via a platform dispatch inPTYSocketProxy. - Known wart:
os.isatty(sys.stdin.fileno())inside a REPL session returnsFalseon Windows (no real pseudo-terminal is involved), whereas it returnsTrueon POSIX — user code inside the REPL that checkssys.stdin.isatty()will see the Windows result; the framework itself doesn't care.
- Previously the whole subsystem was POSIX-only because
Fixed:
unpythonic.net.server:start()now returns the actually-bound ports, not the values the caller passed in.- Matters when passing
repl_port=0/control_port=0to let the kernel pick a free port — previously the caller got(bind, 0, 0)back. - Also fixes a latent bug in
unpythonic.net.util.ReuseAddrThreadingTCPServer: its customserver_bind()override dropped theself.server_address = self.socket.getsockname()refresh from stdlib'sTCPServer.server_bind.
- Matters when passing
unpythonic.net.ptyproxy:stop()is now idempotent and safe to call on a proxy that was never started.- Latent bug: previously
stop()gated the entire teardown (includingos.close(master)/os.close(slave)) behindif self._thread:, so constructing a proxy and then exiting without callingstart()leaked both fds.
- Latent bug: previously
unpythonic.net.client: tab completion now works on macOS.- macOS ships
readlinebacked bylibedit, which speaks a differentparse_and_binddialect than GNU readline — the client now detectsplatform.system() == "Darwin"and issues the libedit form there.
- macOS ships
unpythonic.misc.timerandunpythonic.timeutil.ETAEstimator: switched fromtime.monotonic()totime.perf_counter().- Latent Windows-only bug:
monotonicis backed by a ~16 ms tick counter on Windows, so microsecond-scalewith timer() as t: ...blocks recordedt.dt = 0.0and downstream divisions raisedZeroDivisionError.perf_counterhas the highest available resolution on every platform. POSIX unaffected.
- Latent Windows-only bug:
unpythonic.arity._kwargs: generic dispatch path useddictinstead ofsetfor accumulating kwargs names. Latent bug — only triggers if a@genericfunction has keyword-only arguments.unpythonic.test.runner: module discovery no longer crashes on MS Windows withre.error: bad escape.- The runner used
re.sub(os.path.sep, ...)—os.path.sepis a lone backslash on Windows, an invalid regex pattern. Fixed by usingstr.replace. Affects any project reusingunpythonic.test.runner.
- The runner used
Internal:
unpythonic.netnow has an automated test suite for the REPL client and server.unpythonic/net/tests/test_client.pyexercises the full client ↔ server roundtrip in-process (eval, multi-line, syntax-error recovery, clean disconnect), netcat-mode raw-socket access, control-channel RPC, and stretch cases (sequential reconnect, two concurrent clients). Tier 1 only — no subprocess / pty driver. Runs on every CI platform (Linux, macOS, Windows).
unpythonic.net.ptyproxy: refactored into an abstract base class with platform-specific backends (PosixPTYSocketProxyviaos.openpty,WindowsPTYSocketProxyviasocket.socketpair).- Dispatch happens inside
PTYSocketProxy.__new__, so callers instantiate the base class and get the right backend for free. PTYSocketProxyis now a context manager (with PTYSocketProxy(...) as proxy:) for guaranteed cleanup. Public interface otherwise unchanged.
- Dispatch happens inside
unpythonic.net.client:connect()is now a thin public shim over a private_connect(..., _input=None).- The
_inputseam lets tests drive the REPL loop without monkey-patchingbuiltins.inputglobally. Public API unchanged.
- The
unpythonic.net.client:import readlinemoved from module top intoconnect(), with a three-tier fallback (readline→pyreadline3→ graceful degradation).- POSIX behaviour unchanged; the module is now importable on Windows.
unpythonic.net.tests.fixtures.nettest: binds on port 0 (kernel-assigned), removed asleep(0.05)race-condition bandage, and re-raises worker-thread exceptions instead of swallowing them.- Type annotations added to public API signatures (and private helpers/closures) across 32 modules.
- Full list of newly type-annotated modules:
regutil,symbol,assignonce,numutil,misc,excutil,fup,fix,environ,fun,it,fold,funutil,lazyutil,ec,singleton,env,gtco,amb,tco,slicing,dynassign,gmemo,llist,fploop,let,lispylet,seq,collections,arity,conditions,mathseq. - Remaining unannotated:
dispatch,typecheck(hard tier — deeply dynamic). - Convention:
F = TypeVar('F', bound=Callable)for callable parameters,T = TypeVar('T')for data values.
- Full list of newly type-annotated modules:
ambcleanups.Assignmentrenamed toChoice.- Internal
envclass renamed toScope. MonadicListconstructor standardized to accept a single iterable (likelist/tuple);Sequencemethods added (__reversed__,__contains__,index,count); registered asContainer/Iterable/Sized/SequenceABC.
slicing: NewSlicedandFupTarget/Fuppabletag types with abstract methods, used as return types forisliceandfup. Public API for type annotations, exported in__all__.collections: Internal class_StrReprEqMixinrenamed to_SequenceReprEqMixin.__eq__now requiresSequenceand raisesTypeErrorfor incompatible types (latent bug: previously crashed on non-Sizedinput).roview._cacheattribute now declared in__init__._make_negidx_converter.convertnow has explicitreturn Nonefor passthrough path.
arity._bind: rebased from Python 3.8.5inspect.Signature._bindto Python 3.14. Adds deferred positional-only-in-kwargs handling, updated error messages. Divergence points marked with[unpythonic]for easy auditing.OrderedDict→dictthroughout (ordered since 3.7).mathseq:hasattr(x, "__iter__")→isinstance(x, Iterable)(3 sites).imathifyregistered as virtual subclass ofIterable. Internalprimitive_*operator aliases renamed toatom_*.spow/sroundvarargs (*mod,*ndigits) changed toint | None = None.- Bare
object()sentinels replaced withsym/gensymfor debug readability.- Affected:
ec.py(gensym("anchor")),llist.py(gensym("fill"), module-level),fold.py(sym("_uselast")),test_conditions.py,test_collections.py.
- Affected:
Version 2.0.0
2.0.0 (16 March 2026) — "Six impossible things before breakfast" edition:
IMPORTANT:
- Python version support: 3.10–3.14 (dropped 3.8, 3.9; added 3.13, 3.14). PyPy 3.11.
- If you need
unpythonicfor Python 3.8 or 3.9, use version 1.0.0.
- If you need
- Requires mcpyrate >= 4.0.0.
- mcpyrate 4.0.0 dropped the
Str,Num,NameConstantAST compatibility shims and thegetconstanthelper. Useast.Constantdirectly, and.valueto get the constant's value.
- mcpyrate 4.0.0 dropped the
New:
- Python 3.13 and 3.14 support.
autoreturnmacro now handlesmatch/casestatements. Each case branch has its own tail position.- New scope analyzer tests for
match/casepatterns andtry/except*. - New
unpythonic.test.runnermodule: reusable test runner with module discovery, version-suffix gating (e.g.test_foo_3_11.pyskipped on Python < 3.11), and integration with the test framework's warning system. Other projects usingunpythonic.test.fixturescan import it directly. - New
emit_warning()function inunpythonic.test.fixturesfor signaling test warnings from infrastructure code (outsidetest[]/warn[]macros). Used by the test runner for version-suffix skips, which show in the warning count for the innermost enclosing testset. - Missing optional dependencies (sympy, mpmath) in tests emit
warn[]instead oferror[], correctly reflecting that these are expected skips, not failures. - Runtime type checker (
unpythonic.typecheck): new supported typing features —NoReturn,Never(3.11+),Literal,Type,ClassVar,Final,DefaultDict,OrderedDict,Counter,ChainMap,IO/TextIO/BinaryIO(mapped toiomodule ABCs),Pattern[T]/Match[T](string type checked when parametric),ContextManager,AsyncContextManager,Awaitable,Coroutine,AsyncIterable,AsyncIterator,Generator,AsyncGenerator. - Runtime type checker:
TypedDictsupport — structural checking of required/optional keys and value types. - Runtime type checker:
Protocolsupport —@runtime_checkableProtocols work viaisinstance; non-runtime-checkable Protocols raiseTypeErrorwith an actionable message. - Runtime type checker: parametric forms of abstract ABCs —
Iterable[T],Collection[T],Reversible[T]perform best-effort element checking (elements checked when value isSized; ABC-only for opaque iterators).Iterator[T]andContainer[T]accept parametric form with type arg silently ignored (iterating anIteratorwould consume it;Containeronly has__contains__, so elements can't be enumerated).
Fixed:
- Runtime type checker (
unpythonic.typecheck): fixed compatibility with Python 3.14, wheretyping.Unionis no longer a_GenericAlias. Now usestyping.get_origin(available since 3.8). - Runtime type checker: fixed
TypeVardetection to useisinstance(T, typing.TypeVar)instead of a fragilerepr-based heuristic. - Runtime type checker:
typing.Reversiblecheck now usesisinstanceinstead of ahasattr("__reversed__")workaround from the Python 3.5 era. - Runtime type checker: removed redundant
safeissubclassfallbacks for generic types —typing.get_originhandles both bare and parameterized generics on 3.10+. - Scope analyzer: fixed
MatchCapturesCollectorbug where class references (e.g.Pointincase Point(x, y):) were incorrectly collected as captured variable names. - Macro layer: updated all
hasattr(tree, "ctx")checks to usegetattrwith defaults, for correct behavior on Python 3.13+ where AST fields always exist with default values.- Important: Since Python 3.13, the default of
ctxisLoad(), hence no AST node has itsctxin a "not set yet" state anymore. Hence, any macro-createdNamenodes that appear in aStoreorDelposition MUST have theirctxset appropriately by the macro author. Failing to do so will cause mysterious errors during macro expansion.
- Important: Since Python 3.13, the default of
- Macro layer: updated
arguments()constructor calls to always includeposonlyargs=[], avoiding aDeprecationWarningon Python 3.13 (will become an error in 3.15). - MS Windows:
unpythonic.net.utilfailed to load, due to missingtermiosmodule (which is *nix only) being loaded byunpythonic.net.__init__when it importsunpythonic.net.ptyproxy.- Fixed by catching
ModuleNotFoundError, disablingptyproxyon MS Windows systems. Thus the remote REPL functionalityunpythonic.net.client/serveris not available on MS Windows, but the rest ofunpythonicworks fine.
- Fixed by catching
Deprecated:
- Parenthesis syntax for macro arguments (e.g.
let((x, 1), (y, 2))). Use bracket syntax instead:let[[x, 1], [y, 2]]. The parenthesis syntax is kept for backward compatibility for now. - Runtime type checker:
typing.Text(deprecated since Python 3.11) andtyping.ByteString(deprecated since Python 3.12) support is now marked for removal when the floor bumps to Python 3.12.
v1.0.0 — "Same supercharger, new badge" edition
Re-release of 0.15.5 as 1.0.0. No code changes. The library has been stable and in light maintenance mode for years; the version number now reflects this de facto status quo.
Also includes CI modernization: Dependabot for GitHub Actions, bumped action versions to current.
Available on PyPI.
v0.15.5
0.15.5 (16 April 2025) - hotfix:
Changed:
-
Internal: Upgrade build system to
pdm.- This is important for the road ahead, since the old
setuptoolsbuild system has been deprecated. - The GitHub CI scripts for
unpythonicnow use PDM to manage the testing venv and dependencies, too. Now the tests should run the same way as they would on a local system.
- This is important for the road ahead, since the old
-
Bump
mcpyrateto the hotfix version 3.6.4.- The only difference is (beside
mcpyratetoo internally upgrading its build system topdm) that the text colorizer now works correctly also forinputwithreadline.
- The only difference is (beside
0.15.4 (27 September 2024) - hotfix:
Fixed
- Bump
mcpyrateto the hotfix version 3.6.3.- This is only to make sure no one accidentally installs the broken version,
mcpyrate3.6.2, which had a bug in interactive console mode that wasn't caught by CI.
- This is only to make sure no one accidentally installs the broken version,
v0.15.3
0.15.3 (27 September 2024) - New tree snakes edition:
IMPORTANT:
- Minimum Python language version is now 3.8.
- We support 3.8, 3.9, 3.10, 3.11, 3.12, and PyPy3 (language versions 3.8, 3.9, and 3.10).
- Python 3.6 and 3.7 support dropped, as these language versions have officially reached end-of-life. If you need
unpythonicfor Python 3.6 or 3.7, use version 0.15.2.
- Minimum version for optional macro expander
mcpyrateis now 3.6.2, because theastcompatutility module was moved there.
New:
- Python 3.12 support.
- As in, all tests pass, so there are no regressions. Some undiscovered interactions with new language features (
typestatement) may still be broken, although the most obvious cases are already implemented.
- As in, all tests pass, so there are no regressions. Some undiscovered interactions with new language features (
- Python 3.11 support.
- As in, all tests pass, so there are no regressions. Some undiscovered interactions with new language features (
try/except*construct) may still be broken, although the most obvious cases are already implemented.
- As in, all tests pass, so there are no regressions. Some undiscovered interactions with new language features (
- Walrus syntax
name := valueis now supported, and preferred, for all env-assignments. Old syntaxname << valuestill works, and will remain working at least until v0.16.0, whenever that is.- Note that language support for using an assignment expression inside a subscript without parenthesizing it was added in Python 3.10.
- If you still use Python 3.8 or 3.9, with the new
:=syntax you must put parentheses around eachletbinding, because syntactically, the bindings subform looks like a subscript. - All documentation is written in Python 3.10 syntax; all unit tests are written in Python 3.8 syntax.
Changed:
- Utility module
unpythonic.syntax.astcompat, used by the macro layer, moved tomcpyrate.astcompat. This module handles version differences in theastmodule in various versions of Python.
Fixed:
ETAEstimatoredge case: at any point after all tasks have been marked completed, return a constant zero estimate for the remaining time.- Fix borkage in
mathseqwhen running with SymPy 1.13 (SymPy is only used in tests). Bump SymPy version to 1.13. - Fix bug in scopeanalyzer:
get_names_in_store_contextnow collects also names bound inmatch/caseconstructs (pattern matching, Python 3.10).
v0.15.2
0.15.2 (19 September 2024)
This time, just a small but important fix.
Fixed:
unpythonic.env.envis now pickleable. Save your fancy bunches into.picklefiles and load them back!
Future plans:
Contrary to appearances, this project is not dead. But it already does most of what I personally need it to do, so it is pretty much in maintenance mode. And it has not required much maintenance over the past two years.
We still plan to officially support Python 3.11+ later, as well as to update all constructs with assignment semantics to use the more appropriate := operator, when/if I find the time to do so. The syntax uses << for historical reasons - these constructs were originally implemented in 2018, on Python 3.4, back when := did not exist.
The most likely upgrade timeframe is when I personally switch to Python 3.11+, and something breaks. That is also when I'll likely next upgrade the sister project mcpyrate.