Declare the optional dependency and then import it unconditionally if the optional is installed. You can conditionally import a file you control based on asking whether an optional specifier was installed, either by probing the filesystem, a CLI argument, an environment variable, or whatever folks come up with for https://github.com/pypa/packaging-problems/issues/215. The "if: ... import" laziness-defeating clause only applies to your stub module, and the imports in that module are unconditional and thus will work with analyzers/laziness/etc.
Comments
I don't understand, sorry. How does declaring an optional dependency in a toml file solve the problem of accessing the symbol in your code?
Also, you need something that works for simple one-file scripts, not just a whole package or project.
Declare the optional dependency and then import it unconditionally if the optional is installed. You can conditionally import a file you control based on asking whether an optional specifier was installed, either by probing the filesystem, a CLI argument, an environment variable, or whatever folks come up with for https://github.com/pypa/packaging-problems/issues/215. The "if: ... import" laziness-defeating clause only applies to your stub module, and the imports in that module are unconditional and thus will work with analyzers/laziness/etc.
If you need something for one-off scripts, use https://docs.astral.sh/uv/guides/scripts/.