Skip to content

format_usage() doesn't work on captured parser #501

@maticus

Description

@maticus

🐛 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions