jsonargparse
jsonargparse copied to clipboard
How to dynamically import packages?
I'm designing a package that have main functionality and optional functionality that requires extra packages to be installed. I want to build a CLI for the package. jsonargparse dissuades use of parse_known_args(), so I cannot import packages only when needed.
For example, I want to add optional function arguments. I cannot use parser.add_function_args because it would need me to import the function. I must add arguments manually, but I can't always do this, because some arguments may depend on classes in my optional functionality. How to manage this case? Thank you
I cannot use
parser.add_function_argsbecause it would need me to import the function.
You could do like:
if optional_package_available:
import optional_package
...
if optional_package_available:
parser.add_function_args(optional_package.some_function, ...)
I can't always do this, because some arguments may depend on classes in my optional functionality
Not really sure what you mean by this.
Yes, but if I try to run a command with arguments, it won't recognize them and exit, and the only way to show a message about installing additional packages, as I understand, is to catch SystemExit, which I think is not the most elegant solution.
I guess what you need is an Action that always raises an argument exception with some message. But this action must be triggered if nested arguments are given. That is, something like:
if optional_package_available:
from optional_package import some_function
...
if optional_package_available:
parser.add_function_arguments(some_function, "group")
else:
parser.add_argument("--group", action=ActionNotAvaliable("please install optional_package"))
The CLI would exit with the given message if any option --group.* is given. This action would be useful for the case of optional packages, but also for deprecated options that were removed.
jsonargparse internally importing optional packages, I am not sure it is a good idea.