Re:Python Type Hints – How to Handle Optional Imports
by dragonwriter on Wednesday January 05, 2022 @02:15AM
(#29806093)
The thing listed as “A Non-Functioning Alternative” seems to work correctly in both Pylance and mypy, if you add “# type: ignore” at the end of the import line.
[ Parent
| on HN ]
Re:Python Type Hints – How to Handle Optional Imports
by adamchainz on Thursday January 06, 2022 @10:36AM
(#29824841)
Unfortunately that prevents Mypy from loading the type hints for 'markdown'
from types import ModuleType
markdown: ModuleType | None
try:
import markdown # type: ignore [no-redef]
except ImportError:
markdown = None
if markdown is not None:
reveal_type(markdown.markdown)
Running Mypy: example.py:11: note: Revealed type is "Any"
Whereas when correctly imported: example.py:3: note: Revealed type is "def (text: builtins.str, *, extensions: Union[typing.Sequence[Union[builtins.str, markdown.extensions.Extension]], None] =, extension_configs: Union[typing.Mapping[builtins.str, typing.Mapping[builtins.str, Any]], None] =, output_format: Union[Literal['xhtml'], Literal['html'], None] =, tab_length: Union[builtins.int, None] =) -> builtins.str"