Skip to content

Coconut v3.3.0

Choose a tag to compare

@evhub evhub released this 30 Nov 01:45
· 57 commits to master since this release
9e9deed

See the documentation for more information on all of the features listed below.

Language Features

Are these really algebraic data types? #418: Coconut now has real sum types with case data, which defines a closed set of data variants that type checkers see as the union of its variants. Matches on case data types are checked for exhaustiveness by MyPy and Pyright, so a missing variant is a type error (e.g. UnhandledCaseDataVariants[Square]).

Extend assignment function notation / make more things expressions #190: Added match expressions, which can be used on the right side of an assignment, after return, or as the body of an assignment function, as in def area(shape) = match shape: followed by case lines that each give a result.

Added update sections for making updated copies of immutable objects, including nested ones, such as player |> (.pos.x += 1) |> (.hp -= 10). Consecutive update sections in a pipe are compiled into a single update, and ._replace on pattern-matching data types now checks the new values the same way the constructor does.

Added final declarations (e.g. final x = 1), which make reassigning a variable a compile-time error.

Added PEP 810 lazy imports (lazy import json), supported on every Python version.

Added PEP 822 d-strings (dedented multiline strings).

Added a backport of Python 3.14's lazy annotations to every target. Annotations of functions, classes, and modules are no longer left as strings at runtime (as with from __future__ import annotations, which was Coconut's previous behavior); instead, they're evaluated the first time __annotations__ is accessed, in the scope they were written in (so they can use names defined later, in enclosing functions, or in class bodies). An annotation that can't be evaluated yet stays a string until it can be. from __future__ import annotations is now respected on every target to keep annotations as strings, and --no-wrap-types now means evaluating annotations eagerly.

Support pattern-matching in comprehensions #887: Comprehensions can now use pattern-matching for clauses, including mixed with normal clauses.

where with final result at end #863: Added the block where syntax, x = where:, whose last line is the result.

Match rest keyword arguments of a data class #899: Data and class patterns now support **rest.

Add literal typing.Unpack syntax #802, Compile variadic generic typing syntax to Unpack calls #662: Added *args: *Ts, and *Ts in type subscripts and class bases, compiled to typing.Unpack on targets that need it.

Added PEP 696 type parameter defaults, starred subscripts on all targets, and comments and line breaks inside f-string expressions.

Type hints don't work with *args inside data #579, MyPy can't detect default arguments for data types #318: Starred data fields and data type __new__ arguments can now have type annotations.

Built-ins

Added iterate(func, x) (x, func(x), func(func(x)), ...) and unfold(func, seed), which are lazy, can be iterated over more than once, and support efficient indexing and slicing.

Add map_using to starmap and add more .using_processes/.using_threads methods #808: Added starmap(..., map_using=...), starmap.using_processes, and starmap.using_threads, plus map.using_processes/map.using_threads as aliases for process_map/thread_map.

Compiler and Tooling Features

Providing a language server implementation for coconut #513, Better IDE integration #537: coconut --lsp now runs a full-featured language server with diagnostics (including lint and optional type checking), hover documentation, go to definition, references, completion, signature help, document symbols, and highlights. coconut --mcp serves the same tools over the Model Context Protocol. For Claude Code, the Coconut repository is also a plugin marketplace with a plugin that gives Claude the language server, those tools, and the AI guide below: install coconut[lsp] and run /plugin install coconut --marketplace evhub/coconut in Claude Code.

Coconut is now much easier for AI coding assistants to write: coconut --ai-docs (or llms.txt) prints a concise guide to writing idiomatic Coconut, and compiled files point back to their source and to the guide.

Added --pure mode, which enforces functional purity (no reassignment, mutation, or mutable default arguments) and requires every multi-case match to be total.

Coconut options can now be set in the [tool.coconut] table of a project's pyproject.toml.

Add coconut -m support #801: coconut -m module compiles a module's package and then runs it like python -m.

Pytest with automatic compilation #888: Added an opt-in pytest plugin (pytest -p coconut.pytest_plugin) that collects test_*.coco files.

Add Coconut line numbers to MyPy output #332, Add proper pyright support #785: MyPy and Pyright errors now point to the Coconut source line.

Addpattern with mypy - name already defined #524: Type checkers no longer report redefinition errors for addpattern def.

Warn or strict error on undefined names #889: Coconut's undefined name warnings now understand scopes.

Produce better assert error messages #456: Failed asserts of simple comparisons now show the values being compared.

Add a way to configurably silence warnings #774: Added --silence-warnings <regex> to hide matching warnings.

Coconut is incompatible with the zipapp module #720: Compiled packages now work inside zipapps.

New warnings (errors under --strict): return, break, or continue exiting a finally block (PEP 765), and shadowing imported names (other than by importing a submodule, e.g. import a.b after import a).

Compiled code is much cleaner for type checkers. Coconut no longer adds # type: ignore comments where MyPy and Pyright don't need them (including in the header of every file in a package, class patterns, lazy imports, addpattern def, and data types), or on lines of their own. data types also no longer produce Pyright errors: their starred-field methods and pattern-matching helpers are hidden from type checkers (which already see the right types from the underlying named tuple), methods that a data body defines itself with a normal def (e.g. __add__, __eq__, or __new__) are no longer also generated, and __new__ takes cls as its first argument. Class patterns (e.g. case Point(x, y)) also no longer make Pyright treat the class as not callable afterwards, and Pyright no longer thinks the names that patterns bind might be unbound (which made e.g. case Square(s): s * s an error). Together these remove hundreds of unnecessary-ignore warnings and over a hundred Pyright errors from Coconut's own test suite.

Compiled output is now deterministic, and compiling is substantially faster, both from compiler improvements and from cPyparsing 2.4.7.2.4.4, which makes compiling about 26-40% faster on its own.

The tutorial has been updated, with exercises and new sections (including on case data), and now has an interactive version where every example can be run in the browser.

coconut[mypy] now requires MyPy 2.4 or later (and thus Python 3.10+, which --mypy already effectively required, since earlier versions get many of the built-in types wrong), and other optional dependencies have been updated to their latest versions.

Type checkers now report addpattern def without a previously defined function (which was already deprecated, since it acts like match def) rather than having it hidden by a # type: ignore.

TYPE_CHECKING can no longer be redefined (unless escaped as \TYPE_CHECKING), since Coconut's compiled code relies on it being False at runtime; importing it from typing or setting it to False (the usual idiom) still works. Compiled code checks the bare TYPE_CHECKING because that's the only spelling (besides typing.TYPE_CHECKING) that Pyright treats as a static condition.

The Jupyter kernel, the %coconut IPython magic, the xonsh integration, and the coconut encoding now evaluate annotations lazily, like compiled code, rather than with --no-wrap-types.

Deprecations (will change in Coconut v4)

Make sequence patterns match Python's (PEP 634) semantics #911: Sequence patterns matching strings, and star and unparenthesized tuple patterns matching arbitrary iterables, now show a CoconutWarning, since these matches will fail in Coconut v4, as they do in Python. Use lazy list patterns ((| x, *rest |)) to match any iterable, or string patterns to match strings.

Make ambiguous operator partials like (.%2==0) a syntax error in v4 #914: Operator partials whose operand binds less tightly than their operator, like (.%2==0) (which means x => x % (2==0)), now show a warning (an error under --strict).

Bugfixes

Coconut Jupyter notebooks cannot execute #908: Fixed the Jupyter kernel with newer versions of ipykernel.

xonsh multiline with coconut: SyntaxError #906: Fixed backslash line continuations in xonsh.

The --interact option in v3.1.0 and later #909: --interact now works without a source file.

Pickle fails in REPL #146: Classes and functions defined in the interpreter or coconut -c can now be pickled (and so used with process_map).

Make chain non-lazy when laziness is not needed or problematic #410: Operands of :: that are already-defined names are now evaluated immediately, which fixes a segfault from x = x :: y.

Fixed compatibility with MyPy 2.x, chained exponentiation (a**b**c) failing to parse, and a number of other miscompilations of modern Python syntax.

Coconut's header no longer looks up builtins or Coconut built-ins by name when its functions are called, which broke things like tail call optimization, hashing an Expected, MatchError messages, and memoize(memoize.RECURSIVE) in the interpreter, coconut -c, Jupyter, and --standalone code after user code rebound a name like isinstance or hash. (Coconut's test suite now checks this, for both the header and compiled code.)

--mypy --warn-unused-ignores (and Pyright's reportUnnecessaryTypeIgnoreComment) now work with Coconut code: since a # type: ignore goes on every line that its Coconut line compiles to, Coconut now only reports it as unused if all of those copies are unused, and then only once.

Fixed the lines after a match expression or case data block (and after multi-line functions with lazy annotations) getting the wrong line numbers, which put errors on the wrong line and gave them the wrong line's comments, and fixed a # type: ignore sometimes ending up on a line of its own in compiled code.

Fixed MyPy errors that MyPy wrapped right after error: (with long file paths) being merged into the previous message, so that they weren't mapped back to the Coconut source line or counted as errors.

Fixed the lines that a dotted function definition (e.g. def Cls.method(...)) adds after the function getting the next line's number, which put errors on the wrong line and gave them the next line's comments (including # type: ignore).

Fixed multiline passthroughs (\( ... )) causing an IndentationError with --minify or in code that isn't indented by 4 spaces, and type errors in Coconut's generated code for starred data fields and tail-recursive functions under MyPy's --strict (--check-untyped-defs).

Fixed Pyright reporting Variable not allowed in type expression for annotations using modules imported with import typing (and other imports Coconut replaces at runtime), and Expected[...] raising a TypeError below Python 3.9 in annotations evaluated at runtime.

Coconut's test suite now compiles the newest Python's own tests of its syntax as Coconut (running them on the newest Python, and checking that they can be backported on older versions), which found and fixed a number of cases where valid Python failed to compile or compiled incorrectly: empty f-strings (f''), uppercase f-string prefixes (F'', Rf''), backslash continuations inside single-quoted strings, defaults for positional-only parameters (def f(a=1, /)), star arguments after keyword arguments (f(a=1, *args)), except *E with a space, unparenthesized assignment expressions as match subjects (match x := y, :), yield expressions, format specs starting with = (f"{x:=10}"), replacement fields starting with {, and the text shown by = when the expression contains comments, quotes, braces, or backslashes in f-strings, single-constraint type parameters ([T: (int,)], which also now work below 3.12, where TypeVar doesn't allow a single constraint), unstarred TypeVarTuple defaults ([*Ts = int]), Python 3.15's unary + in complex literal patterns (case 0.25 - +1.75j:), assignments to attributes and items of parenthesized expressions and literals ((x).y = 1), empty unpacking targets ([] = it), grouped del targets (del a, (b, c)), parenthesized annotation targets ((x): int, which doesn't make x local), \N{...} escapes in f-strings, type statements for names declared global (below 3.12), and an explicit from __future__ import annotations being dropped with --no-wrap or --target 3.14. Syntax from the newest Python that can't be backported to the given --target (asynchronous comprehensions nested in non-asynchronous comprehensions below 3.11, and reassigning type parameters below 3.12) is now a target error rather than invalid output or a syntax error. Type parameters referenced in string annotations (e.g. -> "Box[U]") now also work on targets below 3.12, and in pattern-matching functions, a *args after positional-only parameters no longer also gets the positional-only arguments.

Thanks

Thanks to @ad4mf06 (#900, #901, #902), @esvanha (#903), @anki-code (#905), and @Bortlesboat (#910), whose pull requests were incorporated into this release!