Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 474
imbolc Avatar asked Dec 23 '22 18:12

imbolc


1 Answers

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.

like image 76
imbolc Avatar answered Jan 26 '23 18:01

imbolc