Skip to content

Commit

Permalink
Refactor create_kml_geometry function to handle unknown geometry types
Browse files Browse the repository at this point in the history
  • Loading branch information
cleder committed Oct 26, 2024
1 parent c622c87 commit 137a5a1
Showing 1 changed file with 26 additions and 6 deletions.
32 changes: 26 additions & 6 deletions fastkml/geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,11 @@
from typing import Final
from typing import Iterable
from typing import List
from typing import NoReturn
from typing import Optional
from typing import Sequence
from typing import Tuple
from typing import Type
from typing import Union
from typing import cast

Expand Down Expand Up @@ -1432,6 +1434,23 @@ def geometry(self) -> Optional[MultiGeometryType]:
KMLGeometryType = Union[Point, LineString, Polygon, LinearRing, MultiGeometry]


def _unknown_geometry_type(geometry: Union[GeoType, GeoCollectionType]) -> NoReturn:
"""
Raise an error for an unknown geometry type.
Args:
----
geometry: The geometry object.
Raises:
------
KMLWriteError: If the geometry type is unknown.
"""
msg = f"Unsupported geometry type {type(geometry)}" # pragma: no cover
raise KMLWriteError(msg) # pragma: no cover


def create_kml_geometry(
geometry: Union[GeoType, GeoCollectionType],
*,
Expand Down Expand Up @@ -1463,7 +1482,10 @@ def create_kml_geometry(
KML geometry object.
"""
_map_to_kml = {
_map_to_kml: Dict[
Union[Type[GeoType], Type[GeoCollectionType]],
Type[KMLGeometryType],
] = {
geo.Point: Point,
geo.Polygon: Polygon,
geo.LinearRing: LinearRing,
Expand All @@ -1476,17 +1498,15 @@ def create_kml_geometry(
geom = shape(geometry)
for geometry_class, kml_class in _map_to_kml.items():
if isinstance(geom, geometry_class):
return kml_class( # type: ignore[no-any-return]
return kml_class(
ns=ns,
name_spaces=name_spaces,
id=id,
target_id=target_id,
extrude=extrude,
tessellate=tessellate,
altitude_mode=altitude_mode,
geometry=geom,
geometry=geom, # type: ignore[arg-type]
)

# this should be unreachable, but mypy doesn't know that
msg = f"Unsupported geometry type {type(geometry)}" # pragma: no cover
raise KMLWriteError(msg) # pragma: no cover
_unknown_geometry_type(geometry)

0 comments on commit 137a5a1

Please sign in to comment.