API Reference

gpx.gpx Module

GPX model for GPX data.

This module provides the GPX model representing the root GPX document, following the GPX 1.1 specification.

gpx.gpx.GPX_NAMESPACE = 'http://www.topografix.com/GPX/1/1'

GPX 1.1 namespace

gpx.gpx.XSI_NAMESPACE = 'http://www.w3.org/2001/XMLSchema-instance'

XML Schema instance namespace

class gpx.gpx.GPX(creator='https://github.com/sgraaf/gpx', *, metadata=None, wpt=<factory>, rte=<factory>, trk=<factory>)

Bases: GPXModel

The root GPX document.

GPX documents contain a metadata header, followed by waypoints, routes, and tracks. You can add your own elements to the extensions section of the GPX document.

Note: The GPX version is always “1.1” per the specification and is automatically set during XML serialization.

Parameters:
  • creator (str) – The name or URL of the software that created the GPX document. Defaults to “https://github.com/sgraaf/gpx”.

  • metadata (Metadata | None) – Metadata about the file. Defaults to None.

  • wpt (list[Waypoint]) – List of waypoints. Defaults to empty list.

  • rte (list[Route]) – List of routes. Defaults to empty list.

  • trk (list[Track]) – List of tracks. Defaults to empty list.

to_xml(tag=None, nsmap=None)

Convert the GPX to an XML element.

Parameters:
  • tag (str | None) – The XML tag name. Defaults to “gpx”.

  • nsmap (dict[str | None, str] | None) – Optional namespace mapping. Defaults to GPX 1.1 namespace with XML Schema instance namespace.

Returns:

The XML element.

Return type:

Element

to_string(*, pretty_print=True)

Serialize the GPX instance to a string.

Parameters:

pretty_print (bool) – Whether to format the output with indentation. Defaults to True.

Returns:

The GPX data as a string.

Return type:

str

Example

>>> from gpx import GPX
>>> gpx = GPX(creator="MyApp")
>>> xml_string = gpx.to_string()
>>> print(xml_string[:50])
<?xml version='1.0' encoding='UTF-8'?>
<gpx ve
write_gpx(file_path, *, pretty_print=True)

Write the GPX to a file.

Parameters:
  • file_path (str | Path) – The file path to write the GPX data to.

  • pretty_print (bool) – Whether to format the output with indentation. Defaults to True.

Example

>>> from gpx import GPX
>>> gpx = GPX(creator="MyApp")
>>> gpx.write_gpx("output.gpx")
write_geojson(file_path, *, indent=2)

Write the GPX to a GeoJSON file.

Parameters:
  • file_path (str | Path) – The file path to write the GeoJSON data to.

  • indent (int | None) – Indentation level for pretty printing. Defaults to 2.

Example

>>> from gpx import GPX
>>> gpx = GPX()
>>> gpx.write_geojson("output.geojson")
write_kml(file_path, *, pretty_print=True)

Write the GPX to a KML file.

Parameters:
  • file_path (str | Path) – The file path to write the KML data to.

  • pretty_print (bool) – Whether to format the output with indentation. Defaults to True.

Example

>>> from gpx import GPX
>>> gpx = GPX()
>>> gpx.write_kml("output.kml")
to_wkt()

Convert the GPX to a WKT (Well-Known Text) string.

Returns a GeometryCollection containing all waypoints, routes, and tracks.

Returns:

A WKT string representation of the GPX data.

Return type:

str

Example

>>> from gpx import GPX, Waypoint
>>> from decimal import Decimal
>>> gpx = GPX(wpt=[Waypoint(Decimal("52.0"), Decimal("4.0"))])
>>> print(gpx.to_wkt())
GEOMETRYCOLLECTION (POINT (4.0 52.0))
to_wkb(*, byte_order='little')

Convert the GPX to WKB (Well-Known Binary).

Returns a GeometryCollection containing all waypoints, routes, and tracks.

Parameters:

byte_order (str) – Byte order for the binary data. Either “little” (NDR) or “big” (XDR). Defaults to “little”.

Returns:

WKB bytes representation of the GPX data.

Return type:

bytes

Example

>>> from gpx import GPX, Waypoint
>>> from decimal import Decimal
>>> gpx = GPX(wpt=[Waypoint(Decimal("52.0"), Decimal("4.0"))])
>>> wkb = gpx.to_wkb()

gpx.convert Module

Conversion functions for converting data formats to GPX.

This module provides functions for converting from GeoJSON-like objects, WKB, and WKT data formats to GPX objects.

gpx.convert.WKB_POINT = 1

WKB geometry type codes

gpx.convert.WKB_Z_FLAG = 1000

Z dimension flag (add to base type for 3D)

gpx.convert.EWKB_Z_FLAG = 2147483648

EWKB Z flag (high bit)

gpx.convert.from_string(gpx_str)

Create a GPX instance from a string.

Parameters:

gpx_str (str) – The string containing the GPX data.

Returns:

The GPX instance.

Return type:

GPX

Example

>>> from gpx import from_string
>>> gpx = from_string('''<?xml version="1.0"?>
... <gpx version="1.1" creator="MyApp">
...     <metadata><name>My Track</name></metadata>
... </gpx>''')
>>> print(gpx.creator)
MyApp
gpx.convert.from_geo_interface(geo, *, creator=None)

Convert a GeoJSON-like object (with __geo_interface__ property) to GPX.

This function supports Python objects that implement the __geo_interface__ protocol (e.g., Shapely geometries) as well as raw GeoJSON dictionaries.

Parameters:
  • geo (dict[str, Any] | SupportsGeoInterface) – A dictionary with GeoJSON structure or an object with __geo_interface__ property.

  • creator (str | None) – The creator string for the GPX. Defaults to None (uses default).

Returns:

A GPX object.

Raises:

ValueError – If the geometry type is not supported.

Return type:

GPX

Example

>>> from shapely.geometry import Point
>>> from gpx import from_geo_interface
>>> point = Point(4.0, 52.0)
>>> gpx = from_geo_interface(point)
gpx.convert.from_wkb(wkb, *, creator=None)

Convert Well-Known Binary (WKB) to GPX.

Supports both standard WKB and EWKB (Extended WKB) with Z coordinates.

Parameters:
  • wkb (bytes) – WKB as bytes.

  • creator (str | None) – The creator string for the GPX. Defaults to None (uses default).

Returns:

A GPX object.

Raises:

ValueError – If the WKB format is invalid or geometry type is unsupported.

Return type:

GPX

Example

>>> from gpx import from_wkb
>>> # WKB for POINT(4.0 52.0)
>>> wkb = bytes.fromhex("0101000000000000000000104000000000004a4a40")
>>> gpx = from_wkb(wkb)
gpx.convert.from_wkt(wkt, *, creator=None)

Convert Well-Known Text (WKT) to GPX.

Parameters:
  • wkt (str) – WKT string.

  • creator (str | None) – The creator string for the GPX. Defaults to None (uses default).

Returns:

A GPX object.

Raises:

ValueError – If the WKT format is invalid or geometry type is unsupported.

Return type:

GPX

Example

>>> from gpx import from_wkt
>>> gpx = from_wkt("POINT (4.0 52.0)")

gpx.io Module

I/O functions for reading file formats into GPX.

This module provides functions for reading GPX, GeoJSON, and KML files from disk and returning GPX objects.

gpx.io.KML_NAMESPACE = 'http://www.opengis.net/kml/2.2'

KML namespace

gpx.io.read_gpx(file_path)

Read a GPX file and return a GPX object.

Parameters:

file_path (str | Path) – Path to the GPX file.

Returns:

A GPX object.

Return type:

GPX

Example

>>> from gpx import read_gpx
>>> gpx = read_gpx("path/to/file.gpx")
gpx.io.read_geojson(file_path, *, creator=None)

Read a GeoJSON file and return a GPX object.

Parameters:
  • file_path (str | Path) – Path to the GeoJSON file.

  • creator (str | None) – The creator string for the GPX. Defaults to None (uses default).

Returns:

A GPX object.

Return type:

GPX

Example

>>> from gpx import read_geojson
>>> gpx = read_geojson("path/to/file.geojson")
gpx.io.read_kml(file_path, *, creator=None)

Read a KML file and return a GPX object.

Parameters:
  • file_path (str | Path) – Path to the KML file.

  • creator (str | None) – The creator string for the GPX. Defaults to None (uses default).

Returns:

A GPX object.

Return type:

GPX

Example

>>> from gpx import read_kml
>>> gpx = read_kml("path/to/file.kml")

gpx.base Module

Base class for GPX dataclass models.

This module provides the base class that all GPX dataclass models inherit from, implementing common XML parsing and serialization logic.

gpx.base.GPX_NAMESPACE = 'http://www.topografix.com/GPX/1/1'

GPX 1.1 namespace

class gpx.base.GPXModel

Bases: object

Base class for GPX dataclass models.

Provides common XML parsing and serialization methods. Subclasses must define the _tag class attribute to specify the default XML tag name.

_tag

The default XML tag name for this model.

Type:

ClassVar[str]

classmethod from_xml(element)

Parse the model from an XML element.

Parameters:

element (Element) – The XML element to parse.

Returns:

The parsed model instance.

Raises:

ValueError – If required attributes are missing.

Return type:

Self

to_xml(tag=None, nsmap=None)

Convert the model to an XML element.

Parameters:
  • tag (str | None) – The XML tag name. Defaults to the model’s _tag attribute.

  • nsmap (dict[str | None, str] | None) – Optional namespace mapping. Defaults to GPX 1.1 namespace.

Returns:

The XML element.

Return type:

Element

gpx.metadata Module

Metadata model for GPX data.

This module provides the Metadata model containing information about the GPX file, author, and copyright restrictions, following the GPX 1.1 specification.

class gpx.metadata.Metadata(*, name=None, desc=None, author=None, copyright=None, link=<factory>, time=None, keywords=None, bounds=None)

Bases: GPXModel

Information about the GPX file, author, and copyright restrictions.

Providing rich, meaningful information about your GPX files allows others to search for and use your GPS data.

Parameters:
  • name (str | None) – The name of the GPX file. Defaults to None.

  • desc (str | None) – A description of the contents of the GPX file. Defaults to None.

  • author (Person | None) – The person or organization who created the GPX file. Defaults to None.

  • copyright (Copyright | None) – Copyright and license information governing use of the file. Defaults to None.

  • link (list[Link]) – URLs associated with the location described in the file. Defaults to empty list.

  • time (datetime | None) – The creation date of the file. Defaults to None.

  • keywords (str | None) – Keywords associated with the file. Search engines or databases can use this information to classify the data. Defaults to None.

  • bounds (Bounds | None) – Minimum and maximum coordinates which describe the extent of the coordinates in the file. Defaults to None.

gpx.waypoint Module

Waypoint model for GPX data.

This module provides the Waypoint model representing a waypoint, point of interest, or named feature on a map, following the GPX 1.1 specification.

class gpx.waypoint.Waypoint(lat, lon, *, ele=None, time=None, magvar=None, geoidheight=None, name=None, cmt=None, desc=None, src=None, link=<factory>, sym=None, type=None, fix=None, sat=None, hdop=None, vdop=None, pdop=None, ageofdgpsdata=None, dgpsid=None)

Bases: GPXModel

A waypoint, point of interest, or named feature on a map.

Parameters:
  • lat (Latitude) – Latitude of the point in decimal degrees, WGS84 datum.

  • lon (Longitude) – Longitude of the point in decimal degrees, WGS84 datum.

  • ele (Decimal | None) – Elevation (in meters) of the point. Defaults to None.

  • time (datetime | None) – Creation/modification timestamp for element (dt.UTC). Defaults to None.

  • magvar (Degrees | None) – Magnetic variation (in degrees) at the point. Defaults to None.

  • geoidheight (Decimal | None) – Height (in meters) of geoid (mean sea level) above WGS84 earth ellipsoid. Defaults to None.

  • name (str | None) – GPS name of the waypoint. Defaults to None.

  • cmt (str | None) – GPS waypoint comment. Defaults to None.

  • desc (str | None) – Text description of the element. Defaults to None.

  • src (str | None) – Source of data. Defaults to None.

  • link (list[Link]) – Links to additional information about the waypoint. Defaults to empty list.

  • sym (str | None) – Text of GPS symbol name. Defaults to None.

  • type (str | None) – Type (classification) of the waypoint. Defaults to None.

  • fix (Fix | None) – Type of GPX fix. Defaults to None.

  • sat (int | None) – Number of satellites used to calculate the GPX fix. Defaults to None.

  • hdop (Decimal | None) – Horizontal dilution of precision. Defaults to None.

  • vdop (Decimal | None) – Vertical dilution of precision. Defaults to None.

  • pdop (Decimal | None) – Position dilution of precision. Defaults to None.

  • ageofdgpsdata (Decimal | None) – Number of seconds since last DGPS update. Defaults to None.

  • dgpsid (DGPSStation | None) – ID of DGPS station used in differential correction. Defaults to None.

distance_to(other, radius=6378137)

Return the distance to another waypoint using the haversine formula.

Uses a simple spherical earth model (haversine formula).

Parameters:
  • other (Waypoint) – The other waypoint.

  • radius (int) – The radius of the earth. Defaults to 6,378,137 metres.

Returns:

The distance to the other waypoint (in metres).

Return type:

float

duration_to(other)

Return the duration to another waypoint.

Parameters:

other (Waypoint) – The other waypoint.

Returns:

The duration to the other waypoint. Returns zero dt.timedelta if either waypoint lacks a timestamp.

Return type:

timedelta

speed_to(other)

Return the speed to another waypoint.

Parameters:

other (Waypoint) – The other waypoint.

Returns:

The speed to the other waypoint (in metres per second).

Return type:

float

gain_to(other)

Return the elevation gain to another waypoint.

Parameters:

other (Waypoint) – The other waypoint.

Returns:

The elevation gain to the other waypoint (in metres). Returns zero if either waypoint lacks elevation data.

Return type:

Decimal

slope_to(other)

Return the slope to another waypoint.

Parameters:

other (Waypoint) – The other waypoint.

Returns:

The slope to the other waypoint (in percent).

Return type:

Decimal

gpx.route Module

Route model for GPX data.

This module provides the Route model representing an ordered list of waypoints representing a series of turn points leading to a destination, following the GPX 1.1 specification.

class gpx.route.Route(*, name=None, cmt=None, desc=None, src=None, link=<factory>, number=None, type=None, rtept=<factory>)

Bases: GPXModel

An ordered list of waypoints representing a series of turn points.

A route represents waypoints leading to a destination.

Parameters:
  • name (str | None) – GPS name of route. Defaults to None.

  • cmt (str | None) – GPS comment for route. Defaults to None.

  • desc (str | None) – Text description of route for user. Defaults to None.

  • src (str | None) – Source of data. Defaults to None.

  • link (list[Link]) – Links to external information about the route. Defaults to empty list.

  • number (int | None) – GPS route number. Defaults to None.

  • type (str | None) – Type (classification) of route. Defaults to None.

  • rtept (list[Waypoint]) – List of route points. Defaults to empty list.

property bounds: tuple[Latitude, Longitude, Latitude, Longitude]

The bounds of the route.

property total_distance: float

The total distance (in metres).

property total_duration: timedelta

The total duration.

property moving_duration: timedelta

The moving duration.

The moving duration is the total duration with a speed greater than 0.5 km/h.

property avg_speed: float

The average speed (in metres / second).

property avg_moving_speed: float

The average moving speed (in metres / second).

property max_speed: float

The maximum speed (in metres / second).

property min_speed: float

The minimum speed (in metres / second).

property speed_profile: list[tuple[datetime, float]]

The speed profile.

The speed profile is a list of (timestamp, speed) tuples.

property avg_elevation: Decimal

The average elevation (in metres).

property max_elevation: Decimal

The maximum elevation (in metres).

property min_elevation: Decimal

The minimum elevation (in metres).

property diff_elevation: Decimal

The difference in elevation (in metres).

property total_ascent: Decimal

The total ascent (in metres).

property total_descent: Decimal

The total descent (in metres).

property elevation_profile: list[tuple[float, Decimal]]

The elevation profile.

The elevation profile is a list of (distance, elevation) tuples.

gpx.track Module

Track model for GPX data.

This module provides the Track model representing an ordered list of points describing a path, following the GPX 1.1 specification.

class gpx.track.Track(*, name=None, cmt=None, desc=None, src=None, link=<factory>, number=None, type=None, trkseg=<factory>)

Bases: GPXModel

An ordered list of points describing a path.

A track represents a GPS track consisting of track segments.

Parameters:
  • name (str | None) – GPS name of track. Defaults to None.

  • cmt (str | None) – GPS comment for track. Defaults to None.

  • desc (str | None) – User description of track. Defaults to None.

  • src (str | None) – Source of data. Defaults to None.

  • link (list[Link]) – Links to external information about track. Defaults to empty list.

  • number (int | None) – GPS track number. Defaults to None.

  • type (str | None) – Type (classification) of track. Defaults to None.

  • trkseg (list[TrackSegment]) – List of track segments. Defaults to empty list.

property bounds: tuple[Latitude, Longitude, Latitude, Longitude]

The bounds of the track.

property total_distance: float

The total distance of the track (in metres).

property total_duration: timedelta

The total duration of the track (in seconds).

property moving_duration: timedelta

The moving duration of the track.

The moving duration is the total duration with a speed greater than 0.5 km/h.

property avg_speed: float

The average speed of the track (in metres / second).

property avg_moving_speed: float

The average moving speed of the track (in metres / second).

property max_speed: float

The maximum speed of the track (in metres / second).

property min_speed: float

The minimum speed of the track (in metres / second).

property speed_profile: list[tuple[datetime, float]]

The speed profile of the track.

The speed profile is a list of (timestamp, speed) tuples.

property avg_elevation: Decimal

The average elevation (in metres).

property max_elevation: Decimal

The maximum elevation of the track (in metres).

property min_elevation: Decimal

The minimum elevation of the track (in metres).

property diff_elevation: Decimal

The difference in elevation of the track (in metres).

property total_ascent: Decimal

The total ascent of the track (in metres).

property total_descent: Decimal

The total descent of the track (in metres).

property elevation_profile: list[tuple[float, Decimal]]

The elevation profile of the track.

The elevation profile is a list of (distance, elevation) tuples.

gpx.track_segment Module

TrackSegment model for GPX data.

This module provides the TrackSegment model representing a list of track points which are logically connected in order, following the GPX 1.1 specification.

class gpx.track_segment.TrackSegment(*, trkpt=<factory>)

Bases: GPXModel

A track segment holding a list of logically connected track points.

A Track Segment holds a list of Track Points which are logically connected in order. To represent a single GPS track where GPS reception was lost, or the GPS receiver was turned off, start a new Track Segment for each continuous span of track data.

Parameters:

trkpt (list[Waypoint]) – List of track points. Defaults to empty list.

property bounds: tuple[Latitude, Longitude, Latitude, Longitude]

The bounds of the track segment.

property total_distance: float

The total distance (in metres).

property total_duration: timedelta

The total duration.

property moving_duration: timedelta

The moving duration.

The moving duration is the total duration with a speed greater than 0.5 km/h.

property avg_speed: float

The average speed (in metres / second).

property avg_moving_speed: float

The average moving speed (in metres / second).

property max_speed: float

The maximum speed (in metres / second).

property min_speed: float

The minimum speed (in metres / second).

property speed_profile: list[tuple[datetime, float]]

The speed profile.

The speed profile is a list of (timestamp, speed) tuples.

property avg_elevation: Decimal

The average elevation (in metres).

property max_elevation: Decimal

The maximum elevation (in metres).

property min_elevation: Decimal

The minimum elevation (in metres).

property diff_elevation: Decimal

The difference in elevation (in metres).

property total_ascent: Decimal

The total ascent (in metres).

property total_descent: Decimal

The total descent (in metres).

property elevation_profile: list[tuple[float, Decimal]]

The elevation profile.

The elevation profile is a list of (distance, elevation) tuples.

gpx.copyright Module

Copyright model for GPX data.

This module provides the Copyright model containing information about the copyright holder and any license governing use of the GPX data, following the GPX 1.1 specification.

class gpx.copyright.Copyright(author, *, year=None, license=None)

Bases: GPXModel

Information about the copyright holder and any license.

By linking to an appropriate license, you may place your data into the public domain or grant additional usage rights.

Parameters:
  • author (str) – Copyright holder (e.g. TopoSoft, Inc.)

  • year (int | None) – Year of copyright. Defaults to None.

  • license (str | None) – Link to external file containing license text. Defaults to None.

gpx.email Module

Email model for GPX data.

This module provides the Email model representing an email address broken into two parts (id and domain) to help prevent email harvesting, following the GPX 1.1 specification.

class gpx.email.Email(id, domain)

Bases: GPXModel

An email address.

Broken into two parts (id and domain) to help prevent email harvesting.

Parameters:
  • id (str) – id half of email address (e.g. billgates2004)

  • domain (str) – domain half of email address (e.g. hotmail.com)

gpx.person Module

Person model for GPX data.

This module provides the Person model representing a person or organization, following the GPX 1.1 specification.

class gpx.person.Person(*, name=None, email=None, link=None)

Bases: GPXModel

A person or organization.

Parameters:
  • name (str | None) – Name of person or organization. Defaults to None.

  • email (Email | None) – Email address. Defaults to None.

  • link (Link | None) – Link to Web site or other external information about person. Defaults to None.

gpx.bounds Module

Bounds model for GPX data.

This module provides the Bounds model representing two lat/lon pairs defining the extent of an element, following the GPX 1.1 specification.

class gpx.bounds.Bounds(minlat, minlon, maxlat, maxlon)

Bases: GPXModel

Two lat/lon pairs defining the extent of an element.

Parameters:
  • minlat (Latitude) – The minimum latitude.

  • minlon (Longitude) – The minimum longitude.

  • maxlat (Latitude) – The maximum latitude.

  • maxlon (Longitude) – The maximum longitude.

as_tuple()

Return the bounds as a tuple.

Returns:

A tuple of (minlat, minlon, maxlat, maxlon).

Return type:

tuple[Latitude, Longitude, Latitude, Longitude]

gpx.types Module

This module provides simple type objects to contain various GPX data.

class gpx.types.SupportsGeoInterface(*args, **kwargs)

Bases: Protocol

class gpx.types.Latitude(value)

Bases: Decimal

A latitude class for the GPX data format.

The latitude of the point. Decimal degrees, WGS84 datum.

Parameters:

value (str | float | Decimal) – The latitude value.

Raises:

ValueError – If the value is not a valid latitude (i.e. between [-90.0, 90.0]).

class gpx.types.Longitude(value)

Bases: Decimal

A longitude class for the GPX data format.

The longitude of the point. Decimal degrees, WGS84 datum.

Parameters:

value (str | float | Decimal) – The longitude value.

Raises:

ValueError – If the value is not a valid latitude (i.e. between [-180.0, 180.0]).

class gpx.types.Degrees(value)

Bases: Decimal

A degrees class for the GPX data format.

Used for bearing, heading, course. Units are decimal degrees, true (not magnetic).

Parameters:

value (str | float | Decimal) – The degrees value.

Raises:

ValueError – If the value is not a valid latitude (i.e. between [0.0, 360.0)).

class gpx.types.Fix(value)

Bases: str

A fix class for the GPX data format.

Type of GPS fix. None means GPS had no fix. To signify “the fix info is unknown”, leave out fix entirely. pps = military signal used.

Parameters:

value (str) – The fix value.

Raises:

ValueError – If the value is not a valid fix (i.e. one of none, 2d, 3d, dgps, pps).

class gpx.types.DGPSStation(value)

Bases: int

A DGPS station class for the GPX data format.

Represents a differential GPS station.

Parameters:

value (int | str) – The DGPS station value.

Raises:

ValueError – If the value is not a valid DGPS station (i.e. between [0, 1023]).

gpx.utils Module

Utilities for GPX models.

This module provides utilities for automatic XML parsing and serialization based on dataclass field types and metadata.

Key GPX specification pattern: - XML attributes are always required → dataclass fields without | None - XML child elements are always optional → dataclass fields with | None

This allows automatic determination of attributes vs elements based on type hints.

gpx.utils.remove_encoding_from_string(s)

Remove encoding declarations (e.g. encoding=”utf-8”) from the string, if any.

Parameters:

s (str) – The string.

Returns:

The string with any encoding declarations removed.

Return type:

str

gpx.utils.from_isoformat(dt_str)

Convert a string in ISO 8601 format to a datetime object.

gpx.utils.to_isoformat(dt)

Convert a datetime object to a string in ISO 8601 format.

gpx.utils.is_optional(field_type)

Check if a type annotation represents an optional field.

Parameters:

field_type (type) – The type annotation to check.

Returns:

True if the type is Optional (Union[T, None]), False otherwise.

Return type:

bool

gpx.utils.get_inner_type(field_type)

Extract the inner type from an Optional type annotation.

Parameters:

field_type (type) – The type annotation (possibly Optional).

Returns:

The inner type (without None).

Return type:

type

gpx.utils.is_list_type(field_type)

Check if a type annotation represents a list.

Parameters:

field_type (type) – The type annotation to check.

Returns:

True if the type is a list, False otherwise.

Return type:

bool

gpx.utils.get_list_item_type(field_type)

Extract the item type from a list type annotation.

Parameters:

field_type (type) – The list type annotation.

Returns:

The item type.

Return type:

type

gpx.utils.has_from_xml(obj_type)

Check if a type has a from_xml classmethod.

Parameters:

obj_type (type) – The type to check.

Returns:

True if the type has a from_xml method, False otherwise.

Return type:

bool

gpx.utils.has_to_xml(obj)

Check if an object has a to_xml method.

Parameters:

obj (Any) – The object to check.

Returns:

True if the object has a to_xml method, False otherwise.

Return type:

bool

gpx.utils.parse_from_xml(cls, element)

Parse XML element into dictionary by auto-detecting attributes vs elements.

Uses the GPX specification pattern: - Required fields (no | None) are parsed as XML attributes - Optional fields (with | None) are parsed as XML child elements

Supports: - Simple types (str, int, etc.) - Nested models (types with from_xml() method) - Lists of models (list[Model])

Parameters:
  • cls (type[Any]) – The dataclass type.

  • element (Element) – The XML element to parse.

Returns:

A dictionary mapping field names to parsed values.

Raises:

ValueError – If a required attribute is missing.

Return type:

dict[str, Any]

gpx.utils.build_to_xml(obj, element, nsmap=None)

Serialize dataclass to XML by auto-detecting attributes vs elements.

Uses the GPX specification pattern: - Required fields (no | None) are serialized as XML attributes - Optional fields (with | None) are serialized as XML child elements

Supports: - Simple types (str, int, etc.) - Nested models (objects with to_xml() method) - Lists of models (list[Model])

Parameters:
  • obj (Any) – The dataclass instance.

  • element (Element) – The XML element to populate.

  • nsmap (dict[str | None, str] | None) – Optional namespace mapping for child elements.

gpx.utils.has_geo_properties(obj, exclude_fields=None)

Check if a dataclass instance has any optional fields set (for GeoJSON properties).

This is used to determine whether a GeoJSON representation should be a pure geometry or a Feature with properties.

Parameters:
  • obj (Any) – The dataclass instance to check.

  • exclude_fields (Iterable[str] | None) – Field names to exclude from the check (e.g., coordinate fields).

Returns:

True if any optional fields (excluding specified ones) are set, False otherwise.

Return type:

bool

gpx.utils.build_geo_properties(obj, exclude_fields=None)

Build a GeoJSON properties dictionary from a dataclass instance.

Converts dataclass fields to JSON-serializable values for GeoJSON properties. Excludes specified fields (typically coordinate fields) and only includes optional fields that are set.

Parameters:
  • obj (Any) – The dataclass instance.

  • exclude_fields (Iterable[str] | None) – Field names to exclude (e.g., coordinate fields).

Returns:

A dictionary mapping field names to JSON-serializable values.

Return type:

dict[str, Any]

gpx.utils.build_geo_feature(geometry, obj, exclude_fields=None)

Build a GeoJSON Feature or pure geometry based on whether properties exist.

If the object has any optional fields set (excluding coordinate fields), returns a Feature with geometry and properties. Otherwise, returns the pure geometry.

Parameters:
  • geometry (dict[str, Any]) – The GeoJSON geometry dictionary.

  • obj (Any) – The dataclass instance.

  • exclude_fields (Iterable[str] | None) – Field names to exclude from properties (e.g., coordinate fields).

Returns:

A GeoJSON Feature or pure geometry dictionary.

Return type:

dict[str, Any]