-
Notifications
You must be signed in to change notification settings - Fork 13
Description
Disclaimer: my understanding of this library is limited. I did not go through all of the code.
When debugging in vscode, we generally want the execution to pause on any "unhandled exceptions".
At this time, when using pydantic_cli, the debugger does not work this way.
A solution is to set an exception_handler
that simply raises the exception.
Here is a script to explain:
import sys
from pydantic import BaseModel
from pydantic_cli import run_and_exit, to_runner
class CliModel(BaseModel):
a: int = 123
def exception_handler(ex: BaseException):
raise ex
def main(c: CliModel):
raise Exception('Execution should stop at this line with vscode and "unhandled exceptions"')
if __name__ == "__main__":
# BAD: Pauses the debugger in pydantic_cli.run_and_exit. Exception has occurred: SystemExit
run_and_exit(CliModel, main)
# BAD: Ends the program without pausing the debugger.
to_runner(CliModel, main)(sys.argv[1:])
# GOOD: Works as intended. Debugger stops in main() on the unhandled exception
to_runner(CliModel, main, exception_handler=exception_handler)(sys.argv[1:])
This is an issue that could bother many users.
In my opinion, the default exception_handler should simply re-raise the exception.
This issue could also simply be addressed in the readme.
I really think you guys are on the right track with pydantic_cli. Thanks!
edit: I realize an easy way to solve this is to make public a function that simply parses sys.argv[1:] and returns an instance of the pydantic model. I would only use this function. Something like this:
import sys
from pydantic_cli import parse_argv_to_model_instance
def main(c: CliModel, *args, **kwargs):
# do something
return
if __name__ == "__main__":
c: CliModel = parse_argv_to_model_instance(CliModel, sys.argv[1:])
main(c)