omni-us / jsonargparse

Implement minimal boilerplate CLIs derived from type hints and parse from command line, config files and environment variables

Home Page:https://jsonargparse.readthedocs.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`format_usage()` doesn't work on captured parser

maticus opened this issue Β· comments

πŸ› Bug report

jsonargparse.capture_parser(main).format_usage() fails with
LookupError: <ContextVar name='parent_parser' at 0x7f0859cb54e0>

To reproduce

import jsonargparse

def fun(a: int):
    pass

def main():
    jsonargparse.CLI(fun)

# THIS IS OK
jsonargparse.capture_parser(main).print_usage()

# THIS FAILS
print(jsonargparse.capture_parser(main).format_usage())

Output:

$ python python-jsonargparse-format-usage.py 
usage: python-jsonargparse-format-usage.py [-h] [--config CONFIG] [--print_config[=flags]] a
Traceback (most recent call last):
  File "/home/mati/tests/python-jsonargparse-format-usage.py", line 12, in <module>
    print(jsonargparse.capture_parser(main).format_usage())
  File "/usr/lib/python3.10/argparse.py", line 2540, in format_usage
    return formatter.format_help()
  File "/usr/lib/python3.10/argparse.py", line 295, in format_help
    help = self._root_section.format_help()
  File "/usr/lib/python3.10/argparse.py", line 226, in format_help
    item_help = join([func(*args) for func, args in self.items])
  File "/usr/lib/python3.10/argparse.py", line 226, in <listcomp>
    item_help = join([func(*args) for func, args in self.items])
  File "/home/mati/.local/lib/python3.10/site-packages/jsonargparse/_formatters.py", line 90, in _format_usage
    parser = parent_parser.get()
LookupError: <ContextVar name='parent_parser' at 0x7f2efed7c130>

Expected behavior

Should print same thing in both cases.

Environment

  • jsonargparse version: 4.28.0
  • Python version: 3.10.12
  • How jsonargparse was installed: pip install jsonargparse
  • OS (e.g., Linux): Ubuntu Jammy

Thank you for reporting! The same happens with normal parsers, so not really related to capture_parser.