facebookresearch/detectron2 · error · SyntaxError

Config file {filename} has syntax error!

Error message

Config file {filename} has syntax error!

What it means

Before executing a Python config file, detectron2 parses it with ast.parse to give a friendlier error. A SyntaxError from the file (bad indentation, unclosed bracket, Python-2 style print) is re-raised as this message with the original error chained.

Source

Thrown at detectron2/config/lazy.py:81

    Apply func recursively to all DictConfig in cfg.
    """
    if isinstance(cfg, DictConfig):
        func(cfg)
        for v in cfg.values():
            _visit_dict_config(v, func)
    elif isinstance(cfg, ListConfig):
        for v in cfg:
            _visit_dict_config(v, func)


def _validate_py_syntax(filename):
    # see also https://github.com/open-mmlab/mmcv/blob/master/mmcv/utils/config.py
    with PathManager.open(filename, "r") as f:
        content = f.read()
    try:
        ast.parse(content)
    except SyntaxError as e:
        raise SyntaxError(f"Config file {filename} has syntax error!") from e


def _cast_to_config(obj):
    # if given a dict, return DictConfig instead
    if isinstance(obj, dict):
        return DictConfig(obj, flags={"allow_objects": True})
    return obj


_CFG_PACKAGE_NAME = "detectron2._cfg_loader"
"""
A namespace to put all imported config into.
"""


def _random_package_name(filename):
    # generate a random package name when loading config files
    return _CFG_PACKAGE_NAME + str(uuid.uuid4())[:4] + "." + os.path.basename(filename)

View on GitHub (pinned to a2f4a8771a)

Solutions

  1. Run python -m py_compile my_cfg.py to see the exact line/column of the syntax error
  2. Fix the reported syntax error in the config file
  3. If using new syntax, upgrade Python or rewrite the construct compatibly

Example fix

# before (my_cfg.py)
model = dict(target="..."  # missing closing paren
# after
model = dict(target="...")
Defensive patterns

Strategy: validation

Validate before calling

import ast
src = open(cfg_path).read()
try:
    ast.parse(src)
except SyntaxError as e:
    raise SystemExit(f"fix config first: {e}")

Try / catch

try:
    cfg = LazyConfig.load(path)
except SyntaxError as e:
    if "has syntax error" in str(e) and e.__cause__:
        print("line", e.__cause__.lineno, "col", e.__cause__.offset)
    raise

Prevention

When it happens

Trigger: Calling fvcore/detectron2 LazyConfig.load('my_cfg.py') where the file fails to compile: unterminated string, missing colon after if, invalid syntax for the running Python version.

Common situations: Editing configs by hand or via sed and breaking syntax; configs written for a newer Python version (e.g. match statements under 3.10); generated configs with truncated lines.

Related errors


AI-assisted analysis of facebookresearch/detectron2@a2f4a8771a (2026-08-27). Data as JSON: /api/errors/4e76ae4eacf725a7. Report an issue: GitHub.