Skip to content

Commit

Permalink
switch from None to AttributeError for searched elements
Browse files Browse the repository at this point in the history
  • Loading branch information
xoolive committed Jan 16, 2025
1 parent 2d76098 commit 4cac98f
Show file tree
Hide file tree
Showing 13 changed files with 35 additions and 42 deletions.
2 changes: 1 addition & 1 deletion src/traffic/algorithms/navigation.py
Original file line number Diff line number Diff line change
Expand Up @@ -949,7 +949,7 @@ def point_merge(
if navaids_extent is None:
_log.warn(msg)
return None
point_merge = navaids_extent.get(point_merge) # type: ignore
point_merge = navaids_extent.get(point_merge)
if point_merge is None:
_log.warn("Navaid for point_merge not found")
return None
Expand Down
4 changes: 2 additions & 2 deletions src/traffic/core/airspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,10 @@ class Airspaces(DataFrameMixin):
lower=dict(),
)

def __getitem__(self, name: str) -> None | Airspace:
def __getitem__(self, name: str) -> Airspace:
subset = self.consolidate().query(f'designator == "{name}"')
if subset is None:
return None
raise AttributeError(f"Airspace {name} not found")

return Airspace(
elements=unary_union_with_alt(
Expand Down
2 changes: 1 addition & 1 deletion src/traffic/core/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def point(self) -> AirportPoint:
return p

@property
def runways(self) -> Optional[RunwayAirport]:
def runways(self) -> RunwayAirport:
"""
Get runway information associated with the airport.
Expand Down
12 changes: 8 additions & 4 deletions src/traffic/data/basic/airways.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,10 @@ def data(self) -> pd.DataFrame:

return self._data

def __getitem__(self, name: str) -> None | Route:
def __getitem__(self, name: str) -> Route:
output = self.data.query("route == @name").sort_values("id")
if output.shape[0] == 0:
return None
raise AttributeError(f"Route {name} not found")
return Route(
name,
list(
Expand All @@ -132,7 +132,11 @@ def __getitem__(self, name: str) -> None | Route:
),
)

def global_get(self, name: str) -> None | Route:
def global_get(self, name: str) -> Route:
_log.warning("Use .get() function instead", DeprecationWarning)
return self.get(name)

def get(self, name: str) -> Route:
"""Search for a route from all alternative data sources."""
for _key, value in sorted(
self.alternatives.items(),
Expand All @@ -142,7 +146,7 @@ def global_get(self, name: str) -> None | Route:
alt = value[name]
if alt is not None:
return alt
return None
raise AttributeError(f"Route {name} not found")

def search(self, name: str) -> "Airways":
"""
Expand Down
12 changes: 6 additions & 6 deletions src/traffic/data/basic/navaid.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,12 +198,12 @@ def data(self) -> pd.DataFrame:
return self._data

@lru_cache()
def __getitem__(self, name: str) -> None | Navaid:
def __getitem__(self, name: str) -> Navaid:
x = self.data.query(
"description == @name.upper() or name == @name.upper()"
)
if x.shape[0] == 0:
return None
raise AttributeError(f"Point {name} not found")
dic = dict(x.iloc[0])
for key, value in dic.items():
if isinstance(value, np.float64):
Expand All @@ -216,11 +216,11 @@ def __getitem__(self, name: str) -> None | Navaid:
del dic["id"]
return Navaid(**dic)

def global_get(self, name: str) -> None | Navaid:
_log.warn("Use .get() function instead", DeprecationWarning)
def global_get(self, name: str) -> Navaid:
_log.warning("Use .get() function instead", DeprecationWarning)
return self.get(name)

def get(self, name: str) -> None | Navaid:
def get(self, name: str) -> Navaid:
"""Search for a navaid from all alternative data sources.
>>> from traffic.data import navaids
Expand Down Expand Up @@ -250,7 +250,7 @@ def get(self, name: str) -> None | Navaid:
alt = value[name]
if alt is not None:
return alt
return None
raise AttributeError(f"Point {name} not found")

def __iter__(self) -> Iterator[Navaid]:
for _, x in self.data.iterrows():
Expand Down
12 changes: 3 additions & 9 deletions src/traffic/data/basic/runways.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,19 +201,13 @@ def runways(self) -> RunwaysType:
self._runways = pickle.load(fh)
return self._runways

def __getitem__(
self, airport: Union["Airport", str]
) -> Optional[RunwayAirport]:
def __getitem__(self, name: Union["Airport", str]) -> RunwayAirport:
from .. import airports

airport_: Optional["Airport"] = (
airports[airport] if isinstance(airport, str) else airport
)
if airport_ is None:
return None
airport_ = airports[name] if isinstance(name, str) else name
elt = self.runways.get(airport_.icao, None)
if elt is None:
return None
raise AttributeError(f"Runway information not found for {name}")
return RunwayAirport(runways=elt)

def download_runways(self) -> None: # coverage: ignore
Expand Down
6 changes: 4 additions & 2 deletions src/traffic/data/eurocontrol/aixm/airspaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,14 @@ def __init__(
self.data = gpd.GeoDataFrame.from_records(self.parse_tree(tree, ns))
self.data.to_pickle(airspace_file)

def __getitem__(self, name: str) -> None | Airspace:
self.data = self.data.set_geometry("geometry")

def __getitem__(self, name: str) -> Airspace:
# in this case, running consolidate() on the whole dataset is not
# reasonable, but it still works if we run it after the query
subset = self.query(f'designator == "{name}"')
if subset is None:
return None
raise AttributeError(f"Airspace {name} not found")

return Airspace(
elements=unary_union_with_alt(
Expand Down
4 changes: 2 additions & 2 deletions src/traffic/data/eurocontrol/aixm/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ def from_file(cls, filename: str | Path, **kwargs: Any) -> Self:
return instance

@lru_cache()
def __getitem__(self, name: str) -> None | Route:
def __getitem__(self, name: str) -> Route:
output = self.data.query("name == @name")
if output.shape[0] == 0:
return None
raise AttributeError(f"Route {name} not found")

cumul = []
for x, d in output.groupby("routeFormed"):
Expand Down
4 changes: 3 additions & 1 deletion src/traffic/data/eurocontrol/ddr/airspaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,4 +166,6 @@ def consolidate_rec(df: pd.DataFrame) -> pd.DataFrame:

new_data = pd.DataFrame(self.data).pipe(consolidate_rec)

return self.__class__(gpd.GeoDataFrame(new_data))
return self.__class__(
gpd.GeoDataFrame(new_data).set_geometry("geometry")
)
3 changes: 1 addition & 2 deletions tests/test_airports.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ def test_search() -> None:
@pytest.mark.skipif(skip_runways, reason="Failed to download runway data")
def test_runway_list() -> None:
airport = airports["TLS"]
assert airport is not None
assert airport.runways is not None
rwy_list = set(t.name for t in airport.runways.list)
assert rwy_list == {"14L", "14R", "32L", "32R"}
Expand All @@ -50,7 +49,7 @@ def test_runway_list() -> None:
def test_runway_bearing() -> None:
for apt_name in ["EHAM", "EDDF", "LFPG", "KLAX", "KSFO", "RJTT"]:
airport = airports[apt_name]
if airport is None or airport.runways is None:
if airport.runways is None:
# Robustness against airports being maliciously edited out
# of OurAirports database
continue
Expand Down
3 changes: 0 additions & 3 deletions tests/test_airspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
def test_airspace() -> None:
EBBU = eurofirs["EBBU"]
EHAA = eurofirs["EHAA"]
assert EBBU is not None
assert EHAA is not None

summed = EBBU + EHAA
lon1, lon2, lat1, lat2 = summed.extent
Expand All @@ -41,5 +39,4 @@ def test_area() -> None:
@pytest.mark.skipif(not nm_data, reason="No NM data available")
def test_nm() -> None:
maastricht = nm_airspaces["EDYYUTAX"]
assert maastricht is not None
assert maastricht.area > 1e11
10 changes: 4 additions & 6 deletions tests/test_airways.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@


def test_basic() -> None:
foo = airways["FOO"]
assert foo is None
with pytest.raises(AttributeError):
_foo = airways["FOO"]

l888 = airways["L888"]
assert l888 is not None
Expand All @@ -25,22 +25,20 @@ def test_through_extent() -> None:
air_ext = airways.extent(LSAS)
assert air_ext is not None
swiss_length = max(
air_ext[route].project_shape().length # type: ignore
air_ext[route].project_shape().length
for route in air_ext.search("DITON").data.route
)
full_length = max(
airways[route].project_shape().length # type: ignore
airways[route].project_shape().length
for route in airways.search("DITON").data.route
)
assert swiss_length < 1e6 < full_length

LFBB = eurofirs["LFBB"]
assert LFBB is not None
air_ext = airways.extent(LFBB)
assert air_ext is not None

short_un871 = air_ext["UN871"]
assert short_un871 is not None
assert list(navaid.name for navaid in short_un871.navaids) == [
"LARDA",
"RONNY",
Expand Down
3 changes: 0 additions & 3 deletions tests/test_navaid.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

def test_getter() -> None:
narak = navaids["NARAK"]
assert narak is not None
assert narak.latlon == (44.29527778, 1.74888889)
assert narak.lat == 44.29527778
assert narak.lon == 1.74888889
Expand All @@ -12,14 +11,12 @@ def test_getter() -> None:

def test_extent() -> None:
gaithersburg = navaids["GAI"]
assert gaithersburg is not None
assert gaithersburg.type == "NDB"
LFBB = eurofirs["LFBB"]
assert LFBB is not None
nav_ext = navaids.extent(LFBB)
assert nav_ext is not None
gaillac = nav_ext["GAI"]
assert gaillac is not None
assert gaillac.type == "VOR"
assert gaillac.latlon == (43.95405556, 1.82416667)

Expand Down

0 comments on commit 4cac98f

Please sign in to comment.