Slava
Slava

Reputation: 425

How to import class for type hints in Python?

I have a code as:

from pandas import DataFrame
def func(df: DataFrame) -> DataFrame
    ...

Since I don't actually create a DataFrame object in my code I wanted to do:

from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from pandas import DataFrame
def func(df: DataFrame) -> DataFrame
    ...

This raises error:

E   NameError: name 'DataFrame' is not defined

How can I solve it? Must I stay with the original import? It makes little sense to me to import a package that my code isn't really required but only for hints

Upvotes: 5

Views: 1306

Answers (1)

chepner
chepner

Reputation: 531808

You'll want to use from __future__ import annotations so that no attempt is made to evaluate the expression at run-time; the annotations will be treated as implicitly quoted strings instead.

Upvotes: 2

Related Questions