Skip to content

Commit

Permalink
simplify _BaseObject, use registry
Browse files Browse the repository at this point in the history
  • Loading branch information
cleder committed Jun 19, 2024
1 parent 0a2e61d commit bed73f8
Show file tree
Hide file tree
Showing 9 changed files with 112 additions and 107 deletions.
100 changes: 0 additions & 100 deletions fastkml/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,103 +221,3 @@ def class_from_string(
config.etree.fromstring(string), # type: ignore[attr-defined]
),
)


class _BaseObject(_XMLObject):
"""
Base class for all KML objects.
This is an abstract base class and cannot be used directly in a
KML file. It provides the id attribute, which allows unique
identification of a KML element, and the targetId attribute,
which is used to reference objects that have already been loaded into
Google Earth. The id attribute must be assigned if the <Update>
mechanism is to be used.
"""

_default_ns = config.KMLNS

id = None
target_id = None

def __init__(
self,
ns: Optional[str] = None,
name_spaces: Optional[Dict[str, str]] = None,
id: Optional[str] = None,
target_id: Optional[str] = None,
**kwargs: Any,
) -> None:
"""Initialize the KML Object."""
super().__init__(ns=ns, name_spaces=name_spaces, **kwargs)
self.id = id
self.target_id = target_id

def __repr__(self) -> str:
"""Create a string (c)representation for _BaseObject."""
return (
f"{self.__class__.__module__}.{self.__class__.__name__}("
f"ns={self.ns!r}, "
f"name_spaces={self.name_spaces!r}, "
f"id={self.id!r}, "
f"target_id={self.target_id!r}, "
f"**kwargs={self._get_splat()!r},"
")"
)

def __eq__(self, other: object) -> bool:
"""Return True if the two objects are equal."""
try:
assert isinstance(other, type(self))
return (
super().__eq__(other)
and self.id == other.id
and self.target_id == other.target_id
)
except AssertionError:
return False

def etree_element(
self,
precision: Optional[int] = None,
verbosity: Verbosity = Verbosity.normal,
) -> Element:
"""Return the KML Object as an Element."""
element = super().etree_element(precision=precision, verbosity=verbosity)
if self.id:
element.set("id", self.id)
if self.target_id:
element.set("targetId", self.target_id)
return element

@classmethod
def _get_id(cls, element: Element, strict: bool) -> str:
return element.get("id") or ""

@classmethod
def _get_target_id(cls, element: Element, strict: bool) -> str:
return element.get("targetId") or ""

@classmethod
def _get_kwargs(
cls,
*,
ns: str,
name_spaces: Optional[Dict[str, str]] = None,
element: Element,
strict: bool,
) -> Dict[str, Any]:
"""Get the keyword arguments to build the object from an element."""
kwargs = super()._get_kwargs(
ns=ns,
name_spaces=name_spaces,
element=element,
strict=strict,
)
kwargs.update(
{
"id": cls._get_id(element=element, strict=strict),
"target_id": cls._get_target_id(element=element, strict=strict),
},
)
return kwargs
2 changes: 1 addition & 1 deletion fastkml/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
from typing import Union

from fastkml import config
from fastkml.base import _BaseObject
from fastkml.enums import DataType
from fastkml.exceptions import KMLSchemaError
from fastkml.helpers import attribute_enum_kwarg
Expand All @@ -40,6 +39,7 @@
from fastkml.helpers import text_subelement
from fastkml.helpers import xml_subelement_list
from fastkml.helpers import xml_subelement_list_kwarg
from fastkml.kml_base import _BaseObject
from fastkml.registry import RegistryItem
from fastkml.registry import registry

Expand Down
2 changes: 1 addition & 1 deletion fastkml/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
from fastkml import atom
from fastkml import config
from fastkml import gx
from fastkml.base import _BaseObject
from fastkml.base import _XMLObject
from fastkml.data import ExtendedData
from fastkml.geometry import AnyGeometryType
Expand All @@ -55,6 +54,7 @@
from fastkml.helpers import xml_subelement_kwarg
from fastkml.helpers import xml_subelement_list
from fastkml.helpers import xml_subelement_list_kwarg
from fastkml.kml_base import _BaseObject
from fastkml.links import Link
from fastkml.mixins import TimeMixin
from fastkml.registry import RegistryItem
Expand Down
2 changes: 1 addition & 1 deletion fastkml/geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
from typing_extensions import Self

from fastkml import config
from fastkml.base import _BaseObject
from fastkml.base import _XMLObject
from fastkml.enums import AltitudeMode
from fastkml.enums import Verbosity
Expand All @@ -51,6 +50,7 @@
from fastkml.helpers import xml_subelement_kwarg
from fastkml.helpers import xml_subelement_list
from fastkml.helpers import xml_subelement_list_kwarg
from fastkml.kml_base import _BaseObject
from fastkml.registry import RegistryItem
from fastkml.registry import known_types
from fastkml.registry import registry
Expand Down
105 changes: 105 additions & 0 deletions fastkml/kml_base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# Copyright (C) 2012 - 2024 Christian Ledermann
#
# This library is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

"""Abstract base classes."""
from typing import Any
from typing import Dict
from typing import Optional

from fastkml import config
from fastkml.base import _XMLObject
from fastkml.helpers import attribute_text_kwarg
from fastkml.helpers import text_attribute
from fastkml.registry import RegistryItem
from fastkml.registry import registry


class _BaseObject(_XMLObject):
"""
Base class for all KML objects.
This is an abstract base class and cannot be used directly in a
KML file. It provides the id attribute, which allows unique
identification of a KML element, and the targetId attribute,
which is used to reference objects that have already been loaded into
Google Earth. The id attribute must be assigned if the <Update>
mechanism is to be used.
"""

_default_ns = config.KMLNS

id = None
target_id = None

def __init__(
self,
ns: Optional[str] = None,
name_spaces: Optional[Dict[str, str]] = None,
id: Optional[str] = None,
target_id: Optional[str] = None,
**kwargs: Any,
) -> None:
"""Initialize the KML Object."""
super().__init__(ns=ns, name_spaces=name_spaces, **kwargs)
self.id = id
self.target_id = target_id

def __repr__(self) -> str:
"""Create a string (c)representation for _BaseObject."""
return (
f"{self.__class__.__module__}.{self.__class__.__name__}("
f"ns={self.ns!r}, "
f"name_spaces={self.name_spaces!r}, "
f"id={self.id!r}, "
f"target_id={self.target_id!r}, "
f"**kwargs={self._get_splat()!r},"
")"
)

def __eq__(self, other: object) -> bool:
"""Return True if the two objects are equal."""
try:
assert isinstance(other, type(self))
return (
super().__eq__(other)
and self.id == other.id
and self.target_id == other.target_id
)
except AssertionError:
return False


registry.register(
_BaseObject,
item=RegistryItem(
attr_name="id",
node_name="id",
classes=(str,),
get_kwarg=attribute_text_kwarg,
set_element=text_attribute,
),
)

registry.register(
_BaseObject,
item=RegistryItem(
attr_name="target_id",
node_name="targetId",
classes=(str,),
get_kwarg=attribute_text_kwarg,
set_element=text_attribute,
),
)
2 changes: 1 addition & 1 deletion fastkml/links.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
from typing import Dict
from typing import Optional

from fastkml.base import _BaseObject
from fastkml.enums import RefreshMode
from fastkml.enums import ViewRefreshMode
from fastkml.helpers import enum_subelement
Expand All @@ -27,6 +26,7 @@
from fastkml.helpers import subelement_float_kwarg
from fastkml.helpers import subelement_text_kwarg
from fastkml.helpers import text_subelement
from fastkml.kml_base import _BaseObject
from fastkml.registry import RegistryItem
from fastkml.registry import registry

Expand Down
2 changes: 1 addition & 1 deletion fastkml/styles.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
from typing import Union

from fastkml import config
from fastkml.base import _BaseObject
from fastkml.base import _XMLObject
from fastkml.enums import ColorMode
from fastkml.enums import DisplayMode
Expand All @@ -53,6 +52,7 @@
from fastkml.helpers import xml_subelement_kwarg
from fastkml.helpers import xml_subelement_list
from fastkml.helpers import xml_subelement_list_kwarg
from fastkml.kml_base import _BaseObject
from fastkml.links import Icon
from fastkml.registry import RegistryItem
from fastkml.registry import registry
Expand Down
2 changes: 1 addition & 1 deletion fastkml/times.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@
import arrow

from fastkml import config
from fastkml.base import _BaseObject
from fastkml.enums import DateTimeResolution
from fastkml.enums import Verbosity
from fastkml.kml_base import _BaseObject
from fastkml.types import Element

# regular expression to parse a gYearMonth string
Expand Down
2 changes: 1 addition & 1 deletion fastkml/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
from typing import Union

from fastkml import config
from fastkml.base import _BaseObject
from fastkml.base import _XMLObject
from fastkml.enums import AltitudeMode
from fastkml.helpers import enum_subelement
Expand All @@ -30,6 +29,7 @@
from fastkml.helpers import subelement_float_kwarg
from fastkml.helpers import xml_subelement
from fastkml.helpers import xml_subelement_kwarg
from fastkml.kml_base import _BaseObject
from fastkml.mixins import TimeMixin
from fastkml.registry import RegistryItem
from fastkml.registry import registry
Expand Down

0 comments on commit bed73f8

Please sign in to comment.