Skip to content

Commit

Permalink
Merge pull request #94 from dericke/loop_consolidation
Browse files Browse the repository at this point in the history
Sourcery-suggested refactors
  • Loading branch information
cleder authored Jan 2, 2021
2 parents 82c6241 + bf54d2b commit 9f24722
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 104 deletions.
66 changes: 28 additions & 38 deletions fastkml/atom.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,7 @@ def __init__(
self, ns=None, href=None, rel=None, type=None,
hreflang=None, title=None, length=None
):
if ns is None:
self.ns = NS
else:
self.ns = ns
self.ns = NS if ns is None else ns
self.href = href
self.rel = rel
self.type = type
Expand All @@ -104,22 +101,21 @@ def from_string(self, xml_string):
def from_element(self, element):
if self.ns + self.__name__.lower() != element.tag:
raise TypeError
if element.get('href'):
self.href = element.get('href')
else:
if element.get('href'):
self.href = element.get('href')
else:
logger.critical('required attribute href missing')
raise TypeError
if element.get('rel'):
self.rel = element.get('rel')
if element.get('type'):
self.type = element.get('type')
if element.get('hreflang'):
self.hreflang = element.get('hreflang')
if element.get('title'):
self.title = element.get('title')
if element.get('length'):
self.length = element.get('length')
logger.critical('required attribute href missing')
raise TypeError
if element.get('rel'):
self.rel = element.get('rel')
if element.get('type'):
self.type = element.get('type')
if element.get('hreflang'):
self.hreflang = element.get('hreflang')
if element.get('title'):
self.title = element.get('title')
if element.get('length'):
self.length = element.get('length')

def etree_element(self):
element = etree.Element(self.ns + self.__name__.lower())
Expand Down Expand Up @@ -171,10 +167,7 @@ class _Person(object):
# contains an email address for the person.

def __init__(self, ns=None, name=None, uri=None, email=None):
if ns is None:
self.ns = NS
else:
self.ns = ns
self.ns = NS if ns is None else ns
self.name = name
self.uri = uri
self.email = email
Expand All @@ -191,10 +184,9 @@ def etree_element(self):
# XXX validate uri
uri = etree.SubElement(element, "%suri" % self.ns)
uri.text = self.uri
if self.email:
if check_email(self.email):
email = etree.SubElement(element, "%semail" % self.ns)
email.text = self.email
if self.email and check_email(self.email):
email = etree.SubElement(element, "%semail" % self.ns)
email.text = self.email
return element

def from_string(self, xml_string):
Expand All @@ -203,17 +195,15 @@ def from_string(self, xml_string):
def from_element(self, element):
if self.ns + self.__name__.lower() != element.tag:
raise TypeError
else:
name = element.find('%sname' % self.ns)
if name is not None:
self.name = name.text
uri = element.find('%suri' % self.ns)
if uri is not None:
self.uri = uri.text
email = element.find('%semail' % self.ns)
if email is not None:
if check_email(email.text):
self.email = email.text
name = element.find('%sname' % self.ns)
if name is not None:
self.name = name.text
uri = element.find('%suri' % self.ns)
if uri is not None:
self.uri = uri.text
email = element.find('%semail' % self.ns)
if email is not None and check_email(email.text):
self.email = email.text

def to_string(self, prettyprint=True):
""" Return the ATOM Object as serialized xml """
Expand Down
10 changes: 2 additions & 8 deletions fastkml/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,7 @@ class _XMLObject(object):
ns = None

def __init__(self, ns=None):
if ns is None:
self.ns = config.KMLNS
else:
self.ns = ns
self.ns = config.KMLNS if ns is None else ns

def etree_element(self):
if self.__name__:
Expand Down Expand Up @@ -77,10 +74,7 @@ class _BaseObject(_XMLObject):
def __init__(self, ns=None, id=None):
super(_BaseObject, self).__init__(ns)
self.id = id
if ns is None:
self.ns = config.KMLNS
else:
self.ns = ns
self.ns = config.KMLNS if ns is None else ns

def etree_element(self):
element = super(_BaseObject, self).etree_element()
Expand Down
74 changes: 33 additions & 41 deletions fastkml/geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
Import the geometries from shapely if it is installed or otherwise from Pygeoif
"""

import re

try:
from shapely.geometry import Point, LineString, Polygon
from shapely.geometry import MultiPoint, MultiLineString, MultiPolygon
Expand All @@ -31,17 +33,15 @@
# to another geometry. I've seen some signs of this changing in GEOS,
# but until it does I don't think there's any point to the class.
# It wouldn't be much more than a list of geometries.
from pygeoif.geometry import GeometryCollection
from shapely.geometry import asShape

except ImportError:
from pygeoif.geometry import Point, LineString, Polygon
from pygeoif.geometry import MultiPoint, MultiLineString, MultiPolygon
from pygeoif.geometry import LinearRing
from pygeoif.geometry import GeometryCollection
from pygeoif.geometry import as_shape as asShape
from pygeoif.geometry import GeometryCollection

import re
import fastkml.config as config

from .config import etree
Expand Down Expand Up @@ -322,10 +322,10 @@ def _get_coordinates(self, element):
# spaces. Clean up badly formatted tuples by stripping
# space following commas.
latlons = re.sub(r', +', ',', coordinates.text.strip()).split()
coords = []
for latlon in latlons:
coords.append([float(c) for c in latlon.split(',')])
return coords
return [
[float(c) for c in latlon.split(',')]
for latlon in latlons
]

def _get_linear_ring(self, element):
# LinearRing in polygon
Expand All @@ -350,9 +350,8 @@ def _get_geometry(self, element):
outer_boundary = element.find('%souterBoundaryIs' % self.ns)
ob = self._get_linear_ring(outer_boundary)
inner_boundaries = element.findall('%sinnerBoundaryIs' % self.ns)
ibs = []
for inner_boundary in inner_boundaries:
ibs.append(self._get_linear_ring(inner_boundary))
ibs = [self._get_linear_ring(inner_boundary)
for inner_boundary in inner_boundaries]
return Polygon(ob, ibs)
if element.tag == ('%sLinearRing' % self.ns):
coords = self._get_coordinates(element)
Expand All @@ -364,49 +363,42 @@ def _get_multigeometry(self, element):
geoms = []
if element.tag == ('%sMultiGeometry' % self.ns):
points = element.findall('%sPoint' % self.ns)
if points:
for point in points:
self._get_geometry_spec(point)
geoms.append(Point(self._get_coordinates(point)[0]))
for point in points:
self._get_geometry_spec(point)
geoms.append(Point(self._get_coordinates(point)[0]))
linestrings = element.findall('%sLineString' % self.ns)
if linestrings:
for ls in linestrings:
self._get_geometry_spec(ls)
geoms.append(LineString(self._get_coordinates(ls)))
for ls in linestrings:
self._get_geometry_spec(ls)
geoms.append(LineString(self._get_coordinates(ls)))
polygons = element.findall('%sPolygon' % self.ns)
if polygons:
for polygon in polygons:
self._get_geometry_spec(polygon)
outer_boundary = polygon.find(
'%souterBoundaryIs' % self.ns
)
ob = self._get_linear_ring(outer_boundary)
inner_boundaries = polygon.findall(
'%sinnerBoundaryIs' % self.ns
)
ibs = []
for inner_boundary in inner_boundaries:
ibs.append(self._get_linear_ring(inner_boundary))
geoms.append(Polygon(ob, ibs))
for polygon in polygons:
self._get_geometry_spec(polygon)
outer_boundary = polygon.find(
'%souterBoundaryIs' % self.ns
)
ob = self._get_linear_ring(outer_boundary)
inner_boundaries = polygon.findall(
'%sinnerBoundaryIs' % self.ns
)
ibs = [self._get_linear_ring(inner_boundary)
for inner_boundary in inner_boundaries]
geoms.append(Polygon(ob, ibs))
linearings = element.findall('%sLinearRing' % self.ns)
if linearings:
for lr in linearings:
self._get_geometry_spec(lr)
geoms.append(LinearRing(self._get_coordinates(lr)))
if len(geoms) > 0:
geom_types = []
for geom in geoms:
geom_types.append(geom.geom_type)
geom_types = list(set(geom_types))
if geoms:
geom_types = {geom.geom_type for geom in geoms}
if len(geom_types) > 1:
return GeometryCollection(geoms)
if geom_types[0] == 'Point':
if 'Point' in geom_types:
return MultiPoint(geoms)
elif geom_types[0] == 'LineString':
elif 'LineString' in geom_types:
return MultiLineString(geoms)
elif geom_types[0] == 'Polygon':
elif 'Polygon' in geom_types:
return MultiPolygon(geoms)
elif geom_types[0] == 'LinearRing':
elif 'LinearRing' in geom_types:
return GeometryCollection(geoms)

def from_element(self, element):
Expand Down
8 changes: 3 additions & 5 deletions fastkml/kml.py
Original file line number Diff line number Diff line change
Expand Up @@ -819,7 +819,7 @@ def altitudeMode(self):
@altitudeMode.setter
def altitudeMode(self, mode):
if mode in ('clampToGround', 'absolute'):
self._altitudeMode = str(mode)
self._altitudeMode = str(mode)
else:
self._altitudeMode = 'clampToGround'

Expand Down Expand Up @@ -1280,17 +1280,15 @@ def __init__(self, ns=None, id=None, name=None, fields=None):

@property
def simple_fields(self):
sfs = [
return tuple(
{
'type': simple_field['type'],
'name': simple_field['name'],
'displayName': simple_field.get('displayName'),
}
for simple_field in self._simple_fields
if simple_field.get('type') and simple_field.get('name')
]

return tuple(sfs)
)

@simple_fields.setter
def simple_fields(self, fields):
Expand Down
22 changes: 10 additions & 12 deletions fastkml/styles.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,18 +179,16 @@ def from_element(self, element):

def etree_element(self):
element = super(StyleMap, self).etree_element()
if self.normal:
if isinstance(self.normal, (Style, StyleUrl)):
pair = etree.SubElement(element, "%sPair" % self.ns)
key = etree.SubElement(pair, "%skey" % self.ns)
key.text = 'normal'
pair.append(self.normal.etree_element())
if self.highlight:
if isinstance(self.highlight, (Style, StyleUrl)):
pair = etree.SubElement(element, "%sPair" % self.ns)
key = etree.SubElement(pair, "%skey" % self.ns)
key.text = 'highlight'
pair.append(self.highlight.etree_element())
if self.normal and isinstance(self.normal, (Style, StyleUrl)):
pair = etree.SubElement(element, "%sPair" % self.ns)
key = etree.SubElement(pair, "%skey" % self.ns)
key.text = 'normal'
pair.append(self.normal.etree_element())
if self.highlight and isinstance(self.highlight, (Style, StyleUrl)):
pair = etree.SubElement(element, "%sPair" % self.ns)
key = etree.SubElement(pair, "%skey" % self.ns)
key.text = 'highlight'
pair.append(self.highlight.etree_element())
return element


Expand Down

0 comments on commit 9f24722

Please sign in to comment.