Sometimes you want to fetch data from a deeply nested data structure. Dotted notation
helps you do that.
Installation
pip install dotted-notation
Since this package includes the dq command-line tool, several data formats are supported:
Format
-i/-o
Status
JSON
json
included
JSONL
jsonl
included
Python
py
included
Python lines
pyl
included
CSV
csv
included
YAML
yaml
optional
TOML
toml
optional
To install optional format support:
pip install dotted-notation[formats]
Or pick only what you need:
pip install dotted-notation[yaml,toml]
Or everything, formats and copium (below) alike:
pip install dotted-notation[all]
For faster mutable=False updates and removes, install the
copium extra, a C implementation of
copy.deepcopy (CPython 3.10+). Dotted uses it when present and falls back to
copy.deepcopy otherwise:
pip install dotted-notation[copium]
Caveat (copium 0.1.0): after copium copies a large object, its copies of
small objects in the same process become slower than copy.deepcopy and stay
that way. Copying whole documents is 3-9x faster, but a long-running process
that mixes one large copy with many small ones can come out slower overall.
Tracked upstream in copium#54.
Like JavaScript's optional chaining operator (?.), dotted safely handles missing paths.
If any part of the path doesn't exist, get returns None (or a specified default)
instead of raising an exception:
>>> import dotted
>>> d = {'a': {'b': 1}}
>>> dotted.get(d, 'a.b.c.d.e') is None # path doesn't exist
True
>>> dotted.get(d, 'a.b.c.d.e', 'default') # with default
'default'
>>> dotted.get(d, 'x.y.z', 42) # missing from the start
42
This makes dotted ideal for safely navigating deeply nested or uncertain data structures
without defensive coding or try/except blocks.
Why Dotted?
Several Python libraries handle nested data access. Here's how dotted compares:
Pattern matching with wildcards (*) and regex (/pattern/)
Both read and write operations on nested structures
Transforms to coerce types inline (path|int, path|str:fmt)
Recursive patterns with *key (dict keys), *([*]) (slots), *(@*) (attrs), and *(expr) (mixed), with depth slicing
Path grouping (a,b).c / prefix(.a,.b) for multi-access
Cut (#) in disjunction—first matching branch wins; e.g. (a#, b) or emails[(*&email="x"#, +)] for "update if exists, else append"
Soft cut (##) in disjunction—suppress later branches only for overlapping paths; e.g. (*(*#, [*]:!(str, bytes)):-2(.*, [])##, (*, [])) for "recurse into containers, fall back for the rest"
NOP (~) to match without updating—e.g. (name.~first#, name.first) for conditional updates
String/bytes glob patterns—match by prefix, suffix, or substring: *="user_"..., *=b"header"...b"footer"
Value groups—disjunction over filter values: *=(1, 2, 3), [*&status=("active", "pending")]
Strict mode—enforce type separation: [0] only matches lists, .key only matches dicts
Streaming reads—iget, ipluck and iexpand read through generators and other one-shot iterators, one match at a time: rows[*&active=True].id over a cursor
Breaking Changes
v0.57.0
pluck and expand no longer dedup by default.unique=False
replaces duplicates=False on pluck, expand and their i and _multi
forms: a path a pattern reaches twice is yielded twice.
Pass unique=True for each path once; duplicates= is gone and raises
TypeError. See Pluck.
iget, ipluck and iexpand are streaming reads. A pattern
iterates what it reads, so they read through a one-shot iterator, which
yielded nothing before. See Streaming reads.
walk and walk_multi are removed. They were other names for
ipluck and pluck_multi; call ipluck and ipluck_multi. See
Ipluck.
v0.56.0
sparkize's build takes the DataFrame's schema. A path reads
each node by its type, so r.build(fragment, schema=df.schema);
without it, build raises. See Spark Translation.
sqlize and sparkize read as dotted does. A regex fullmatches,
!= holds for a null, a string never equals a number, and a slice
filter is one list: queries built on the old reads may match other
rows.
v0.55.0
walk dedups. It is now ipluck, and walk_multi is pluck_multi,
so a path a pattern reaches twice is yielded once, as pluck does:
walk({'a': 1, 'b': 2}, '(a,*)') yields ('a', 1), ('b', 2). Pass
duplicates=True for the old behavior. See Ipluck.
v0.53.0
! negates the whole path.!(metadata.*) yields everything
outside metadata.*, and !a.b is the complement of a.b; it no
longer negates a and continues into b, which is written (!a).b.
A guard or filter after it applies to what it yields: !a.b=5 is
(!a.b)=5. See Negation.
A ? group picks first, then continues.(a,b)?.c is .c of the
first of a, b; (a,b)?=5 is that first match if it equals 5, as
*?=5 is. They were the first of a.c, b.c and of a=5, b=5;
write those (a.c,b.c)? and ((a,b)=5)?. See First match.
A group with one branch and no pattern is not a pattern.get(d, '(a.b)') returns the value, as get(d, 'a.b') does, where it returned
a 1-tuple. Write (a.b,) for the tuple.
~ on a group covers only the group.~(a.b) is ~a.~b:
update through ~(a.b).c writes .c, where it wrote nothing, and
remove through ~(a.b) leaves a.b. See
The NOP ~ operator.
v0.50.0
Nothing is read through [+] or [+?]. They are the slot past the
end, so get(d, 'a[+]') is the default, not the last item; use a[-1].
has is False, remove, pluck and expand through them find
nothing, a guard on them never passes, and setdefault always appends
([+?] only when the value is absent). See
The append + operator.
An append branch in a group always applies in an update.(a, b[+]) appends to b whether or not it is empty; it used to append
only when b already had items. With a cut, [(*&k=1#, +)], the append
is still the fallback.
v0.49.0
; is now a reserved character: it packs a group, (a,b;) (see
Packing). If you have keys containing a literal ;, quote
them: "a;b".
v0.47.0
! binds tighter than guards, filters and transforms.!a=5 is now
(!a)=5, the values other than a's that equal 5; the old meaning,
everything but an a equal to 5, is written !(a=5). Likewise !a&k=v
filters what !a yields and !a|int transforms it. See
Precedence.
A guard, filter or transform after a group distributes to every branch.(a,b)=5 is (a=5,b=5), (first&last)>5 is (first>5&last>5),
(a,b)|int is (a|int,b|int), and assemble writes the distributed form.
These used to fail to parse.
a,b|int transforms only b. A transform binds to the expression on
its left before , and &; (a,b)|int transforms both.
:type tests the value a path yields, not the node it is applied to.x:int on {'x': 3} is 3; it was None. Restrict a container one
segment earlier: a.b:dict → a:dict.b, and
*[*]:!(str, bytes) → *:!(str, bytes)[*]. **:!(str, bytes) and
*(*, [*]):!(str, bytes) now drop string values themselves, not only
their decomposition.
!a.b continues into b. It yielded the complement of a and
ignored .b; it now yields .b of every key other than a, as
match always read it.
Ops own their transforms.Dotted.transforms is read-only and
reflects the trailing op; parse('a.b|int') reprs as
Dotted([a, b|int]). A guard's or filter's match-only transforms,
a|int=5, are guard_transforms, not transforms.
v0.44.0
Parameter renamed from key to path across the public API to align with
the terminology used throughout the docs (a path is the whole dotted
expression; a path segment or field is one component). Positional calls
are unaffected; keyword callers must update:
get(obj, key=...) → get(obj, path=...)
update(obj, key=...), update_if(obj, key=...) → update(obj, path=...), etc.
remove(obj, key=...), remove_if(obj, key=...) → remove(obj, path=...), etc.
has, setdefault, build, mutable, match — same rename
is_pattern(key=...), is_template(key=...), is_reference(key=...),
is_indeterminate(key=...), is_simple(key=...), is_inverted(key=...) —
all take path= now.
remove_if default pred signature: lambda key: key is not None →
lambda path: path is not None
is_mutable added as the preferred name for mutable — parallels the
other is_* predicates. mutable remains as an alias.
expand_multi, pluck_multi, assemble_multi now return a generator
instead of a tuple, aligning with the other read-side _multi APIs
(get_multi, match_multi, walk_multi, translate_multi,
setdefault_multi). Callers that consumed the return as a tuple (indexing
r[0], len(r), equality r == (...)) must now materialize:
tuple(pluck_multi(...)). The singular forms (expand, pluck, assemble)
are unchanged.
v0.43.4
is_pattern no longer returns True for substitutions. Subst previously
inherited from Pattern in the class hierarchy, so any path containing a
substitution in an access position (e.g. a.$(x), a.$0) reported as a
pattern. Substitutions resolve to a single key, not a set — that was a
misclassification. Use is_template(path) to check "contains a
substitution."
v0.40.0
unpack() now returns a dict: Previously returned a tuple of
(path, value) pairs. Now returns {path: value, ...} directly.
Replace dict(dotted.unpack(d)) with dotted.unpack(d).
v0.39.0
normalize() removed: Use quote() instead, which is now idempotent.
match module renamed to matchers: Update imports from
from dotted.match import ... to from dotted.matchers import ....
$-prefixed keys now canonicalize to single-quoted form: quote('$0')
returns '$0' instead of \$0. The \$ form is still accepted as input.
v0.38.0
< and > are now reserved characters: These are used for
comparison operators in filters and value guards
(<, >, <=, >=). If you have keys containing literal < or >,
quote them: "my<key>".
v0.35.0
Recursive traversal now walks into str and bytes: Previously, recursive
patterns like *(*#, [*]) hardcoded a skip for strings and bytes. This is now
controlled by type restrictions instead. If you use custom
recursive accessor groups with [*], add :!(str, bytes) to prevent character
decomposition: *(*#, [*]:!(str, bytes)). The default ** (key-only recursion)
is unaffected — it never entered strings because strings have no dict keys.
v0.31.0
{ and } are now reserved characters: Curly braces are used for container
filter values (dict and set patterns). If you have keys containing literal { or },
quote them: "my{key}".
v0.30.0
update_if pred now gates on incoming value, not current value: Previously,
update_if(obj, key, val) checked pred(current_value_at_path). Now it checks
pred(val). Default pred changed from lambda val: val is None to
lambda val: val is not None — meaning None values are skipped.
Use path expressions with NOP (~) and cut (#) for conditional updates based on
existing values.
remove_if pred now gates on key, not current value: Previously,
remove_if(obj, key) checked pred(current_value_at_path). Now it checks
pred(key). Default pred is lambda key: key is not None — meaning None keys
are skipped.
update_if_multi / remove_if_multi: Same pred changes as their single
counterparts.
v0.28.0
[*=value] on primitive lists no longer works — use [*]=value (value guard) instead.
[*=value] is a SliceFilter that tests keys of dict-like items; primitives have no keys,
so it now correctly returns [].
[!*=value] on primitive lists no longer works — use [*]!=value instead.
*&*=value no longer matches primitives — use *=value (value guard) instead.
Existing [*=value] on dicts/objects is unchanged.
Existing & filter behavior on dict-like nodes is unchanged.
v0.13.0
Filter conjunction operator changed from . to &: The conjunction operator for
chaining multiple filters has changed. Previously, *.id=1.name="alice" was used for
conjunctive (AND) filtering. Now use *&id=1&name="alice". This change enables support
for dotted paths within filter keys (e.g., items[user.id=1] to filter on nested fields).
API
Probably the easiest thing to do is pydoc the api layer.
$ pydoc dotted
Parsed dotted paths are LRU-cached (after the first parse of a given path string), so repeated use of the same path string is cheap.
Get
Get the value at a dotted path. See the Paths, Patterns, and Operators sections below for the full notation.
A path read many times can be made into a getter once: a callable
obj -> value that returns what get would, with the parse, the resolver's
hooks and the fast-path decision settled when it is made, against the
resolver in force then. It takes get's arguments, the object aside.
iget is get as a generator. A pattern yields each match as it is found,
and a concrete path yields its one value, or the default when it is missing,
so the caller never has to ask which kind of path it holds.
iget, ipluck and iexpand, and their _multi forms, are streaming
reads. Where get looks items up (__getitem__), a streaming read's
pattern iterates what it reads and yields one match at a time. So it reads
through a one-shot iterator too (a generator, a map, a cursor), drawing
from it only as far as it is asked:
A slice of an iterator is an islice of it, one value, as a slice of a list
is a list; [*] then reads it, no further than the slice's bound. A slice
filter of one is likewise a generator of the items that pass.
A recursive pattern enters an iterator as it enters a list, and reads it to
its end before it yields. The matches are the same; the read is not lazy
there.
A set is not read: it has no order, so its items have no positions to be
their paths.
>>> list(dotted.iget({'s': {1, 2}}, 's[*]'))
[]
A dict-like is read through its own items(), in one pass, when it has
one, else through each key it iterates; a sequence or iterator through its
__iter__; anything else by index, as get reads it. For a lazy mapping
of your own, a lazy items() is the interface to implement.
iget_multi reads several paths as one flat stream of values, and
ipluck_multi and iexpand_multi are pluck_multi and expand_multi as
streaming reads. The paths of one call read the same object, so an iterator
one path has read is empty for the next, as it is for the next call:
Use mutable=False to prevent mutation of the original object:
>>> import dotted
>>> data = {'a': 1, 'b': 2}
>>> result = dotted.update(data, 'a', 99, mutable=False)
>>> data
{'a': 1, 'b': 2}
>>> result
{'a': 99, 'b': 2}
This works for remove as well:
>>> data = {'a': 1, 'b': 2}
>>> result = dotted.remove(data, 'a', mutable=False)
>>> data
{'a': 1, 'b': 2}
>>> result
{'b': 2}
When mutable=False is specified and the root object is mutable, copy.deepcopy()
is called first. This ensures no mutation occurs even when updating through nested
immutable containers (e.g., a tuple inside a dict).
Update if
update_if updates only when pred(val) is true. Default pred is
lambda val: val is not None, so None values are skipped. Use pred=None
for unconditional update (same as update):
Similar to update, all patterns that match will be removed. If you provide a value as
well, only the matched patterns that also match the value will be removed.
Remove if
remove_if removes only when pred(key) is true. Default pred is
lambda key: key is not None, so None keys are skipped. Use pred=None
for unconditional remove (same as remove):
In the above example, hello matched to hello and * matched to there.bye (partial
matching is enabled by default).
A capture is the path's segment as the path writes it: its accessor, filters, value
guard and transforms come with it. A filter, guard or transform on the path only
narrows a segment, so an undecorated pattern still matches it:
Op groups match like regex alternation, and parentheses act as a capture
group: a group captures the segments its matching branch consumed as a
single group, and counts as one pattern position:
A slice filter reads the list narrowed to the items that pass it, so the
slice of the whole list covers it, as * covers a&x=1. Which items pass
depends on the data, so no part of the list covers it, and neither does
[*], which steps into each item rather than reading the list:
A segment matches however it is read: [*] matches the key table, and * the slot
[0]. Pass strict=True to keep keys, slots and attrs apart, as
strict mode does for get:
Substitute placeholders in a template path with bound values. Template paths
are validated at parse time — structural errors are caught immediately, not at runtime.
Positional ($N) placeholders resolve against a list or tuple:
See Substitution for is_template, escaping, and more.
Translate
Translate a path using a pattern map (first exact match wins). Each key in the map
is a match pattern; the value is a template with $N placeholders that refer to
captured pattern segments only (wildcards, regex — not literals):
>>> from dotted.api import translate
>>> translate('a.hello.b', {'a.*.b': '$0.there'})
'hello.there'
Here * captures hello as $0. Literal segments a and b are not numbered.
With multiple wildcards, $N indices follow wildcard order:
A path the pattern reaches more than once is given each time; pass
unique=True for each path once. iexpand is expand as a generator, and
a streaming read.
Test whether two dotted paths overlap—i.e. one is a prefix of the other, or they
are identical. Used internally by soft cut (##) to
decide which later-branch results to suppress.
Check if update(obj, key, val) would mutate obj in place. Returns False for
empty paths (root replacement) or when the object or any container in the path
is immutable.
This is useful when you need to know whether to use the return value:
>>> data = {'a': 1}
>>> if dotted.mutable(data, 'a'):
... _ = dotted.update(data, 'a', 2) # mutates in place
... else:
... data = dotted.update(data, 'a', 2) # use return value
Setdefault
Set a value only if the path doesn't already exist. Creates nested structures as needed.
>>> import dotted
>>> d = {'a': 1}
>>> dotted.setdefault(d, 'a', 999) # path exists, no change; returns value
1
>>> dotted.setdefault(d, 'b', 2) # path missing, sets value; returns it
2
>>> dotted.setdefault({}, 'a.b.c', 7) # creates nested structure; returns value
7
Pluck
Extract (path, value) pairs from an object matching a pattern.
ipluck is pluck as a generator — it yields (path, value) pairs without
materializing the full result, for a concrete path as for a pattern. Useful
for streaming or large structures: it is a streaming read.
>>> import dotted
>>> d = {'a': {'b': 1, 'c': 2}, 'x': 3}
>>> list(dotted.ipluck(d, 'a.*'))
[('a.b', 1), ('a.c', 2)]
>>> list(dotted.ipluck(d, 'a.b'))
[('a.b', 1)]
>>> for path, val in dotted.ipluck(d, '*'):
... print(f'{path} = {val}')
a = {'b': 1, 'c': 2}
x = 3
Unpack
Recursively unpack a nested structure into a flat dict mapping dotted paths to
leaf values — its dotted normal form. The result can be replayed with pack to
reconstruct the original object.
>>> class Pt:
... def __init__(self, x, y):
... self.x = x
... self.y = y
>>> dotted.unpack({'point': Pt(3, 4)}, attrs=[dotted.Attrs.standard])
{'point@x': 3, 'point@y': 4}
Pass both to include all attributes: attrs=[Attrs.standard, Attrs.special].
Pass project= to keep only the leaf paths selected by one or more dotted
patterns. Selection is directional — a leaf survives if it matches a
projection pattern — so projecting a.b never drags in a shallower scalar leaf
a:
Matching uses match's partial=True by default, so a trailing segment is
greedy (a.* also keeps a.b.c). Set partial=False for exact-depth matching,
where a.*, a.*.*, and a.** are all distinct:
Override partial per field with a (pattern, partial) tuple — bare patterns
inherit the global setting. This matters for mid-pattern matches that **
cannot express (e.g. a.*.c keeping both a.x.c and a.x.c.d):
Quote a key for use in a dotted path. Idempotent: quote(quote(x)) == quote(x).
Wraps in single quotes if the key contains reserved characters or whitespace.
>>> d = {'7': 'seven', 'a.b': 'dotted', 'hello': 'world'}
>>> flat = dotted.unpack(d)
>>> dotted.pack(flat) == d
True
AUTO
All write operations (update, update_multi, build, setdefault, etc.) accept
AUTO as the base object. Instead of passing {} or [], let dotted infer
the root container type from the first key — dict keys produce {}, slot keys
produce [].
Most operations have *_multi variants for batch processing:
Note: The read-side _multi APIs — get_multi, iget_multi, match_multi,
expand_multi, iexpand_multi, pluck_multi, ipluck_multi,
translate_multi, assemble_multi, and
setdefault_multi — return a generator, not a list or tuple. Consume with
list() / tuple() / for. The write-side _multi APIs (update_multi,
remove_multi, build_multi, apply_multi, etc.) return the mutated object.
The generator shape keeps input and output in the same style when you pass an
iterator or generator of paths — lazy in, lazy out — and lets callers early-exit
before a full traversal completes.
Available multi operations: get_multi, update_multi, update_if_multi, remove_multi,
remove_if_multi, setdefault_multi, match_multi, expand_multi, apply_multi,
build_multi, pluck_multi, assemble_multi, and the streaming iget_multi,
iexpand_multi, ipluck_multi.
Strict Mode
By default, dotted is flexible about accessor types: bracket notation [0] falls through
to dict keys on dicts, and dot notation .0 coerces numeric keys to list indices on lists.
This makes casual access forgiving, but sometimes you want type-separated access where
slots only match lists and keys only match dicts.
Pass strict=True to enforce this separation:
>>> import dotted
>>> d = {0: 'by-key', 'a': [10, 20]}
>>> # Non-strict (default): [0] falls through to dict key 0
>>> dotted.get(d, '[0]')
'by-key'
>>> # Strict: [0] only matches lists, returns None on dict
>>> dotted.get(d, '[0]', strict=True) is None
True
>>> # Non-strict: .0 coerces to list index
>>> dotted.get(d, 'a.0')
10
>>> # Strict: .0 only matches dict keys, returns None on list
>>> dotted.get(d, 'a.0', strict=True) is None
True
Strict mode applies to all operations — get, update, remove, has, expand,
pluck, match, and their _multi variants. Mismatches silently return empty results, consistent
with dotted's safe traversal model:
Use strict mode when your data mixes integer dict keys and list indices, and you need
to distinguish between them.
match and match_multi take strict too. By default a segment matches however it is
read, so [*] matches a key and * a slot. Strict keeps them apart, as get does: a key
pattern matches only a key, a slot pattern only a slot, an attr pattern only an attr.
** reads keys, so it consumes only key segments; *(.*,[*]) reads both:
Dotted notation shares similarities with python. A dot. field expects to see a
dictionary-like object (using keys and __getitem__ internally). A bracket[]
field is biased towards sequences (like lists or strs) but can also act on dicts. A
attr@ field uses getattr/setattr/delattr.
Key fields
A key field is expressed as a or part of a dotted expression, such as a.b. The
grammar parser is permissive for what can be in a key field. Pretty much any non-reserved
char will match. Key fields work best with objects that have a keys method
(dictionaries and dictionary-like objects). For concrete access like .name, objects
with __getitem__ and __contains__ but no keys method are also supported via direct
lookup (though pattern access like .* requires keys).
If the key field starts with a space or -, you should either quote it OR you may use
a \ as the first char.
Bracketed fields
You may also use bracket notation, such as a[0] which does a __getitem__ at key 0.
The parser prefers numeric types over string types (if you wish to look up a non-numeric
field using brackets be sure to quote it). Bracketed fields will work with pretty much
any object that can be looked up via __getitem__.
An attr field is expressed by prefixing with @. This will fetch data at that attribute.
You may wonder why have this when you can just as easily use standard python to access.
Two important reasons: nested expressions and patterns.
Concrete access (@name) works on any object — dotted tries enumeration first,
then falls back to getattr directly. This means objects that provide attributes
via __getattr__ (such as Stripe API objects and other dynamic-attribute wrappers)
work out of the box.
Pattern access (@*, @/regex/) requires enumerable attributes. Dotted discovers
attribute names from __dict__ (standard instance attributes), __slots__ (slot-based
classes), and _fields (namedtuples, which store data in the tuple itself and don't
expose field names through either __dict__ or __slots__):
>>> class Point:
... __slots__ = ('x', 'y')
... def __init__(self, x, y):
... self.x = x
... self.y = y
>>> dotted.get(Point(3, 4), '@*')
(3, 4)
Objects that rely solely on __getattr__ without exposing their keys through any of
these mechanisms will support concrete attr access but not pattern matching.
Slicing
Dotted slicing works like python slicing and all that entails.
Sometimes you need to quote a field which you can do by just putting the field in quotes.
>>> import dotted
>>> dotted.get({'has . in it': 7}, '"has . in it"')
7
The numericize # operator
Non-integer numeric fields may be interpreted incorrectly if they have decimal point. To
solve, use the numerize operator # at the front of a quoted field, such as #'123.45'.
This will coerce to a numeric type (e.g. float).
Container literals express list, dict, set, tuple, and frozenset values inline. They
appear in two contexts: as filter values / value guards
(with pattern support) and as transform arguments
(concrete values only).
Without a type prefix, brackets match loosely: [] matches any
list or tuple, {v, v} matches any set or frozenset, {} matches dict (following
Python convention where {} is a dict literal, not a set).
In filter context, containers support patterns (*, ..., /regex/) inside — see
Container filter values. In transform argument context,
only concrete scalar values are allowed.
Bytes literals
Prefix a quoted string with b to create a bytes literal: b"hello" or b'hello'.
Bytes literals produce bytes values and only match bytes — never str:
Note that b"hello" does not match the string 'hello' — types must match exactly.
Patterns
You may use dotted for pattern matching. You can match to wildcards or regular
expressions. You'll note that patterns always return a tuple of matches.
Dotted will return all values that match the pattern(s). Patterns can only discover
what is advertised — they work by enumerating keys or attributes, so the object must
expose them via keys() (dicts), __dict__, __slots__, or _fields (namedtuples).
Wildcards
The wildcard pattern is *. It will match anything.
Regular expressions
The regex pattern is enclosed in slashes: /regex/. Note that if the field is a non-str,
the regex pattern will internally match to its str representation.
The match-first operator
You can also postfix any pattern with a ?. This will return only
the first match.
A pattern yields only what it finds, so a match the rest of the path finds
nothing under drops out. Postfix any pattern with a + to follow the
cadence of the input instead: each match yields at least one result, the
default where the rest of the path finds nothing.
A guard or filter on the pattern itself decides which items are matches;
one after it decides what a match yields, and a match that yields nothing,
missing or rejected, yields the default:
*+, /regex/+ and the recursive **+ and *key+ align the same way.
Writes already follow the input, so update and remove treat a +
pattern as the plain one. sqlize and sparkize translate it with NULL
as the fill.
Slicing vs Patterns
Slicing a sequence produces a sequence and a filter on a sequence is a special
type of slice operation. Whereas, patterns iterate through items:
Chaining after a slice accesses the result itself, not the items within it:
>>> dotted.get(data, '[1:3].name') is None # accessing .name on the list
True
>>> dotted.get(data, '[name="alice"].name') is None # also accessing .name on the list
True
>>> dotted.get(data, '[].name') is None # .name on a raw list
True
To chain through the items, use a pattern instead:
All $-prefixed syntax falls into two categories: substitutions (resolved
at replace time) and references, inline expressions evaluated during
traversal.
Syntax
Type
Resolved against
$0, $1
Positional substitution
replace() bindings (list/tuple)
$(name)
Named substitution
replace() bindings (dict)
$(0), $(name)
Substitution with parens
replace() bindings via __getitem__
$(name|int)
Substitution with transform
replace() bindings, then transform
$$(path)
Reference
Root object during traversal
$$(^path)
Relative reference
Current node during traversal
$$(^^path)
Relative reference
Parent node during traversal
$$(^path) in a transform, guard or filter
Relative reference
The value under test; ^^ the node holding it
Substitution
Substitution references turn a path into a template. There are two forms:
Positional ($0, $1, …) — resolved against a list or tuple
Named ($(name), $(key), …) — resolved against a dict
The parenthesized form $(N) adapts to the binding type — it uses __getitem__,
so $(0) works as a positional index against a list or as a numeric key against
a dict:
>>> dotted.replace('$(0)', {0: 'zero'})
'zero'
Use is_template to test whether a path contains substitution references:
Substitutions support per-substitution transforms using the | separator inside
the parenthesized form. The transform is applied to the resolved value before it
is spliced into the path:
All traversal APIs — get, update, remove, has, ipluck, expand, pluck,
apply, build, mutable, setdefault, and their multi variants — accept a
bindings= keyword argument to resolve template paths inline:
When partial=True (the default for parse()), unresolved substitutions are
allowed through. When partial=False (the default for traversal APIs),
unresolved templates raise TypeError.
compile() is an alias for parse(). Every API that takes a path also takes
the parsed result, so a path used many times can be compiled once:
A reference, $$(expr), is an inline evaluation expression. The dotted
expression inside is evaluated during traversal, as get would evaluate it
against the root, and its value stands where the reference is written. The
expression is a full dotted path, so it may carry patterns and transforms:
$$(config.offset|mul:10) is the value of config.offset, times ten.
Where the reference stands decides what its value does. In a transform
argument, a guard value or a filter value it is the value itself (see
References in transforms and guards).
In an access position, as a key or slot, it is the key to look up:
Here config.*.field resolves to ('name', 'age'), so the reference
looks up both data['name'] and data['age'].
The resolved value is used as a literal key — it is not re-parsed as a
dotted path. If the reference path is not found, the reference matches nothing
(same as a missing key):
A reference can also stand in for a transform argument, a guard value or a
filter value. It resolves when the transform or comparison runs, against the
value under test: $$(path) is the root as always, $$(^path) is the value
itself, $$(^^path) the node holding it, $$(^^^path) that node's parent,
and so on:
So does a reference inside a container value. One whose path is a pattern
branches the container, once per value; pack it, (…;), to compare with the
tuple instead:
What a reference means at run time is decided by a resolver. The default
is dotted's own reading above. A host with its own namespaces subclasses
dotted.ReferenceResolver, passes an instance as resolver= to get,
update, remove and the rest, or installs one for the process with
dotted.set_resolver(r); set_resolver() with no argument restores the
default.
resolve(ref, settings, node, parents) is called for every $$(...) the
traversal meets, in an access position, a transform argument, a guard or a
filter value. ref.is_reference() is true for those, ref.inner_path is the
text inside, and super().resolve(...) is dotted's reading, so a host can
claim some references and leave the rest:
A resolver with literals = True is also offered every plain token in
those positions, so a host sigil such as $sel can be a variable. Set it on
the class, or per instance with literals= on the constructor. Return
ref.value to leave a token the literal it is; a key the resolver answers
is not offered again:
literals may instead name the positions it wants, as a list or tuple of
'segments' (key, slot and attr segments), 'transforms' (transform
arguments), 'guards' (guard values) and 'filters' (filter values). A host
whose variables only ever stand as arguments leaves 'segments' out, so the
keys of a path cost no call:
An unknown name is a ValueError, on the class or the constructor.
A host variable may span several segments, $amount.value, which dotted has
parsed as two. The path-level hook fold(segments) is called once with a
path's segment strings, ('$amount', 'value'), and returns the runs it
resolves as (start, stop, value) triples; each run becomes one segment
whose key is the value, keeping the last segment's guard, filter and
transforms. An inner segment of a run may carry none.
>>> class Folding(Sigils):
... def fold(self, segments):
... name = '.'.join(str(s) for s in segments)
... if name in self.names:
... return [(0, len(segments), self.names[name])]
... return []
>>> r = Folding({'$amount.value': 'amt'})
>>> dotted.get({'amt': 10}, '$amount.value|sub:3', resolver=r)
7
A path handed in already parsed goes through fold() again, so a hook must
be content to see its own output. Dotted.segments() gives any parsed
path's segment values, and a slice of a parsed path, ops[1:], is a path.
A host's own names may stand where dotted has no reading for a bare token:
a slot, merged[k], a slice bound, items[:n], a filter value,
[*&cur=want], a guard value, a=k, or a transform argument,
|sub:taken. The parse-time hook lex(text, position) is offered each such
token as written, a dotted name whole, with its position, one of 'slots',
'slices', 'filters', 'guards' or 'transforms'. It answers with dotted
text to read in the token's place, None to leave the ParseError (a
transform argument stays the plain string it was), or raises to fail the
parse at the token. The answer must be one token dotted reads there, and is
not offered again.
A token dotted reads, m[$x] or |sub:$taken, is never offered to lex();
a host that means something else by one remaps it at run time, through
literals. parse takes resolver= too, and a path is cached per resolver
that lexes.
Escaping
If your data has keys that start with $, prefix with backslash to suppress
substitution. This works for both positional and named forms:
Quoting also works — a quoted string is always literal:
>>> dotted.get({'$0': 'hello'}, "'$0'")
'hello'
quote and unpack emit single-quoted forms for $-prefixed keys:
>>> dotted.quote('$0')
"'$0'"
To use a literal $$ as a key, escape with backslash (\$$) or quote it
('$$(…)').
A $ before a word is not a substitution at all: $str is the plain string
$str, in a segment, a guard value or a transform argument alike, just as
^str is. Only $0, $(name) and $$(path) have meaning:
In a guard value or transform argument the token may carry dots,
|min:$amount.value or =^lots.taken, and is still one string; a
custom resolver reads it whole. In a segment the dot
separates segments, so there $amount.value is two:
A type restriction keeps a value only if it is of a given type. Append
:type to a path: x:int is x, when its value is an int, so it reads
like a guard, x=5, with a type in place of a value:
A restriction after a parenthesized group applies to what the group yields,
transforms included. A : directly after a transform name is a parameter,
a|int:16, so the parentheses are what make it a type:
Without :!(str, bytes), the [*] slot accessor would decompose 'hello'
into individual characters.
A type restriction can also be applied to an entire group, which distributes it
to every accessor in the group. Here it drops the string 'hello' as well,
since the * accessor yields it too:
The recursive operator * traverses nested data structures by following path
segments that match a pattern at successive levels.
The recursive operator *
*pattern recurses into values whose path segments match the pattern. It follows
chains of matching segments — at each level, if a segment matches, its value is
yielded and the traversal continues into that value:
Recursive pattern matching works across different accessor types:
*<pat> for keys, *([<pat>]) for slots, and *(@<pat>) for attrs.
The accessor determines which children are followed at each level.
*key — recursive dict keys. Since bare * means .* (dict key
access), ** recursively matches all dict keys. Any key pattern works —
*/regex/ recursively matches keys against a regex, *literal follows
only keys named literal:
Use ** with continuation to find a key at any depth:
>>> dotted.get(d, '**.c')
(1,)
Use **? to get only the first match:
>>> dotted.get(d, '**?')
({'b': {'c': 1}},)
*([slot]) — recursive slots. Recurses through lists, dicts, and
anything with __getitem__. Since slots fall through to dict keys, this
also matches dicts. Any slot pattern works — *([*]) matches all slots,
*([/regex/]) matches slots by regex:
*(@attr) — recursive attrs. Recurses through object attributes. Any
attr pattern works — *(@*) matches all attrs, *(@/regex/) matches attrs
by regex:
>>> dotted.get(data, '*(@*)') # doctest: +SKIP
To recurse through multiple accessor types at once, use *(expr) with a
comma-separated list of access ops. Use # (cut) after an accessor to
prevent double-matching — this is needed because [*] falls through to
dict keys:
Control which depths are visited using slice notation: **:start, **:start:stop,
or **:::step. Note the leading : — depth slicing looks a little different from
regular Python slicing since it follows the ** operator. Depth 0 is the values of
the first-level path segments.
Parentheses group operations that branch from a common point. Each branch
is a full operation chain—keys, slots, attrs, and further groups can all
appear inside. Branches are combined using , (disjunction), &
(conjunction), and ! (negation).
>>> import dotted
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> dotted.get(d, '(a,b)') # , — get a and b
(1, 2)
>>> dotted.get(d, '(a&b)') # & — get a and b only if both exist
(1, 2)
>>> dotted.get(d, '(!a)') # ! — get everything except a
(2, 3)
The three access ops—. (key), @ (attr), [] (slot)—are what
actually look up a child value. Modifiers like ! (negation) and ~
(nop) wrap or filter but don't access anything themselves.
At top level, bare keys infer ., so (a,b) is equivalent to (.a,.b):
>>> dotted.get(d, 'a,b') # same as (a,b) and (.a,.b)
(1, 2)
>>> dotted.get(d, '!a') # same as (!a) and (!.a)
(2, 3)
Parentheses are needed to continue after the group ((a,b).c) or to
nest groups inside paths. A group with one branch and no pattern in it is
not a pattern, (a.b) is a.b; write a trailing comma, (a.b,), for one
that is (see Why do I get a tuple for my get?).
Mid-path groups
Mid-path groups—groups that follow another operation—come in two forms.
Prefix shorthand — the access op sits outside the parentheses and
distributes to every branch. Branches are bare keys (no access ops
inside):
Shorthand
Equivalent
a.(b,c)
a(.b,.c)
a.(!b)
a(!.b)
@obj@(x,y)
@obj(@x,@y)
items[(0,1)]
items([0],[1])
Explicit — no prefix; every branch specifies its own access op.
Branches can mix different access ops freely:
Example
Meaning
a(.b,.c)
Keys b and c from a
a(.b,@b)
Key b and attr b from a
a(!.secret)
Everything except key secret
a(.x.y,[0].z)
Key path x.y and slot 0 then key z
The rule is simple: if an access op floats down from a prefix, you
can't specify one; otherwise, you must.
Disjunction (OR)
Comma separates branches. Returns all matches that exist. Disjunction doesn't
short-circuit—when updating, all matching branches get the update. Using the
match-first operator (?) is probably what you want when updating.
>>> d = {'a': {'x': 1, 'y': 2}}
>>> dotted.get(d, 'a(.x,.y)')
(1, 2)
>>> dotted.get(d, 'a(.x,.z)') # z missing, x still returned
(1,)
Updates apply to all matching branches. When nothing matches, the first
concrete path (scanning last to first) is created:
Suffix a branch with # so that if it matches, only that branch is used
(get/update/remove); later branches are not tried. Useful for "update if exists,
else append" in lists. Example with slot grouping:
First branch matches items where email="alice@x.com" and updates them (then cut);
if none match, the + branch appends the new dict.
Soft cut (##) in disjunction
Hard cut (#) stops all later branches when the cut branch matches. Soft cut (##)
is more selective: later branches still run, but skip any paths that overlap with
what the soft-cut branch already yielded. Use soft cut when a branch handles some
keys and you want a fallback branch to handle the rest.
Here *(*#, [*]:!(str, bytes)):-2(.*, []) recurses into containers (dicts and lists)
and yields their leaf containers. The ## means: for keys that recursion covered
(like a and x), don't try the (*, []) fallback. But extra was not covered
by the recursive branch, so the fallback picks it up.
Compare with hard cut (#), which would lose extra entirely:
Use ? suffix to return only the first match. When nothing matches, same
fallback as disjunction—first concrete path (last to first):
>>> d = {'a': {'x': 1, 'y': 2}}
>>> dotted.get(d, 'a(.z,.x,.y)?') # first that exists
(1,)
>>> dotted.update({'a': {}}, 'a(.x,.y)?', 99) # nothing matches → creates last (.y)
{'a': {'y': 99}}
What follows the ? acts on the match it picks, as with *?: a path
continues from it, and a guard, filter or transform tests it. To test
first and then pick, put the guard inside: ((a,b)=5)?.
>>> d = {'a': {}, 'b': {'c': 2}}
>>> dotted.get(d, '(a,b)?.c') # picks a, which has no c
()
>>> dotted.get(d, '(a.c,b.c)?') # first that has a c
(2,)
>>> dotted.get({'a': 6, 'b': 5}, '(a,b)?=5') # picks a; 6 is not 5
()
>>> dotted.get({'a': 6, 'b': 5}, '((a,b)=5)?') # first equal to 5
(5,)
Packing
A group yields its matches one by one. A ; just inside either paren
packs them: the group yields one value, the tuple of what it would
have yielded. (a,b;) and (;a,b) are the same pack, and the group
keeps its own kind—(a,b;) packs the branches that match, (a&b;) packs
both or nothing, (a#,b;) packs what the cut lets through, (a,b;)?
packs the first match—and (a.*;) packs a one-branch group. Nothing
matched packs to ():
The tuple is one value, so a packed path is not a pattern: get returns
the value bare, and a transform after the pack applies to the tuple once.
This is how an aggregate over a pattern is written—the pack gathers, an
ordinary transform reduces:
The group runs from the node the pack sits at, so a pack under a pattern
gives one tuple per match—a group-by—while a pack around the whole path
gathers across every level inside it:
A pack is its own path segment: ipluck and expand give it back as
written, (a.*;)|sum. There is nothing under a tuple of matches to write
to, so update and remove through a pack raise ValueError, and a pack
cannot be negated. ; is a reserved character; quote a key that contains
one, "a;b".
(a.*;)[*] yields the matches again: [*] is the inverse of packing.
Negation (NOT)
Use ! prefix to exclude keys matching a pattern:
>>> import dotted
# Exclude a single key at top level
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> dotted.get(d, '!a')
(2, 3)
# Exclude single key — explicit form (access op on every branch)
>>> user = {'email': 'a@x.com', 'name': 'alice', 'password': 'secret'}
>>> sorted(dotted.get({'user': user}, 'user(!.password)'))
['a@x.com', 'alice']
# Same thing — shorthand form (access op distributes from prefix)
>>> sorted(dotted.get({'user': user}, 'user.(!password)'))
['a@x.com', 'alice']
# Works with lists too
>>> dotted.get({'items': [10, 20, 30]}, 'items(![0])')
(20, 30)
Updates and removes apply to all non-matching keys:
! negates a whole path. !P yields the largest subtrees that hold no
match of P: a subtree P runs through is split, one P ends at is
dropped, and one P never reaches is yielded whole:
The complement is of what P actually matches, so !(a#,b) excludes
only a when a is there. To negate one segment and continue past it,
parenthesize the negation: (!a).b.
Note: For De Morgan's law with filter expressions, see the Filters section below.
A guard, filter or transform applies to the whole expression on its left:
an access path (on its last segment), a ! expression (on what it
yields), or a parenthesized group, where it is shorthand for writing it on
every branch: (a,b)=5 is (a=5,b=5) and (a,b)|int is (a|int,b|int),
which is also how assemble writes them. After a ? group it tests the
match ? picks, as *?=5 does: (a,b)?=5 is the first match, if it
equals 5. A packed group yields one value, so (a,b;)|sum
applies to that tuple once.
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> dotted.get(d, '!a&b,c') # ((!a)&b), c
(2, 3, 2, 3)
>>> dotted.get(d, '!a=3') # (!a)=3: the values other than a's equal to 3
(3,)
>>> dotted.get(d, '!(a=3)') # everything but an a equal to 3
(1, 2, 3)
>>> dotted.get({'a': '1', 'b': '2'}, '(a,b)|int')
(1, 2)
>>> dotted.get({'a': '1', 'b': '2'}, 'a,b|int')
('1', 2)
Since access ops bind tightest, !a.b negates the whole path a.b;
(!a).b negates a and continues into b from every other key. ~ is
the exception: it wraps only the next segment, so ~a.b is (~a).b (see
The NOP ~ operator):
All-literal concats collapse at parse time — hello+world becomes the key
helloworld. When any part is dynamic (substitution or reference), a Concat
node is preserved and resolved at traversal or replace time.
Python's native + semantics apply: str + str concatenates, int + int adds,
and mixed types raise TypeError. Per-part transforms allow type coercion:
[+] is the slot past the end, so nothing is ever there to read: a get
through it is the default, and [-1] is the last item. A write to it always
applies, so in a group an append branch is updated along with any branch
that matches:
The NOP operator means "match but don't update." At update and remove time, paths
marked with ~ are matched for traversal but the mutation is skipped at that segment.
NOP applies only to the segment it wraps; child segments are unaffected.
~ is special: unlike !, it does not take the whole path. !a.b is
!(a.b), but ~a.b is (~a).b. On a group, ~ applies to every
segment in it and to nothing after it: ~(a.b) is ~a.~b, so update
and remove leave a.b alone, and ~(a.b).c still writes .c.
Syntax
Meaning
~a.b
NOP at a, then .b
a.~b
NOP at b (dot segment)
~(name.first)
NOP on every segment of the group
[~*] or ~[*]
NOP on slot (canonical: [~stuff])
@~attr or ~@attr
NOP on attr
>>> dotted.update({'a': {'b': 1}}, '~a.b', 2) # NOP at a, update .b
{'a': {'b': 2}}
>>> dotted.update({'a': {'b': 1}}, 'a.~b', 2) # NOP at b, no change
{'a': {'b': 1}}
Combine NOP with cut (#) for "update only if missing" semantics—if the NOP
branch matches, cut commits to it and skips the remaining branches:
>>> # first existed — NOP branch matched and cut
>>> dotted.update({'name': {'first': 'alice'}}, '(name.~first#, name.first)', 'bob')
{'name': {'first': 'alice'}}
>>> # first missing — fell through to update branch
>>> dotted.update({'name': {}}, '(name.~first#, name.first)', 'bob')
{'name': {'first': 'bob'}}
The cut # operator
Think of cut as an OR/disjunction short-circuit. Suffix a branch with #
so that if it matches, only that branch is used and later branches are not tried.
If it doesn't match, evaluation falls through to the next branch.
A cut works in a conjunction too: in (a#&b), once a matches, b
isn't tried.
>>> dotted.get({'a': 1, 'b': 2}, '(a#&b)')
(1,)
Parentheses alone don't make a group, so (a#) is the branch a with
its cut, and the cut is on the group it's in: ((a#)&b) is (a#&b),
and ((a#), b) is (a#, b). A trailing comma, (a#,), keeps the
group and its cut. A soft cut works in a conjunction as it does in a
disjunction: in (a##&*), * skips what overlaps a's matches, and a
branch a soft cut covers whole adds nothing but still matched.
This is especially useful for "update if exists, else create" patterns:
Soft cut is a gentler version of cut. Where # stops all later branches when the
cut branch matches, ## only suppresses later branches for paths that overlap with
what the soft-cut branch yielded. Later branches still run for non-overlapping paths.
>>> import dotted
>>> d = {'a': 1, 'b': 2}
>>> dotted.get(d, '(a##, *)') # a covers 'a'; * still yields 'b'
(1, 2)
>>> dotted.get(d, '(a#, *)') # hard cut: a matches, * never runs
(1,)
This is especially useful with recursive patterns where one branch handles nested
structures and a fallback handles the rest:
The recursive branch covers a and x, so (*, []) skips those. But extra was
not covered, so the fallback picks it up. With hard cut, extra would be lost entirely.
Two paths "overlap" if one is a prefix of the other (e.g. a and a.b.c overlap,
but a.b and a.c do not). You can test this directly:
The # prefix is also used to coerce a quoted field to a numeric type (e.g. float).
This is needed when a non-integer numeric key contains a decimal point that would
otherwise be parsed as a path separator. See Typing & Quoting
for full details.
You may filter by key-value to narrow your result set. All six comparison operators are
supported: =, !=, <, >, <=, >=. Filter keys can be dotted paths and may
include slice notation (e.g. name[:5]="hello", file[-3:]=".py").
You may use with key or bracketed fields. Key-value fields may be disjunctively (OR)
specified via the , delimiter.
A key-value field on key field looks like: keyfield&key1=value1,key2=value2....
This will return all key-value matches on a subordinate dict-like object. For example,
A key-value field on a bracketed field looks like: [key1=value1,key2=value2...].
This will return all items in a list that match key-value filter. For example,
A value guard tests the value at a path and yields it only if it matches.
Use key=value, [slot]=value or @attr=value after accessing a field. All
comparison operators (=, !=, <, >, <=, >=) are supported:
>>> d = {'first': 7, 'last': 3}
>>> dotted.get(d, 'first=7')
7
>>> dotted.get(d, 'first=3') # no match
>>> dotted.get(d, '*=7')
(7,)
>>> dotted.pluck(d, '*=7')
(('first', 7),)
A guard after a parenthesized group is shorthand for a guard on every
branch: (first,last)>5 is (first>5,last>5), and (first&last)>5 is
(first>5&last>5), which yields nothing unless both pass. After ! it
tests what the negation yields, so !first=3 is the non-first values
equal to 3; see Precedence.
Note: [*=value] (equals inside brackets) is a SliceFilter — it tests keys of each
dict-like list item. [*]=value (equals outside brackets) is a value guard — it tests
the item values directly. For primitive lists, use [*]=value.
Note: Python equality applies, so 1 == True and 0 == False:
Both the transform arguments and the value compared with may be
references.
Container filter values
Filter values and value guards can use container patterns to match against lists,
dicts, and sets structurally. Container patterns support wildcards (*), globs (...),
regex, and full nesting.
List patterns
[elements] matches list and tuple values element by element:
>>> import dotted
>>> d = {'items': [1, 2, 3], 'name': 'test', 'pair': (1, 2)}
# Exact match
>>> dotted.get(d, '*=[1, 2, 3]')
([1, 2, 3],)
# Wildcard: * matches exactly one element
>>> dotted.get(d, '*=[1, *, 3]')
([1, 2, 3],)
# Glob: ... matches zero or more elements ([] matches list and tuple)
>>> dotted.get(d, '*=[1, ...]')
([1, 2, 3], (1, 2))
# Empty list matches any empty list or tuple
>>> dotted.get({'a': [], 'b': [1]}, '*=[]')
([],)
Unprefixed [] matches both list and tuple. See Type prefixes
for strict type matching.
Dict patterns
{key: value} matches dict values by key-value pairs:
>>> d = [{'cfg': {'a': 1, 'b': 2}}, {'cfg': {'a': 1}}]
# Exact match — no extra keys allowed
>>> dotted.get(d, '[*&cfg={"a": 1}]')
({'cfg': {'a': 1}},)
# Partial match — ...: * allows extra entries
>>> dotted.get(d, '[*&cfg={"a": 1, ...: *}]')
({'cfg': {'a': 1, 'b': 2}}, {'cfg': {'a': 1}})
# Any dict: {...: *}
>>> dotted.get({'x': {'a': 1}, 'y': 42}, '*={...: *}')
({'a': 1},)
Set patterns
{elements} (comma-separated, no colons) matches set and frozenset values:
>>> d = {'tags': {1, 2, 3}, 'name': 'test'}
# Exact match
>>> dotted.get(d, '*={1, 2, 3}')
({1, 2, 3},)
# Partial match — ... allows extra members
>>> dotted.get(d, '*={1, ...}')
({1, 2, 3},)
Unprefixed {v, v} matches both set and frozenset. See Type prefixes
for strict type matching.
The ... glob element
Inside containers, ... matches zero or more elements. It supports optional regex
patterns and count constraints:
Form
Meaning
...
0 or more, anything
...5
0 to 5
...2:5
2 to 5
...2:
2 or more
.../regex/
0 or more, each matching regex
.../regex/2:5
2 to 5, each matching regex
Examples:
>>> d = {'nums': [1, 2, 3, 4, 5]}
# Glob with count: at most 3 elements
>>> dotted.get(d, '*=[...3]')
()
>>> dotted.get({'nums': [1, 2, 3]}, '*=[...3]')
([1, 2, 3],)
# Glob with regex: all elements must be digits
>>> dotted.get(d, '*=[.../\\d+/]')
([1, 2, 3, 4, 5],)
Container patterns support type prefixes for strict type matching. Without a prefix,
matching is loose (e.g., [] matches both list and tuple). With a prefix, only the
specified type matches.
String globs only match str values — not bytes. For bytes matching, use
bytes glob patterns.
Bytes glob patterns
Bytes globs are the bytes counterpart to string globs. Use b"..." on any
fragment to produce a bytes glob — all other quoted fragments are automatically
encoded to bytes:
Form
Matches
b"hello"...
Bytes starting with b"hello"
...b"world"
Bytes ending with b"world"
b"hello"...b"world"
Starts with b"hello", ends with b"world"
b"hello"..."world"
Same — naked "world" auto-encoded to bytes
"hello"...b"world"
Same — naked "hello" auto-encoded to bytes
b"hello"...5
Starts with b"hello", at most 5 more bytes
If any fragment uses the b prefix, the entire glob becomes a bytes glob and
naked quoted strings are encoded to bytes automatically.
Filter keys can include slice notation so the comparison applies to a slice of the field value (prefix, suffix, or any slice). Use the same slice syntax as in paths: integers and + for start/stop/step.
You can optionally add transforms to the end of dotted notation. These will
be applied on get and update. Transforms are separated by the | operator
and multiple may be chained together. Transforms may be parameterized using
the : operator; a parameter may be a $$(reference), resolved when the
transform runs (see
References in transforms and guards).
coalesce stands in a fallback for None, as SQL's does; with several
fallbacks the first that is not None wins, which matters when a fallback is
a reference that may itself be None:
A transform only runs on a value the path yields, so coalesce does not fill
a missing key; get(..., default=) does that.
Container transform arguments
Transform parameters accept container literals in addition to scalars. These produce
raw Python values — no patterns (*, ..., /regex/) allowed in this context.
View all registered transforms with dotted.registry().
SQL Translation (sqlize)
Under development. The API shape may still change. Postgres-only.
A translation does what dotted does, reading and writing. Where
Postgres can't give what dotted would, it raises: TranslationError
while translating, or a dotted: … error when the query meets a value
it can't read as dotted does.
dotted.sqlize(path, driver='<name>') translates a dotted path into a
driver-specific Resolver instance carrying SQL fragments.
r.build(sql, **bindings) renders a fragment (or any composition of
fragments) into final SQL + a params dict / args list ready for the
driver.
Registered drivers:
driver
placeholders
output shape
notes
asyncpg
$1, $2, ...
list
Native Postgres; server-side PREPARE.
psycopg2
%(name)s / %s
dict
Client-side parameter substitution.
psycopg / psycopg3
%(name)s / %s
dict
psycopg v3 (same class under either name).
Pick the driver you'll actually hand the SQL to; it determines the
placeholder syntax.
The first segment of the dotted path is the SQL column; further
segments read the JSONB inside it. (root='table' makes it a table
search instead.)
>>> import dotted
>>> r = dotted.sqlize("status = 'active'", driver='asyncpg')
>>> r.where
SQLFragment('status = {_p1}')
>>> r.build(r.where)
('status = $1', ['active'])
>>> r = dotted.sqlize("data.user.name", driver='asyncpg') # pure traversal, no predicate
>>> r.build(r.select)
("data #>> '{user,name}'", [])
A guard on a column of a SQL type compares by SQL's own rules for that
type, but != holds for a NULL, as Python's None != x does, and a
regex fullmatches, as dotted's does:
>>> r = dotted.sqlize("age >= 30", driver='asyncpg')
>>> r.build(r.where)
('age >= $1', [30])
>>> r = dotted.sqlize("deleted_at = None", driver='asyncpg')
>>> r.build(r.where)
('deleted_at IS NULL', [])
>>> r = dotted.sqlize("status != 'banned'", driver='asyncpg')
>>> r.build(r.where)
('status IS DISTINCT FROM $1', ['banned'])
>>> r = dotted.sqlize("name = /alice/", driver='asyncpg')
>>> r.build(r.where)
('name ~ $1', ['^(?:alice)$'])
Boolean grouping maps onto AND / OR:
>>> r = dotted.sqlize('(age >= 18 & status = "active")', driver='asyncpg')
>>> r.build(r.where)
('(age >= $1) AND (status = $2)', [18, 'active'])
Comparing as dotted compares
Inside a JSONB column a value is read by its own type (jsonb_typeof)
and compared as dotted compares, which is as Python does:
a number and a boolean compare as numbers (True == 1);
a string compares with a string, in code-point order;
any other pairing is unequal and unordered: the string '30' is not
>= 30, and no cast fails;
!= is ='s negation;
a guard tests a value that's there, so a missing key matches neither
= None nor !=.
Numbers and booleans are written inline; strings are hoisted:
>>> r = dotted.sqlize("data.user.age >= 30", driver='asyncpg')
>>> print(r.build(r.where)[0])
(SELECT (_pat1.n IS NOT NULL AND (CASE jsonb_typeof(_pat1.n) WHEN 'number' THEN (_pat1.n)::numeric >= (30) ELSE FALSE END)) FROM (SELECT data #> '{user,age}' AS n) AS _pat1)
A substitution's type is known only when it's bound, so it goes to the
driver as its JSON text, cast to jsonb, and compares by its type
there. dotted raises on a list or dict bound where it compares; so does
build:
A regex fullmatches str() of the value, as dotted's does: a string, a
number as Python writes it, True / False, None. A guard's
transforms run in SQL as dotted's own: int, float and str,
without arguments; any other raises:
>>> r = dotted.sqlize("data.user.age|int >= 30", driver='asyncpg')
>>> 'to_jsonb(trunc(' in r.build(r.where)[0]
True
Where dotted's answer is a Python repr — str() of an array or object,
or a regex that could match one — Postgres can't write it, as jsonb
keeps no object's key order, and the query fails with a dotted: …
message where it meets such a value. A regex that can't start with [
or { matches no array or object, as in dotted. jsonb stores a JSON
1e3 as 1000, so a float written with an exponent reads as an int.
SQLFragment and composition
r.select, r.where, r.from_ are SQLFragment objects. The
underlying text uses Python format-string syntax with {name} markers
— each marker is resolved to a driver placeholder ($N / %s / etc.)
at build time. Literal braces in the SQL (e.g. JSONB path arrays) are
doubled as {{…}}.
Fragments concatenate naturally via + / __radd__; metadata merges:
unbound is keyed by the bind marker name (what ends up as
$N / %(name)s); each value is the original substitution name
(what was inside $(...)), kept as provenance. Plain identifiers bind
by that same name; non-identifier names (dotted paths, quoted keys,
spaces) hash to a deterministic _s_<hex> marker:
>>> r = dotted.sqlize('age >= $(user.min_age)', driver='asyncpg')
>>> list(r.where.unbound.values())
['user.min_age']
Repeated uses of the same name share one entry — back-referenced by
the placeholder position (or by name under pyformat):
Relative references (^) and parent references (^^+) are not
supported yet.
Pattern paths
A path with a wildcard (*, [*]), **, a filter ([pred],
[*&pred]), a group or a transform reads a step at a time, as dotted's
walk reads it, each node by its own type:
a key reads an object's member;
an int reads an array's element or a string's character, never an
object's member, whose names are strings;
.* reads an object's members, and [*] an array's elements, an
object's values or a string's characters;
*? reads its first match alone;
a filter keeps a node that is an object and whose key's value
compares, so [*&x!=1] keeps one that has no x;
a slice filter, users[age >= 30], reads the filtered list as one
value.
A pattern path gives three fragments: the filter-style r.where,
whether it reaches anything (an EXISTS); the extract-style
r.lateral, its matches, a value each; and r.select, the lateral's
value.
Filter-style — "which items have any matching user?":
SELECT id FROM items WHERE EXISTS (...)
# composed: "SELECT id FROM items WHERE " + r.where
Extract-style — "each matching age, one row per match":
SELECT id, _pat1.value FROM items, LATERAL (...) AS _pat1(value)
# composed: "SELECT id, " + r.select + " FROM items, " + r.lateral
The lateral fragment has no leading comma or JOIN keyword — attach
it however fits: , LATERAL ..., CROSS JOIN ..., LEFT JOIN ... ON TRUE to keep rows without matches, etc.
Lateral aliases (_pat1, _pat2, …) are allocated from the
ParamPool, so two pattern paths sharing a pool pick distinct
aliases and compose into one query without collision.
A group in a path matches as get does: each branch's matches, with
the path after the group run on from each branch. An & group matches
only where every branch does, at each node it is at:
data.users[*].(age >= 30 & active = True) needs one user who is both.
A group of guards, data.(a = 1, b = 2), keeps plain predicates for
r.where; its r.select is its matches.
A first-match group, (a, b)?, is the first match of the first branch
to have one, in dotted's order, the branch alone; the path after the
group runs on from that match, and a guard after it tests that match.
A cut, (a#, b), holds at each node: b's way yields only where a's
reaches nothing there. In a conjunction, (a#&b), the cut leaves b
unread, and in a first-match group it changes nothing. A soft cut,
(a##, *), compares the paths of matches: * skips what overlaps
a's, the ways read with their paths and folded in order with a
recursive query, as dotted does. A cut or a soft cut changes which
matches a group yields, not whether it yields any, so r.where reads
the group without them.
A negation, !, is the complement of what its path matches, not
NOT: data.(!(status = "banned")) matches x in {"status": "banned", "x": 1}. r.lateral yields the largest subtrees that hold
no match, as dotted does: a recursive query walks down through the
children the matches run through and keeps the children none reaches,
and r.where is whether there is one.
An aligned op, [*+], yields for each match what the path after it
reaches, or one null where it reaches nothing.
A group at the top of a path, (title, author), reads the row's
columns as one value: a jsonb_build_object of the columns its
branches name, which every kind of group, cut and soft cut reads as it
would any node. r.select and r.lateral are its matches; a group of
guards keeps plain predicates for r.where, as (age >= 18 & status = "active") does above. A negation at the top of a path is the
complement among all the row's columns, so it reads the whole row of a
table search's table; in a column path, which
has no table, it raises TranslationError.
Writes (as_update)
r.as_update(value) is the write of value at the path's matches, as
dotted's update does it: value at each match; along a path of
literal keys and slots, the nodes it lacks built, a null one replaced,
as dotted builds them; a slot past the end appending; a pattern, filter
or guard writing only what is there and passes; ~ holding a segment
back; [+] appending, and [+?] where the array doesn't hold it, as
Python's in tells. For a column path it is the assignments, for an
UPDATE ... SET:
>>> r = dotted.sqlize('status', driver='asyncpg')
>>> r.build('UPDATE items SET ' + r.as_update('banned'))
('UPDATE items SET status = $1', ['banned'])
>>> r = dotted.sqlize('data.user.role', driver='asyncpg')
>>> sql, args = r.build('UPDATE items SET ' + r.as_update('admin'))
>>> sql.startswith('UPDATE items SET data = CASE WHEN data IS NULL')
True
>>> args[-1]
'"admin"'
A group writes as update does: (a, b) each branch where it
matches, on the node the branches before it wrote, the last concrete
one built where none does; (a&b) every branch, where each matches or
can be built; (a, b)? the first that matches; and a cut ends the
branches after one that matched, so emails[(*&email="x"#, +)] writes
the email that's there, else appends one.
A value is a literal, sent as a parameter, or a Raw / Col SQL
expression. A transform at the end of the path, data.user.age|int,
applies to a literal value, as dotted's does; on a SQL expression it
raises. Where dotted's update raises — a key on a string or an array,
an index before an array's start — the query fails with a
dotted update: … message.
Not yet supported (TranslationError):
Regex keys, data./prefix_\d+/.field; references inside pattern
paths; a ** with depths or accessors; first filters, [*&a=1?]
Transforms other than int, float and str, or with arguments
In a write: a soft cut, !, ** and slices; a group at the top of
a path; a table search
sqlize table search
By default a path's first segment is a column of the row. With
root='table' the path searches a table instead: its leading keys name
the table, a row step walks its rows, and the rest is a column path
under each row, read as above. r.from_ is what to select from:
>>> r = dotted.sqlize('books[*&author="kafka"].title', driver='asyncpg', root='table')
>>> r.table
'books'
>>> r.build('SELECT ' + r.select + ' FROM ' + r.from_ + ' WHERE ' + r.where)
('SELECT title FROM books WHERE author = $1', ['kafka'])
row step
gives
[*]
every row
[*&<filters>]
where from the filters; a filter key is a column path (&data.user.age>30)
[<filters>] (slice filter)
the same where
[n]
offset=n, limit=1
[a:b], [a:], [:b]
offset=a, limit=b-a (either may be None)
A slice filter and a slice keep the rows one list, as in dotted, so
[*] comes before a column: filter, then page, then select:
A group after the row step reads the row's columns, as one at the top
of a column path does (pattern paths); attach its
lateral after the table:
>>> r = dotted.sqlize('books[*](.title, .author)', driver='asyncpg', root='table')
>>> "jsonb_build_object('title', title, 'author', author) AS value" in str(r.lateral)
True
>>> sql = 'SELECT ' + r.select + ' FROM ' + r.from_ + ', ' + r.lateral
A negation after the row step, books[*](!.title), is the complement
among all the row's columns, read from the table's whole row,
to_jsonb(books) (the name without its schema). An unnamed table has
no row to read, so there it raises TranslationError.
With nothing after the row step, select is *. Everything before
it is the table's name, taken whole:
A path that starts with a row step searches an unnamed table, so it
needs no root=; the caller supplies the FROM:
>>> r = dotted.sqlize('[*&author="kafka"]', driver='asyncpg')
>>> r.table is None, r.build(r.where)
(True, ('author = $1', ['kafka']))
r.table, r.offset and r.limit are plain values, not fragments,
and stay out of the Mapping. The table's name comes back as the path
spells it; quoting it is the caller's (Col(r.table) validates it).
r.from_ is a fragment: the table, quoted where it needs it, or the
rows a group of row steps yields.
A group as the row step, books[(*&a=1, *&b=2)] (the same as
books([*&a=1], [*&b=2])), yields each branch's rows in turn, a row
both reach twice, as dotted does. No WHERE can give a row twice, so
r.from_ is a derived table of them under the table's name, and
r.where and r.select are the path after the group's, from each row:
>>> r = dotted.sqlize('books[(*&author="kafka", *&year<1920)].title', driver='asyncpg', root='table')
>>> r.build('SELECT ' + r.select + ' FROM ' + r.from_)
('SELECT title FROM ((SELECT * FROM books WHERE author = $1) UNION ALL (SELECT * FROM books WHERE year < $2)) AS books', ['kafka', 1920])
The group reads the table as one node, as dotted reads the list of
rows: after a cut, (a#, b), b's rows come only where a yielded
no row at all (NOT EXISTS); after a soft cut, (a##, b), b skips
the rows a yielded; a first match, (a, b)?, is the first row of
the first branch with one (LIMIT 1); an & group yields only where
every branch reaches a row; and a negation, books(![*&a=1]), is the
rows its step doesn't reach, a row its filter is null for among them.
A branch may be [*], [*&…] or [n]; a slice filter before the
group filters every branch's rows.
Not yet supported (TranslationError):
A packed group, books[*](.title,.author;)
A group of row steps of an unnamed table, which has none to select
from; a branch that goes on past its row step,
books([*&a=1].title, [*&b=2].author); and one that is a slice
filter or slice, which reads the list of rows
A soft cut or a negation over rows an index picks, [(0##, *&a=1)]:
no predicate tells those rows apart; and a soft cut whose path after
the group may match a row more than once (.tags[*])
A group of row steps after a slice
A key straight after a slice filter or slice (books[a=1].title —
dotted reads a key of the list there; use books[a=1][*].title)
A row step after [*], [*&…] or [n] — dotted indexes into each
row there
After a slice, anything but [*]; slice steps; negative indexes and
bounds
Composing multiple Resolvers — ParamPool
Each call to dotted.sqlize() allocates its own bind-parameter name
pool, so two independent Resolvers can both emit _p1 for their first
hoisted literal. Composing their fragments via + (or wrapping them
in a CTE) would then collide at render time — the second _p1 would
silently overwrite the first.
Pass a shared ParamPool to every sqlize() call that should compose:
When a ParamPool isn't passed, each Resolver gets a private pool —
the single-Resolver case continues to work unchanged.
SQL expressions as substitution values (Raw / Col)
Substitutions normally bind to Python values that hoist into bind
parameters ($1, %(name)s, etc.). For the cases where the "value"
is actually a SQL expression — a column reference, a subquery,
a function call — bind to a Raw wrapper instead:
>>> from dotted.translators import Raw, Col
>>> r = dotted.sqlize('customer = $(matched.customer)', driver='asyncpg')
>>> r.build(r.where, **{'matched.customer': Raw('matched.customer')})
('customer = matched.customer', [])
The Raw contents are emitted verbatim in place of the placeholder.
No bind parameter allocated, no cast emitted, no args-list entry.
Behavior is identical across every paramstyle.
Typical use case: composing CTEs where a substitution in one
Resolver resolves to a column from another CTE:
WITH matched AS (...),
joined AS (
SELECT * FROM ledger
WHERE <rendered joined-predicate with matched.customer as Raw>
)
SELECT * FROM joined
The same Resolver works for both orchestration strategies: runtime
value per matched row (r.build(..., **{'matched.customer': 'alice'}))
or single-SQL CTE composition (..., **{'matched.customer': Raw('matched.customer')})). The caller picks at build time.
Safety:Raw is an escape hatch. Never pass untrusted input —
the string is emitted unescaped. For the common case of qualified
column references, use Col instead, which validates each identifier
segment before building a Raw:
>>> Col('matched.customer')
Col('matched.customer')
>>> Col('matched', 'customer') # equivalent
Col('matched.customer')
>>> Col('schema', 'table', 'col')
Col('schema.table.col')
>>> Col('bad; DROP TABLE') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
dotted.TranslationError: Col part is not a plain identifier: 'bad; DROP TABLE'
Col is a subclass of Raw, so it behaves identically at render
time — the only difference is construction-time validation.
Adding a driver
Drivers are registered via the @dotted.translators.driver('<name>')
decorator on a Resolver subclass that mixes in a flavor (today just
PostgresMixin in dotted.translators.sql_pg). Each subclass declares its
paramstyle and whether it needs explicit casts:
import dotted
from dotted.translators.sql_pg import PostgresMixin
@dotted.translators.driver('my-driver')
class MyDriverResolver(PostgresMixin, dotted.Resolver):
paramstyle = 'pyformat' # one of 'named' | 'pyformat' |
# 'qmark' | 'format' | 'numeric' |
# 'dollar-numeric'
cast = False # True if driver uses server-side PREPARE
# in polymorphic jsonb_build_object contexts
Once registered, dotted.sqlize(path, driver='my-driver') dispatches
to it. dotted.translators.drivers() returns the names of all currently
registered drivers (built-ins + anything third-party code has added).
Resolver attributes
Attribute
Type
Meaning
.driver
str
Name the resolver was registered under
.paramstyle
str
PEP 249 paramstyle emitted by .build()
.cast
bool
Whether .build() casts a marker that asks for one; none sqlize makes does
.select
SQLFragment | None
Extraction expression (for pattern paths: ref into .lateral)
.where
SQLFragment | None
Predicate (None for pure traversals)
.from_
SQLFragment | None
a table search's FROM: the table, or a group of row steps' rows
.lateral
SQLFragment | None
LATERAL (...) AS _patN(value): a pattern path's matches
.unbound
dict
Union of fragments' unbound mappings: {bind_name: original_name}
.table
str | None
Table search: the table's name, as the path spells it
.offset
int | None
Table search: rows to skip
.limit
int | None
Table search: rows to keep
The Resolver also implements the collections.abc.Mapping protocol
over its non-None fragment attributes (select / where / from_ /
lateral):
>>> r = dotted.sqlize('data.users[*].age', driver='asyncpg')
>>> list(r.keys())
['select', 'where', 'lateral']
>>> 'lateral' in r
True
>>> dict(r) # map of present fragments
{'select': ..., 'where': ..., 'lateral': ...}
driver / paramstyle / cast / unbound / table / offset /
limit are reached as plain attributes, not via the Mapping.
driver — required. Name of a registered driver
('asyncpg', 'psycopg2', 'psycopg', or anything registered via
@register). An unknown driver raises TranslationError.
bindings — resolve substitutions at sqlize time. Path-position
substitutions must be resolved here, row indexes and slice bounds
included.
root — 'column' (default): the first segment is a column.
'table': a table search.
r.build(sql, **bindings)
sql — a SQLFragment (usually r.where, r.select, or a
composition like r.select + " FROM t WHERE " + r.where).
**bindings — values for substitutions, keyed by original
substitution name. One named for a parameter is spelled with a
trailing _: sql_=1 binds $(sql), paramstyle_ binds
$(paramstyle), and sql__ binds $(sql_).
r.as_update(value)
value — a literal, sent as a parameter, or a Raw / Col SQL
expression.
Returns a SQLFragment: for a column path, the assignments for an
UPDATE ... SET, each column's new value as dotted's update writes
value at the path's matches (see Writes above). Build it with
r.build. A table search, and a soft cut, !, ** and slices in
the path, raise TranslationError.
The Resolver.build(sql, paramstyle='...', **bindings) classmethod is
retained as a low-level escape hatch that takes an explicit paramstyle
in place of the driver's. Normal application code uses the instance
form above.
A ParamStyle enum is available for the low-level classmethod and
for introspection. Members are accepted alongside their .value
strings at Resolver.build — enum members normalize internally:
Unsupported features raise dotted.TranslationError.
Spark Translation (sparkize)
Under development. The API shape may still change. PySpark only
(classic and Spark Connect). Needs pip install dotted-notation[spark]
(pyspark>=3.4). A translation reads as dotted does; where Spark
can't give what dotted would, it raises: TranslationError while
translating or building, or a dotted: … error when the job meets a
value it can't read as dotted does.
dotted.sparkize(path, flavor='pyspark') translates a dotted path into
PySpark Column expressions for df.where(...) / df.select(...). It
is the Spark counterpart of sqlize, on the same translation walk:
r.select and r.where are fragments, and r.build(fragment, schema=df.schema, **bindings) makes the Column.
Columns are native Spark types. The first path segment is the column;
further segments read into structs, maps and arrays, each node read by
its type as dotted reads a Python value by its own: a struct and a map
as a dict, an array as a list, as row.asDict(recursive=True) hands
them to Python. The DataFrame's schema says what each node is, so
build takes it. A JSON string column isn't parsed for you: give the
DataFrame real struct columns (read them that way, or from_json with
your own schema) first.
import dotted
r = dotted.sparkize('data.user.age >= 30', flavor='pyspark')
df.where(r.build(r.where, schema=df.schema))
r = dotted.sparkize('data.user.name', flavor='pyspark')
df.select(r.build(r.select, schema=df.schema))
flavor= is required, as driver= is for sqlize; the examples
below leave it out, and schema=df.schema, for brevity.
dotted
at a node that is
.k, ['k']
a struct: its field k; a map: its value at a key equal to 'k'
.0, [0], [-1]
an array: its element; a string: its character; a map with int keys: its value at 0
.*
a struct's fields' values, a map's values
[*]
those, and an array's elements, a string's characters
**
every value under it by keys, through structs and maps, each before what is under it
[1:3], [::-1]
an array's or string's slice, one value
[a = 1]
an array's elements the filter keeps, one value
= != < <= > >=
Python's comparison
= /re/
the regex fullmatches str() of the value
|int |float |str
dotted's transform
Reading as dotted reads
A key reads a struct's field or a map's value; an int, an array's
element or a string's character, never a struct's field, whose names
are strings, though a map with int keys has one at it. A node that is
there may be None: a struct's null field is there, as asDict gives it
with its None, and a map's missing key isn't.
A comparison goes as Python's does, by the values' types: a number and
a bool as numbers (True == 1), exactly (1 == 1.0, but an int is
never equal to 0.1, and a DECIMAL0.1 isn't the float 0.1), a
string with a string in code-point order, any other pairing unequal and
unordered: '30' = 30 is false where Spark would cast. != is ='s
negation, so it holds for a null; < and its kind are false for one; a
NaN orders nowhere. A guard tests a value that is there: a missing key
matches neither = None nor != 1.
A regex fullmatches str() of the value, as dotted's does, written in
Java's syntax as Python reads it: a number as Python writes it,
True / False, None for a null. int, float and str run as
dotted's: int truncates a number and reads a string int() reads,
and keeps what int() raises on; float raises on a None and a
container, which fails the job.
Where dotted raises, as float on a None or a slice filter on a
scalar, the job fails with a dotted: … message, and so where dotted's
answer is a Python repr, str() of a struct, map or array, which Spark
can't write. A float's str() is built from Java's digits: before
Java 19, Java writes a few floats with digits that aren't Python's
shortest.
Pattern paths
where is whether the path reaches anything; select is the array of
its matches, in dotted's order:
r = dotted.sparkize('data.users[*].age >= 30')
df.where(r.build(r.where)) # rows with some user aged 30+
df.select(r.build(r.select)) # per row, the ages that are 30+
r = dotted.sparkize('data.users[*&active = True].age')
df.select(r.build(r.select)) # per row, the active users' ages
A Spark array holds values of one type, so a select whose matches
can be of more than one type raises at build, ints as a long and
floats as a double aside: data.* over a struct of an int and a
string. Its where reads as any.
A path with no pattern in it selects its one value, as get gives it:
data.users[active = False] is the filtered list.
A group in a path matches as get does: select is each branch's
matches in turn, the path after the group run on from each, and an &
group matches only where every branch does, at each node it is at:
r = dotted.sparkize('data.(user, users[*]).age')
df.select(r.build(r.select)) # per row, user.age then each users[*].age
r = dotted.sparkize('data.users[*].(age >= 30 & active = True)')
df.where(r.build(r.where)) # rows with one user both 30+ and active
A first-match group, (a, b)?, is the first match of the first branch
to have one, the path after it run on from that match:
r = dotted.sparkize('data.(users[*], user)?.age')
df.select(r.build(r.select)) # per row, the first user's age, else user.age
After a cut, (a#, b), b runs only where a found nothing, at each
node. After a soft cut, (a##, b), b skips what overlaps a's
matches: the group's branches are read with their paths and folded in
order (aggregate). A negation, !, is the complement of what its
path matches, not ~: tags(!.color) is every value of tags but
color's, split level by level to the depth its path reads, over a
struct's fields, a map's entries and an array's elements.
A group at the top of a path, or after a table
search's row step, reads the row's columns as
one struct of the columns its branches name, so every kind of group,
cut and soft cut works there as at any node:
r = dotted.sparkize('(age >= 30#, data.user.age)')
df.select(r.build(r.select)) # per row, age where it's 30+, else user.age
A negation there, in a search of a named table, is the complement among
all the row's columns.
Substitutions (late binding)
As with sqlize, $(name) stays unbound until build, or resolves
up front with bindings=:
A binding is compared as Python compares it: min_age=30.5 is no int.
A Column binding is compared by its type, which build reads in the
active session: r.build(r.where, schema=df.schema, min_age=F.col('floor')).
A substitution at a path's head starts the read at what build binds
it to: a Column, or a column's name. A higher-order function's lambda
argument is a Column no session can type, so r.typed(column, dtype)
carries its type:
A pattern's is an array of its matches', a where's boolean. dtype
is None where the type can't be told: a path the schema has nothing
at, concrete or a pattern, or a select of *, every column.
Composing fragments
A Column can't hold a placeholder, so r.where is a
ColumnFragment: a Column not made yet. Fragments compose with &,
| and ~ before build; their unbound substitutions merge:
a = dotted.sparkize('age >= $(min_age)')
b = dotted.sparkize('status = "active"')
df.where(a.build(a.where & b.where, schema=df.schema, min_age=30))
Writes (as_update)
r.as_update(value) is the write of value at the path's matches, as
dotted's update does it, and as sqlize's as_update writes it.
build makes it a dict of each column the write touches to its new
value, for df.withColumns:
r = dotted.sparkize('data.user.role')
df = df.withColumns(r.build(r.as_update('admin'), schema=df.schema))
The write is:
value at each match;
along literal keys and slots, the nodes the path lacks built, a null
one replaced, as dotted builds them, and a slot past the end
appending;
a pattern, filter or guard writing only what is there and passes;
~ holding a segment back;
[+] appending, and [+?] where the list doesn't hold the value, as
Python's in tells.
A value is a literal, or a Column, read by its type; a transform at
the end of the path applies to a literal. A struct's field takes the
written value's type; a map's values, and a list's elements, share
one. Where Spark can't hold what dotted writes, the job fails, with a
dotted update: … message, where a row has it:
a null struct, which dotted makes a dict of only the keys the path
names;
a field added to some of a list's structs and not to others;
a str written among a map's ints.
A group writes as dotted's update does, as in sqlize: (a, b) each branch where it
matches, on the node the branches before it wrote, the last concrete
one built where none does; (a&b) every branch, where each matches or
can be built; (a, b)? the first that matches; and a cut ends the
branches after one that matched, so emails[(*&email="x"#, +)] writes
the email that's there, else appends one.
So does a write where dotted's update raises: a key on a list, an
index before its start. A slot on a str, which dotted writes, fails
too for now, as in sqlize (#75).
sparkize table search
root='table' reads a path as a table search, the
same as for sqlize: the leading keys name a DataFrame or table, and
r.table, r.offset and r.limit are plain values the caller chains
(skip .offset / .limit when they are None; offset needs Spark
3.4+):
With nothing after the row step, select is every column
(col('*')). A path that starts with a row step, [*&author="kafka"],
needs no name and no root=: apply its where to any DataFrame.
A group as the row step, books[(*&a=1, *&b=2)], yields a row once per branch that reaches it, which no
where can give: read the rows with r.rows, from the table's
DataFrame, then chain as above. For any other search r.rows(df) is
df itself, so it's always safe to call:
r = dotted.sparkize('books[(*&author="kafka", *&year<1920)].title', root='table')
rows = r.rows(spark.table(r.table)) # each branch's rows, unionByName
rows.select(r.build(r.select, schema=rows.schema))
rows takes bindings as build does. A cut, a first match or an
& over the table is a cross join with a one-row count of the rows it
tests. An unnamed table's group works too, from whichever DataFrame is
handed in; otherwise the same groups raise as in sqlize.
Not yet supported (TranslationError):
A ** with depths or accessors, **:2; a negation reaching any
depth, !**.x
A transform on the column itself, age|int; transforms other than
int, float and str, or with arguments
Comparing a DECIMAL with a float Column; str() or a regex of a
timestamp, whose Python value depends on the session's time zone;
reading into a binary value
In a write: a soft cut, !, ** and slices; a group at the top of
a path; a table search; a column the schema lacks
flavor — required. Name of a registered flavor ('pyspark').
An unknown flavor raises TranslationError.
dotted.translators.flavors() lists them.
bindings — resolve substitutions at sparkize time. Path-position
substitutions must be resolved here, row indexes and slice bounds
included, but for one at a read's head, which build may bind.
root — 'column' (default): the first segment is a column.
'table': a table search.
fragment — a ColumnFragment (r.where, r.select, or a
composition of fragments), or r.as_update(value), which builds to a
dict of column name to Column.
schema — required. The schema of the DataFrame the Column
reads, df.schema: a path reads each node by its type.
typed — True builds a TypedColumn, column, dtype, in place of
the Column; as_update a dict of them. dtype is a Spark type, or
None where it can't be told.
**bindings — values for substitutions, keyed by original
substitution name. An unknown or missing binding raises
TranslationError. One named for a parameter is spelled with a
trailing _: schema_=30 binds $(schema), schema__ binds
$(schema_); r.rows(df, df_=...) binds $(df).
r.as_update(value)
value — a literal, or a Spark Column, read by its type.
Returns a fragment build makes into a dict of each column the write
touches, by name, to its new value, for df.withColumns (see
Writes above).
Translation never imports pyspark; only build does.
Constants and Exceptions
ANY
The ANY constant is used with remove and update to match any value:
--pack and --unpack compose — pack rebuilds structure on input, unpack
flattens on output. This lets you use nested operations on dotted normal form. For
example, removing an entire group without listing every key:
Filters (e.g. key=value, *=None) can use patterns but do not make the path a pattern; only the path segments and path-level operators do. So name.first&first=None is non-pattern (single value), while name.*&first=None is pattern (tuple), even though both can express "when name.first is None." Value guards (e.g. name.first=None) also preserve the pattern/non-pattern status of the underlying path segment.
For update and remove you usually don't care: the result is the (possibly mutated) object either way. For get, the return shape depends on pattern vs non-pattern. Use dotted.is_pattern(path) if you need to branch on it. Similarly, dotted.is_template(path) tells you whether a path contains substitution references.
How do I craft an efficient path?
Same intent can be expressed in more or less efficient ways. Example: "match when name.first is None"
Inefficient:name.*&first=None — pattern path; iterates every key under name, then filters. No short-circuit.
Better:name.*&first=None? — same path with first-match ?; stops after one match.
Even better:name.first=None — value guard; non-pattern path; goes straight to name.first and tests the value directly.
Also good:name.first&first=None — non-pattern path with a concrete filter key.
Prefer a concrete path when it expresses what you want; use pattern + ? when you need multiple candidates but only care about the first match.
Why do I get a RuntimeError when updating with a slice filter?
A slice filter like [id=1] returns the filtered sublist as a single value — it operates on the list itself, not on individual items. Updating that sublist in place is ambiguous: the matching items may be at non-contiguous indices, so there's no clean way to splice a replacement back into the original.
But you probably don't want to update a slice filter anyway — instead, use a pattern like [*&id=1] which walks the items individually and updates each match in place.
Why can't I use patterns on Stripe objects?
Pattern access (@*, .*) works by enumerating an object's known keys or attributes. Dotted checks __dict__, __slots__, _fields (namedtuples), and keys() (for key fields). Stripe objects don't use any of these — they store data in an internal _data dict and expose it through a custom __getattr__. Since Python has no standard protocol for asking "what keys does your __getattr__ accept?", there's nothing for dotted to enumerate.
Concrete access works fine.@name, @email, .id — anything where you specify the exact key will work, because dotted falls back to trying getattr/__getitem__ directly.
Pattern access can't discover what you don't advertise. This is a limitation of the object, not dotted. If you need pattern access, convert to a dict first:
obj_dict = obj.to_dict() # Stripe objects support this
dotted.get(obj_dict, '*') # now enumerable
Alternatives
Use instead of dotted-notation: tools that do the same job, closest first.