HOW-TO

Safe Loading

Safe Loading

See also: API: laco.load / LoadMode, Concepts: Config as Python

When to Use Safe Loading

Config files are Python code. If you load configs from an untrusted source (external contributor, downloaded dataset config, CI artefact), a malicious config could import os and call os.system. LoadMode.SAFE prevents this.

Basic Usage

import laco

cfg = laco.load("external_config.py", mode=laco.LoadMode.SAFE)

What LoadMode.SAFE Removes

  • Dangerous builtins: open, eval, exec, compile, globals, locals, breakpoint
  • All module imports not in the allowlist

Attempting to use a forbidden builtin raises NameError; importing a disallowed module raises ImportError.

Default Allowlist

laco.DEFAULT_SAFE_ALLOWED_MODULES
# ("laco", "omegaconf", "torch", "torch.nn")

A module name N is allowed if N == entry or N.startswith(entry + ".") for any entry in the allowlist. So "torch" in the allowlist permits import torch.nn.functional.

Widening the Allowlist

cfg = laco.load(
    "external_config.py",
    mode=laco.LoadMode.SAFE,
    allowed_modules=(*laco.DEFAULT_SAFE_ALLOWED_MODULES, "numpy", "my_project"),
)

YAML Files

YAML configs loaded with LoadMode.SAFE apply the same allowlist to !!python/name:module.Class tags. Class references that resolve outside the allowlist are rejected.

Default Mode

LoadMode.NORMAL (the default) applies no allowlist and preserves all builtins. Use it for configs you author and control.