pythonpython-typingmypypypi

Python typing - is there a way to avoid importing of optional type if it's None?


Let's say we have a function definition like this:

def f(*, model: Optional[Type[pydantic.BaseModel]] = None)

So the function doesn't require pydantic to be installed until you pass something as a model. Now let's say we want to pack the function into pypi package. And my question is if there's a way to avoid bringing pydantic into the package dependencies only the sake of type checking?


Solution

  • I tried to follow dspenser's advice, but I found mypy still giving me Name 'pydantic' is not defined error. Then I found this chapter in the docs and it seems to be working in my case too:

    from typing import TYPE_CHECKING
    
    if TYPE_CHECKING:
        import pydantic
    

    You can use normal clases (instead of string literals) with __future__.annotations (python 3.8.1):

    from __future__ import annotations
    
    from typing import TYPE_CHECKING, Optional, Type
    
    if TYPE_CHECKING:
        import pydantic
    
    
    def f(*, model: Optional[Type[pydantic.BaseModel]] = None):
        pass
    

    If for some reason you can't use __future__.annotations, e.g. you're on python < 3.7, use typing with string literals from dspenser's solution.