如何键入提示 a class 未被模块公开

How to type hint a class not exposed by a module

我在我的代码中使用了一个名为 pyathena 的模块,并且我有一个接收 pyathena connection:

的函数
import pyathena

def fn(conn) -> None:
    <DO SOMETHING>

conn = pyathena.connect(s3_staging_dir=f's3://<THE_BUCKET>/', region_name=<REGION>)

fn(conn)

我想输入提示 fnconn 参数。

我知道 conn 是 pyathena.connection.Connection 类型,但是做

def fn(conn: pyathena.connection.Connection) -> None:
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

无效: AttributeError: module 'pyathena' has no attribute 'connection'.

正在做

from pyathena.connection import Connection

def fn(conn: Connection):
    ...

似乎工作得很好,但我不想在我的代码中公开这个 Connection class,除了进行类型提示。

问:有没有一种方法可以在我的代码中输入 hint this unexposed class 而不必像上面那样导入?

有用参考:https://github.com/laughingman7743/PyAthena/blob/master/pyathena/init.py

别名怎么样?

from pyathena.connection import Connection as _Con

def fn(conn: _Con):
    ...

使用deferred annotations:

from __future__ import annotations
import pyathena


def fn(conn: pyathena.connection.Connection) -> None:
    ...

注释实际上被视为字符串文字。如果您觉得这会过度损害类型安全性(例如,因为您可能会拼错类型),您可以改用 typing.TYPE_CHECKING

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from pyathena.connection import Connection
else:
    Connection = '...'


def fn(conn: Connection) -> None:
    ...