omni-us / jsonargparse

Implement minimal boilerplate CLIs derived from type hints and parse from command line, config files and environment variables
https://jsonargparse.readthedocs.io
MIT License
319 stars 47 forks source link

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

Closed maticus closed 4 months ago

maticus commented 4 months ago

🐛 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

mauvilsa commented 4 months ago

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

mauvilsa commented 4 months ago

Fixed in #502.