2

I have a function that uses a GeoPandas GeoDataFrame, which is a subclass of a Pandas DataFrame. GeoPandas' read_file() constructor can create either a GeoDataFrame or DataFrame instance, depending on options used, but my function needs a GeoDataFrame to work. I've tried to type hint this thusly:

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)

However, my type checker (Pylance in VS Code) reports that this isn't correct:

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

What's the proper way to hint that only a subset of the types read_file() can return are valid input to my_geographic_function()?

dericke
  • 290
  • 4
  • 13
  • Could you try doing `input_gdf: GeoDataFrame = gpd.read_file(...)` and tell me if that helps? – xjcl Nov 13 '20 at 01:13
  • Does this answer your question? [How to cast a typing.Union to one of its subtypes in Python?](https://stackoverflow.com/questions/44739764/how-to-cast-a-typing-union-to-one-of-its-subtypes-in-python) – Georgy Nov 13 '20 at 09:59

0 Answers0