← Back to Home

YAML: safe_load Rewrites Eight Values Silently

YAMLPyYAMLConfig Parsing

TL;DR: The YAML spec defines syntax, not the types you get in memory — that part belongs to a schema. PyYAML 6.0.3 follows the YAML 1.1 implicit resolution table; ruamel.yaml 0.19.1 defaults to 1.2. I tested 19 common literals and 11 of them (57.9%) return different values. Eight of those differences are silent: no becomes False, 012 becomes 10, 1.0e3 becomes a string. By the time you notice, the config has already shipped in several releases.

// FLOW_01Five stops of one config read5 NODES01STEP_01file says k: no02STEP_02PyYAML safe_load parses as 1.103STEP_03memory holds False04STEP_04check for the string 'no' is never true05STEP_05no error, wrong branchEND_OF_FLOW
Five stops of one config read · diagram drawn from this article
YAML read path: the literal k no becomes False after safe_load
YAML read path: the literal k no becomes False after safe_load · Concept illustration based on this article
PythonJsonYaml
Technologies referenced · icons from Simple Icons (CC0)

Two type systems, not one table

People assume YAML parsing is deterministic: one file, one answer. It is not. The only part of the spec that defines implicit typing is the schema chapter, and the 1.1 and 1.2 schemas do not agree on the same literals.

The YAML 1.1 boolean type page (yaml.org/type/bool.html, Working Draft 2005-01-18) is generous. Its regexp includes y|Y|yes|Yes|YES|n|N|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF, its canonical form is y|n, and the definition adds that booleans "may be abbreviated as a single character y/n or Y/N".

YAML 1.2.2 (Revision 1.2.2, 2021-10-01) drops that vocabulary. The Core Schema table keeps three casings of two words only: true | True | TRUE | false | False | FALSE. Integers changed too: 1.1 marks octal with a leading zero, 1.2 requires 0o [0-7]+. Floats are subtler — the 1.2 table writes ([eE] [-+]? [0-9]+)?, so the exponent sign is optional.

PyYAML uses the 1.1 table. Its resolver.py boolean regexp literal is ^(?:yes|Yes|YES|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF)$, its integer regexp contains [-+]?0[0-7_]+ for leading-zero octal, and its float regexp demands a signed exponent: [eE][-+][0-9]+. ruamel.yaml defaults to 1.2; its own API documentation describes the version argument as a way to "allow downgrading to YAML 1.1", which implies the default is not 1.1.

Put simply: your literal is unambiguous; the resolver table is not.

The measured matrix: 19 literals

Environment: Windows 11, CPython 3.13.14, PyYAML 6.0.3 (released 2025-09-25), ruamel.yaml 0.19.1. Everything below came out of my own run, not from documentation.

Literal in filePyYAML 6.0.3ruamel.yaml default (1.2)Verdict
noFalse'no'differ
onTrue'on'differ
YesTrue'Yes'differ
y'y''y'same
0121012differ
010810differ
0o12'0o12' (string)10differ
08'08' (string)8differ
0x1f3131same
1:3090'1:30'differ
12:00:3043230'12:00:30'differ
1e3'1e3' (string)1000.0differ
1.0e3'1.0e3' (string)1000.0differ
1.0e+31000.01000.0same
1.101.11.1same
42_0004200042000same
2026-11-16datetime.datedatetime.datesame
~NoneNonesame
empty valueNoneNonesame

Eleven of 19 rows differ: 57.9%. And "same" does not mean safe. Both libraries read 1.10 as 1.1, and both leave y as a string even though the 1.1 spec calls it a boolean. One direction loses a value, the other ignores a spec rule.

Reproduce it with two lines:

python -m pip install --target .\yamllib pyyaml==6.0.3 "ruamel.yaml==0.19.1"
set PYTHONPATH=.\yamllib

I have hit the same class of bug one layer up, in JSON libraries, where defaults decide both the value and its shape: see nine defaults tested across json, orjson and msgspec.

Pitfall 1: no and on become booleans, y and n do not

flag: no loads as False in PyYAML. If your code is if cfg['flag'] == 'no', that branch never runs. If your code is if not cfg['flag'], the user's no really does take the false path and everything looks healthy. That is the worst kind: half the behaviour is right.

The single letters are stranger. YAML 1.1 lists y and n as booleans, yet PyYAML's boolean regexp has no single-letter alternative at all. Measured: PyYAML returns 'n'; ruamel.yaml in 1.1 mode returns False. Two implementations that both claim 1.1 give opposite answers for two words the spec spells out.

This is a deliberate decision, not an accident. The PyYAML changelog for 3.06 says: "Fix the 'N' plain scalar being incorrectly recognized as !!bool".

The only dependable fix is quoting every human word:

features:
  cache: "no"
  telemetry: "off"
  audit: false

Quotes push the node through !!str, so both libraries return the string 'no' and nobody guesses. Booleans then have to be real false values instead of words.

Pitfall 2: 012 is 10 or 12, and 08 becomes a string

A leading zero means octal in 1.1. 012 is 10 in PyYAML and 12 in ruamel's default — one file, two port numbers for two services.

010 makes it obvious: PyYAML gives 8. And 08 raises nothing at all, because 8 is not a legal octal digit, so the integer regexp fails and the value degrades to the string '08'. In the same block 010 is an int and 08 is a string, with no warning anywhere.

The reverse trap exists too. 0o12 is valid 1.2, ruamel reads 10, but PyYAML does not understand the 0o prefix and returns the string '0o12'. Writing modern YAML makes the value a string on older loaders.

Fix: quote identifiers, ports, build numbers and version strings, or avoid leading zeros entirely.

Pitfall 3: 1.0e3 is a string, 1.0e+3 is a float

PyYAML's float regexp requires the sign in the exponent, [eE][-+][0-9]+. So 1.0e3 fails to match and you get the string '1.0e3'; only 1.0e+3 becomes 1000.0. ruamel follows the 1.2 optional sign and returns a float for both.

What makes this expensive is that it still looks like a number. The string blows up with TypeError: can't multiply sequence by non-int when you do arithmetic, turns into a quoted number in json.dumps, and sorts as text in a database. The config file itself is fine.

Fix: write 1.0e+3, or write 1000 and stop worrying.

Pitfall 4: 1.10 becomes 1.1, dates become date objects

version: 1.10 loads as 1.1. Both libraries agree, because this is YAML float semantics rather than a 1.1 versus 1.2 disagreement. Release numbers, image tags and protocol versions silently lose a digit.

Dates behave the same way: date: 2026-11-16 loads as datetime.date(2026, 11, 16), not a string. Hand that to json.dumps and you get TypeError: Object of type date is not JSON serializable, while str() gives you a format that may not be the one your API promised.

Fix: quote version strings and dates. Convert types explicitly in code instead of letting the resolver decide.

Pitfall 5: duplicate keys, three different answers

Write the same key twice:

a: 1
a: 2

Three answers. PyYAML's choice is documented in its own changelog for 3.04: "No longer check for duplicate mapping keys as it didn't work correctly anyway." ruamel's documentation is blunt about the consequence: "PyYAML never enforced this although the YAML 1.1 specification already required this."

So a config file with an unresolved merge conflict behaves as "later wins" in PyYAML, as a startup crash in ruamel, and as "first wins" in ruamel with the lenient flag. None of the three tells you that a duplicate exists.

Fix: run ruamel's strict default as a CI check. It stops the problem before the merge lands.

Pitfall 6: an anchor is the same object, not a copy

&anchor and *alias do not copy a value; they reference it. The << merge key does the same, so every mutable object merged in stays shared.

Measured: with defaults: &d {retries: 3, tags: []} merged into two services via <<: *d, svc_a['tags'] is svc_b['tags'] returns True. Append one item to the first list and it appears in svc_b and in defaults too.

In a single process that is a memory optimisation. Across threads it is a race. Across services it turns into "why did A's config change B".

Fix: copy.deepcopy right after load, or restrict anchors to scalars only.

Pitfall 7: %YAML 1.2 in the header changes nothing

It is tempting to add a %YAML 1.2 directive and assume PyYAML will switch to the new rules. It will not. With that directive in the file, no still loads as False and 012 still loads as 10, because PyYAML's implicit resolvers are attached to the loader, not read from the document.

ruamel does honour the directive: in the same document no stays 'no', 012 becomes 12, and yaml.version becomes (1, 2).

Fix: never rely on the header. Pin the parsing version in code and write it into the README, or the next person on the next machine gets different behaviour.

Pitfall 8: writes reorder keys and escape non-ASCII text

After you load, edit and dump, yaml.safe_dump defaults to sort_keys=True, so {'b': 1, 'a': 2} writes a: 2 first. Your config repo diff becomes a wall of moves and the real change is invisible in review.

allow_unicode defaults to False, so {'k': '中文'} dumps as k: "\u4E2D\u6587".

One default does help: the string 'no' is written back with quotes, because the dumper knows that unquoted it would become a boolean. Not every library is that careful.

Fix: pass sort_keys=False and allow_unicode=True explicitly, and make config directories read-only in the pipeline.

The same "the layer silently moves your data" pattern shows up outside YAML as well; field and record boundaries in CSV move just as quietly, as I measured in eight CSV boundaries that shift your data.

Troubleshooting: four errors I reproduced

Every message below is verbatim output from this machine, not a generic example.

Error 1: tab indentation

Symptom:

yaml.scanner.ScannerError: while scanning for the next token
found character '\t' that cannot start any token
  in "config.yaml", line 2, column 1

Cause: YAML indentation is spaces only. A tab cannot start any token anywhere. Snippets copied from a web page or a chat window frequently carry tabs you cannot see.

Fix: rewrite tabs as four spaces, then parse again and confirm the column is gone.

python -c "import io,sys; p=sys.argv[1]; s=io.open(p,encoding='utf-8').read(); s=s.replace(chr(9),'    '); io.open(p,'w',encoding='utf-8',newline='').write(s)" config.yaml

Error 2: two documents in one file

Symptom:

yaml.composer.ComposerError: expected a single document in the stream
  in "config.yaml", line 1, column 1
but found another document
  in "config.yaml", line 2, column 1

Cause: yaml.safe_load reads exactly one document and fails on the second ---. Kubernetes manifests and multi-environment configs are commonly stacked in one file.

Fix: switch to safe_load_all, or split the file on ---.

import yaml
docs = list(yaml.safe_load_all(open('config.yaml', encoding='utf-8')))
print(len(docs), type(docs[0]).__name__)

Error 3: a custom tag with no constructor

Symptom:

yaml.constructor.ConstructorError: could not determine a constructor for the tag '!Foo'
  in "config.yaml", line 1, column 4

Cause: !Foo is a custom tag and the safe loader only knows standard ones. Either the file is wrong or the code never registered a constructor.

Fix: decide whether you need the tag at all. If you do, register it explicitly.

import yaml
def foo(loader, node):
    return loader.construct_scalar(node)
yaml.SafeLoader.add_constructor('!Foo', foo)
print(yaml.safe_load('k: !Foo bar'))

Error 4: load() is missing the Loader argument

Symptom:

TypeError: load() missing 1 required positional argument: 'Loader'

Cause: PyYAML 6.0 (2021-10-13) shipped PR #561, "always require Loader arg to yaml.load()". Older code calling yaml.load(f) stops working outright.

Fix: use yaml.safe_load(f). Do not reach for Loader=yaml.UnsafeLoader to silence it — since 5.4 arbitrary Python tags live in UnsafeLoader, so that option executes your config file as code.

Three checks before you ship

Rule 1, quote anything that looks like something else. Version strings, dates, identifiers, word booleans. This alone removes six of the eight pitfalls above.

Rule 2, diff two parsers in CI. Load with PyYAML and ruamel, compare the normalised structure including types, fail on any mismatch. At a 57.9% disagreement rate this is not perfectionism.

Rule 3, assert types, not values. assert isinstance(cfg['port'], int) beats asserting it equals 8080. A wrong type with the right value is still broken.

Writing a file back safely is its own problem — concurrent writers and atomic replacement are covered in file locking, measured across processes.

FAQ

Q: If I quote every value, will other services break?

Quoting changes the resolved tag, not the text. Go and Node parsers still read a quoted string as a string, so nothing gets worse. The real risk is code that relied on implicit booleans; those values must become explicit false.

Q: Is ruamel.yaml safer than PyYAML?

On duplicate keys, yes — it raises by default. But its 1.2 default brings new behaviour: 012 becomes 12 and 1e3 becomes a float. Switching libraries does not move you to "correct", it moves you to another rulebook. Re-run the comparison.

Q: Any known issues on Python 3.13?

Both libraries ran clean on CPython 3.13.14 here, installed into an isolated pip install --target directory. PyYAML 6.0.3 was released 2025-09-25, and its changelog for 6.0.2 records "Support for Cython 3.x and Python 3.13".

Q: Which other values get rewritten silently?

This run covers 19 literals. 0b11, 0x1f, 1_0, ~, .5 and 12. are also in the implicit resolution tables — both libraries agree on them, and none of them is the string you might assume. For anything else, check the Core Schema section on yaml.org, which is the authoritative table.

This article contains no affiliate links. Every behavioural difference above was measured on this machine; official wording is linked to its source.

👉 Join Xiaomi MiMo Platform: Leading AI model platform with cost-effective inference

👉 Join Aliyun AI: Top AI products with exclusive coupons for business innovation

📌 This article was AI-assisted generated and human-reviewed | TechPassive — An AI-driven content testing site focused on real tool reviews

🔗 Recommended Tools

These are carefully selected tools. Using our affiliate links supports us to keep producing quality content:

As an Amazon Associate, I earn from qualifying purchases at no extra cost to you.

☁️ DigitalOcean Cloud ⚡ Vultr VPS 🤖 QoderWork CN (Refer & Earn) ☁️ Aliyun AI Products 📚 WordPress Books 🧠 AI & LLM Books 🏗️ System Design Books 🐳 Docker & K8s Books 🐧 Linux Admin Books 🐍 Python Books 🗄️ Database Books 🚀 DevOps & SRE Books 🤖 Xiaomi MiMo Platform
← Back to Home