YAML 12 ๐ Custom Tag Constructors and Implicit Resolution Rules
Custom tag constructors and implicit resolution are two sides of the same mechanism: deciding what a node means. Implicit resolution applies a schema’s rules to an untagged scalar, deciding whether true is a boolean or false is a string. A custom tag constructor overrides that decision for a specific tag, letting the application define the type and the parsing logic. The two interact at the point where the parser encounters a node: if the node has an explicit tag, the constructor for that tag runs; if it has no tag, the schema’s implicit resolver decides the type.
This chapter covers the registration of custom tag constructors in Python and JavaScript, the implicit resolution precedence order defined by the YAML 1.2.2 Core Schema, and the security constraint that makes registration a trust decision. The sections that follow walk through the constructor registration APIs, the resolution precedence, and the boundary between safe and unsafe parsing.
Key point: An explicit tag always overrides implicit resolution; registering a constructor on SafeLoader requires passing Loader=yaml.SafeLoader explicitly, and omitting it registers the constructor on every loader except the safe one.
a. Registering custom tag constructors
In PyYAML, a custom tag is handled by a constructor function that receives the loader and the node. The constructor is registered with yaml.add_constructor(tag, constructor, Loader=...). The Loader argument is not optional in practice: if it is omitted, the constructor is registered on Loader, FullLoader, and UnsafeLoader, but not on SafeLoader . A subsequent call to yaml.safe_load() will still fail with “could not determine a constructor for the tag,” because the safe loader never received the registration.
import yaml
def my_constructor(loader, node):
# node is a ScalarNode, SequenceNode, or MappingNode
return loader.construct_scalar(node).lower()
# Correct: register on SafeLoader explicitly
yaml.add_constructor('!my_tag', my_constructor, Loader=yaml.SafeLoader)
parsed = yaml.safe_load('key: !my_tag VALUE')
# parsed == {'key': 'value'}
The constructor’s job is to turn the node into a native object. For a scalar node, loader.construct_scalar(node) returns the string content. For a sequence or mapping, construct_sequence and construct_mapping build the corresponding Python structures. The constructor can return any object, including a custom class instance, which is how YAML represents domain types.
In js-yaml 5, the API changed substantially. The yaml.Type constructor and DEFAULT_SCHEMA.extend() are gone. Custom tags are defined with defineScalarTag, defineSequenceTag, or defineMappingTag, and registered on a schema with Schema.withTags() . Scalar tags use a resolve function that returns the value or NOT_RESOLVED. Collection tags use an incremental protocol: create makes a carrier, addItem or addPair populates it, and finalize converts the carrier into the final object .
import { defineScalarTag, CORE_SCHEMA } from 'js-yaml';
const lowerTag = defineScalarTag('!lower', {
resolve: (data) => data.toLowerCase(),
});
const schema = CORE_SCHEMA.withTags(lowerTag);
The migration trap noted in the js-yaml upgrade documentation is schema breadth. Building on CORE_SCHEMA instead of the old DEFAULT_SCHEMA silently drops the non-core implicit tagsโ!!timestamp, !!merge, !!binary, !!set, !!omap, !!pairsโand any fixture using them changes from “parsed” to “unresolved tag” . A project migrating from js-yaml 4 must confirm which implicit tags are actually in use before narrowing the schema.
b. Implicit resolution precedence
The YAML 1.2.2 Core Schema defines a precedence order for implicit scalar resolution: null โ bool โ int โ float โ str . The resolver tests the scalar against the null patterns first, then boolean, then integer, then float, and falls back to string. The order matters because a scalar that could match multiple patterns is resolved to the first match. null and ~ resolve to null before the boolean pattern can see them; 0 resolves to an integer before the float pattern can claim it.
The Core Schema’s boolean set is restricted to true/True/TRUE and false/False/FALSE . The wider set that includes yes, no, on, and off belongs to the YAML 1.1 schema or the Extended schema, not the 1.2 Core Schema. A parser that resolves yes to a boolean is applying 1.1 rules, regardless of the %YAML directive in the file.
The explicit-tag dispatch is absolute: !!str 123 produces the string "123", and !!int "42" produces the integer 42. The resolution proofs in the L4YAML formalization state this as a theorem: “Explicit tags override implicit resolution” . The parser checks for a tag first; only when no tag is present does it run the implicit resolver.
c. The security boundary
Custom tag constructors are code execution points. A constructor that instantiates a class or calls a function runs that code when the parser encounters the tag. This is why the safe loader refuses to construct unknown tags by default: an attacker who controls the YAML document can choose the tag, and a parser that resolves arbitrary tags will execute whatever the tag’s constructor does.
The PyYAML guidance is explicit: when registering a custom constructor for use with safe_load, the Loader=yaml.SafeLoader argument must be supplied . The registration is a deliberate act of trust: the application decides that !my_tag is a known, safe tag with a constructor that does not execute arbitrary code. Any tag without a registered constructor remains unresolved, and safe_load raises an error rather than guessing.
The same principle applies to the ruamel.yaml change that broke construct_undefined in version 0.17.32. Code that relied on construct_undefined to handle unknown tags had to migrate to construct_unknown, because the former now raises an error instead of returning a placeholder . The change is a tightening of the default: unknown tags are errors unless the application explicitly handles them.
Complete Example Session
# ============================================
# PART 1: THE CUSTOM TAG IN YAML
# ============================================
# config.yaml:
# timeout: !duration 30s
# retries: !duration 5s
# ============================================
# PART 2: THE CONSTRUCTOR
# ============================================
import re
import yaml
def duration_constructor(loader, node):
value = loader.construct_scalar(node) # "30s"
match = re.match(r'^(\d+)s$', value)
if not match:
raise yaml.constructor.ConstructorError(
None, None, f"Invalid duration: {value}", node.start_mark
)
return int(match.group(1)) # seconds as int
# ============================================
# PART 3: REGISTRATION ON SAFELOADER
# ============================================
yaml.add_constructor(
'!duration',
duration_constructor,
Loader=yaml.SafeLoader, # REQUIRED for safe_load
)
# ============================================
# PART 4: PARSING
# ============================================
parsed = yaml.safe_load("timeout: !duration 30s")
# {'timeout': 30}
# ============================================
# PART 5: IMPLICIT RESOLUTION UNCHANGED
# ============================================
# Untagged scalars still use the schema's rules
# enabled: true โ boolean (Core Schema)
# version: 1.10 โ float 1.1 under PyYAML's 1.1 resolver
The parts covered the YAML with custom tags, the constructor that parses the scalar and returns an integer, the registration on SafeLoader, the parsed result, and the implicit resolution that remains active for untagged scalars.
Quick Reference
Constructor Registration (PyYAML)
| API | Effect |
|---|---|
yaml.add_constructor(tag, fn, Loader=SafeLoader) | Registers on safe loader |
yaml.add_constructor(tag, fn) | Registers on Loader/FullLoader/UnsafeLoader, not SafeLoader |
loader.construct_scalar(node) | Returns scalar string |
loader.construct_sequence(node) | Returns list |
loader.construct_mapping(node) | Returns dict |
Implicit Resolution Precedence (Core Schema)
| Order | Type | Example |
|---|---|---|
| 1 | null | null, ~ |
| 2 | bool | true, false |
| 3 | int | 42, 0x2A |
| 4 | float | 3.14, .inf |
| 5 | str | fallback |
Explicit Tag Dispatch
| Tag | Result |
|---|---|
!!str 123 | "123" (string) |
!!int "42" | 42 (integer) |
Untagged 123 | Implicit resolution |
Best Practices
โ Do This:
# Register on SafeLoader explicitly
yaml.add_constructor('!x', fn, Loader=yaml.SafeLoader) # โ
# Validate scalar content in the constructor
if not re.match(r'^\d+s$', value): raise ConstructorError() # โ
# Test the schema after js-yaml migration
# Confirm !!timestamp, !!merge, etc. still resolve # โ
โ Don’t Do This:
# Register without Loader and expect safe_load to work
yaml.add_constructor('!x', fn) # safe_load still fails # โ
# Construct arbitrary classes from untrusted input
return SomeClass(**loader.construct_mapping(node)) # โ
# Assume CORE_SCHEMA has the same tags as DEFAULT_SCHEMA
# (it drops !!timestamp, !!merge, !!binary) # โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
safe_load fails on custom tag | Constructor registered without Loader=SafeLoader | Add the argument |
yes resolves to boolean | 1.1 resolver active | Quote the value or use 1.2 parser |
!!timestamp unresolved after js-yaml 5 migration | Built on CORE_SCHEMA | Add the tag explicitly |
construct_undefined raises in ruamel 0.17.32+ | API changed | Use construct_unknown |
Real-World Examples
1. Scalar custom tag
yaml.add_constructor('!lower', lambda l, n: l.construct_scalar(n).lower(), Loader=yaml.SafeLoader)
2. Sequence custom tag
def point(loader, node):
x, y = loader.construct_sequence(node)
return (x, y)
yaml.add_constructor('!point', point, Loader=yaml.SafeLoader)
3. Mapping custom tag
def config(loader, node):
return loader.construct_mapping(node)
yaml.add_constructor('!config', config, Loader=yaml.SafeLoader)
4. js-yaml 5 scalar tag
defineScalarTag('!lower', { resolve: (d) => d.toLowerCase() });
5. js-yaml 5 sequence tag
defineSequenceTag('!point', {
create: () => ({}),
addItem: (p, v, i) => { p[i === 0 ? 'x' : 'y'] = v; },
});
6. Core Schema null
value: ~ # null
7. Core Schema bool
value: true # boolean (1.2)
8. Explicit string override
value: !!str true # "true", not boolean
9. SafeLoader registration
yaml.add_constructor('!x', fn, Loader=yaml.SafeLoader)
10. Unknown tag error
yaml.safe_load('!unknown x') # ConstructorError
Visual
Constructor Registration Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ add_constructor('!x', fn, Loader=SafeLoader) โ
โ โ โ
โ โผ โ
โ SafeLoader.yaml_constructors['!x'] = fn โ
โ โ โ
โ โผ โ
โ safe_load("key: !x value") โ
โ โ โ
โ โผ โ
โ Parser sees tag '!x' โ
โ โ โ
โ โผ โ
โ fn(loader, node) runs โ returns object โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Implicit Resolution Precedence
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Untagged scalar: "true" โ
โ โ โ
โ โผ โ
โ Check null patterns? โ no โ
โ โ โ
โ โผ โ
โ Check bool patterns? โ yes โ boolean โ
โ โ โ
โ โผ โ
โ (int, float, str checks skipped) โ
โ โ
โ Order: null โ bool โ int โ float โ str โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Explicit Tag Override
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ !!str 123 โ
โ โ โ
โ โผ โ
โ Explicit tag found โ
โ โ โ
โ โผ โ
โ Implicit resolution skipped โ
โ โ โ
โ โผ โ
โ String constructor runs โ "123" โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Security Boundary
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SAFE PATH UNSAFE PATH โ
โ โ
โ Registered constructor Unregistered tag โ
โ on SafeLoader on safe_load โ
โ โ runs, returns object โ ConstructorError โ
โ โ
โ Constructor is trusted code No arbitrary resolution โ
โ (application-defined) (fails closed) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| PyYAML registration | yaml.add_constructor(tag, fn, Loader=SafeLoader) |
| Missing Loader argument | Registers on all loaders except SafeLoader |
| Core Schema precedence | null โ bool โ int โ float โ str |
| Core Schema booleans | true/false only |
| Explicit tag | Overrides implicit resolution |
| js-yaml 5 API | defineScalarTag + Schema.withTags |
| js-yaml 5 schema trap | CORE_SCHEMA drops !!timestamp, !!merge |
Key takeaways:
- The
Loaderargument is not optional. OmittingLoader=yaml.SafeLoaderinadd_constructorregisters the constructor everywhere except the safe loader, andsafe_loadstill fails with an unresolved tag error . - Explicit tags override implicit resolution absolutely.
!!str 123is the string"123"regardless of the implicit resolver’s rules. The parser checks the tag first; only untagged scalars run the schema’s resolution . - The Core Schema’s precedence order is null โ bool โ int โ float โ str. A scalar that matches an earlier pattern is resolved to that type and never tested against later patterns .
- The Core Schema’s boolean set is narrow. Only
true/falseand their case variants are booleans.yes,no,on, andoffare strings under 1.2 Core, and a parser that resolves them to booleans is applying 1.1 rules. - Custom constructors are a trust boundary. A constructor runs application code when its tag appears. Register only tags the application defines and trusts, and never construct arbitrary classes from untrusted input.
Remember: A custom tag constructor is a function the parser calls when it sees a specific tag. The registration is the trust decision: after add_constructor, that tag will execute the function. The Loader argument determines which parser will honor it, and SafeLoader requires the explicit argument. Implicit resolution is the fallback for untagged scalars, and its precedence order means the first matching pattern wins. When a custom tag does not work with safe_load, the cause is almost always the missing Loader argument; when a scalar resolves to the wrong type, the cause is the schema, not the tag.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!