首页 > 解决方案 > 如何键入仅使用构造函数可能返回类型的子集的函数?

问题描述

我有一个使用 GeoPandas 的函数GeoDataFrame,它是 Pandas 的子类DataFrame。GeoPandas 的read_file()构造函数可以创建 aGeoDataFrameDataFrame实例,具体取决于使用的选项,但我的函数需要 aGeoDataFrame才能工作。我试图这样输入提示:

import geopandas as gpd
from geopandas.geodataframe import GeoDataFrame


def my_geographic_function(input_gdf: GeoDataFrame) -> Set[Tuple[int, int]]:
    # do stuff
    return the_result
    

input_gdf = gpd.read_file("my_input_file.geojson")
result = my_geographic_function(input_gdf)

但是,我的类型检查器(VS Code 中的 Pylance)报告说这是不正确的:

Argument of type "DataFrame | GeoDataFrame" cannot be assigned to parameter "input_gdf" of type "GeoDataFrame" in function "my_geographic_function"

提示只有类型的子集read_file()可以返回是有效输入的正确方法是my_geographic_function()什么?

标签: pythontype-hintingtypechecking

解决方案


推荐阅读