| | |

YAML 12 ๐Ÿ“„ Custom Tag Constructors and Implicit Resolution Rules

โฑ๏ธ Estimated read: 10 min | |

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)

APIEffect
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)

OrderTypeExample
1nullnull, ~
2booltrue, false
3int42, 0x2A
4float3.14, .inf
5strfallback

Explicit Tag Dispatch

TagResult
!!str 123"123" (string)
!!int "42"42 (integer)
Untagged 123Implicit 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

PitfallWhy It HappensFix
safe_load fails on custom tagConstructor registered without Loader=SafeLoaderAdd the argument
yes resolves to boolean1.1 resolver activeQuote the value or use 1.2 parser
!!timestamp unresolved after js-yaml 5 migrationBuilt on CORE_SCHEMAAdd the tag explicitly
construct_undefined raises in ruamel 0.17.32+API changedUse 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

ItemValue
PyYAML registrationyaml.add_constructor(tag, fn, Loader=SafeLoader)
Missing Loader argumentRegisters on all loaders except SafeLoader
Core Schema precedencenull โ†’ bool โ†’ int โ†’ float โ†’ str
Core Schema booleanstrue/false only
Explicit tagOverrides implicit resolution
js-yaml 5 APIdefineScalarTag + Schema.withTags
js-yaml 5 schema trapCORE_SCHEMA drops !!timestamp, !!merge

Key takeaways:

  • The Loader argument is not optional. Omitting Loader=yaml.SafeLoader in add_constructor registers the constructor everywhere except the safe loader, and safe_load still fails with an unresolved tag error .
  • Explicit tags override implicit resolution absolutely. !!str 123 is 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/false and their case variants are booleans. yes, no, on, and off are 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.

Was this helpful?


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!