1

How can the type hint be defined to still designate GeoPandas GeoDataFrame as an option but not error when Geopandas is not imported? IE: define a type hint without the module present

Given a class which takes a param typed as a DataFrame or a GeoDataFrame, often only Pandas will be imported, but occasionally GeoPandas will be as well.

The class must be able to take a frame from either interchangeably. If the param is defined as:Union[pandas.Dataframe, geopandas.geodataframe.GeoDataFrame] an error will occur when GeoPandas has not been imported, and vice versa. Pandas or Geopandas would not be imported solely for the purposes of a type hint.

Any is an option to define geopandas dataframe, however I hoped to be more concise. Union[pandas.Dataframe, Any] feels meaningless because it does not supply context as to what type the alternative parameter might be and doesn't cover the case if Geopandas is loaded and not Pandas.

I have reviewed How to type hint with an optional import? but it is not the same situation.

Liquidgenius
  • 639
  • 5
  • 17
  • 32

1 Answers1

2

Assuming Python >= 3.7, add a from __future__ import annotations import in order to postpone type hint evaluation. This means that the interpreter won't actually complain if you refer to an unloaded object in a type hint.

The following code executes just fine without needing any additional imports:

from __future__ import annotations
from typing import Union


def main(data: Union[str, pd.DataFrame]) -> None:
    print(data)


if __name__ == '__main__':
    main('some_data_here')

This behavior was meant to be default starting with Python 3.10, meaning we wouldn't need the future import, but it has been postponed to Python 3.11.

(also, note that you don't technically need to use Union[pandas.Dataframe, geopandas.geodataframe.GeoDataFrame] - type hinting with DataFrame is enough, since a GeoDataFrame is an instance of a DataFrame).

jfaccioni
  • 7,099
  • 1
  • 9
  • 25