How to type hint without import

Viewed 283

Is it possible to hint a non-native type without importing the class it comes from?

For example, I have a function that requires a 'pandas.DataFrame' object and uses its 'index' method. In this case, it is useless to import 'pandas', yet I cannot declare my input without importing the latter since 'DataFrame' is not a native python type:

def foo(x: DataFrame):
    print(x.index)
1 Answers

Pyi stub files https://google.github.io/pytype/user_guide.html#pyi-stub-files

In some cases, it’s not possible to add annotations to a module by editing its source: C extension modules, external python source files, etc . For those cases, PEP 484 allows you to declare a module’s types in a separate “stub” file with a .pyi extension. Pyi files follow a subset of the python syntax and are analogous to header files in C (examples).

Related