Skip to content

Commit

Permalink
Fix existing mypy issues.
Browse files Browse the repository at this point in the history
Part of pydcs#160.

In many cases this is being solved with assert/raise to inform mypy of
the "guaranteed" types. They could be removed later with some changes to
the implementation/API, but those will be easier to make once the type
checker is fully on.

There are a small number of API changes here, primarily removing default
kwargs that aren't actually defaultable (using the defaults would result
in a crash).
  • Loading branch information
DanAlbert committed Jul 9, 2021
1 parent 7e2bbf8 commit 0ec449f
Show file tree
Hide file tree
Showing 23 changed files with 467 additions and 378 deletions.
10 changes: 7 additions & 3 deletions dcs/action.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Dict
from typing import Any, Dict, List, Type
from dcs.lua.serialize import dumps
from dcs.translation import String, ResourceKey
from enum import Enum, IntEnum
Expand All @@ -7,7 +7,7 @@
class Action:
def __init__(self, predicate: str) -> None:
self.predicate = predicate
self.params = []
self.params: List[Any] = []

def __repr__(self) -> str:
s = []
Expand All @@ -20,6 +20,10 @@ def __repr__(self) -> str:
s.append(dumps(x))
return self.predicate + "(" + ", ".join(s) + ")"

@classmethod
def create_from_dict(cls, d, mission):
raise NotImplementedError

def dict(self) -> Dict[Any, Any]:
d = {
"predicate": self.predicate,
Expand Down Expand Up @@ -1773,7 +1777,7 @@ def dict(self):
return d


actions_map = {
actions_map: Dict[str, Type[Action]] = {
"a_activate_group": ActivateGroup,
"a_add_radio_item": AddRadioItem,
"a_add_radio_item_for_coalition": AddRadioItemForCoalition,
Expand Down
2 changes: 1 addition & 1 deletion dcs/cloud_presets.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
class Clouds(Enum):

@staticmethod
def from_name(name: str) -> "CloudPreset":
def from_name(name: str) -> "Clouds":
return CLOUD_PRESETS[name]

LightScattered1 = CloudPreset(
Expand Down
23 changes: 12 additions & 11 deletions dcs/coalition.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import dcs.planes as planes
import dcs.helicopters as helicopters
import dcs.ships as ships
from dcs.unit import Vehicle, Static, Ship, FARP, SingleHeliPad
from dcs.unit import BaseFARP, Vehicle, Static, Ship, FARP, SingleHeliPad
from dcs.flyingunit import Plane, Helicopter
from dcs.point import MovingPoint, StaticPoint
from dcs.country import Country
Expand Down Expand Up @@ -58,7 +58,7 @@ def _park_unit_on_airport(
mission: 'Mission',
group: unitgroup.Group,
unit: Union[Plane, Helicopter]) -> List[StatusMessage]:
ret = []
ret: List[StatusMessage] = []
if group.points[0].airdrome_id is not None and unit.parking is not None:
airport = mission.terrain.airport_by_id(group.points[0].airdrome_id)
slot = airport.parking_slot(unit.parking)
Expand Down Expand Up @@ -120,25 +120,25 @@ def load_from_dict(self, mission, d) -> List[StatusMessage]:
if "ship" in imp_country:
for group_idx in imp_country["ship"]["group"]:
imp_group = imp_country["ship"]["group"][group_idx]
vg = unitgroup.ShipGroup(imp_group["groupId"], self.get_name(mission, imp_group["name"]),
ship_group = unitgroup.ShipGroup(imp_group["groupId"], self.get_name(mission, imp_group["name"]),
imp_group["start_time"])
vg.load_from_dict(imp_group)
mission.current_group_id = max(mission.current_group_id, vg.id)
ship_group.load_from_dict(imp_group)
mission.current_group_id = max(mission.current_group_id, ship_group.id)

Coalition._import_moving_point(mission, vg, imp_group)
Coalition._import_moving_point(mission, ship_group, imp_group)

# units
for imp_unit_idx in imp_group["units"]:
imp_unit = imp_group["units"][imp_unit_idx]
unit = Ship(
ship = Ship(
id=imp_unit["unitId"],
name=self.get_name(mission, imp_unit["name"]),
_type=ships.ship_map[imp_unit["type"]])
unit.load_from_dict(imp_unit)
ship.load_from_dict(imp_unit)

mission.current_unit_id = max(mission.current_unit_id, unit.id)
vg.add_unit(unit)
_country.add_ship_group(vg)
mission.current_unit_id = max(mission.current_unit_id, ship.id)
ship_group.add_unit(ship)
_country.add_ship_group(ship_group)

if "plane" in imp_country:
for pgroup_idx in imp_country["plane"]["group"]:
Expand Down Expand Up @@ -228,6 +228,7 @@ def load_from_dict(self, mission, d) -> List[StatusMessage]:
# units
for imp_unit_idx in sgroup["units"]:
imp_unit = sgroup["units"][imp_unit_idx]
static: Static
if imp_unit["type"] == "FARP":
static = FARP(
unit_id=imp_unit["unitId"],
Expand Down
7 changes: 6 additions & 1 deletion dcs/condition.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from typing import Dict, Type
from dcs.lua.serialize import dumps


Expand Down Expand Up @@ -28,6 +29,10 @@ def condition_str(cls, rules):
return s + " )"
return "return(true)"

@classmethod
def create_from_dict(cls, d):
raise NotImplementedError

def dict(self):
d = {
"predicate": self.predicate
Expand Down Expand Up @@ -1258,7 +1263,7 @@ def dict(self):
return d


condition_map = {
condition_map: Dict[str, Type[Condition]] = {
"c_all_of_coalition_in_zone": AllOfCoalitionInZone,
"c_all_of_coalition_out_zone": AllOfCoalitionOutsideZone,
"c_all_of_group_in_zone": AllOfGroupInZone,
Expand Down
14 changes: 9 additions & 5 deletions dcs/country.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from dcs.helicopters import HelicopterType
from dcs.planes import PlaneType
from dcs.unitgroup import VehicleGroup, ShipGroup, PlaneGroup, StaticGroup, HelicopterGroup, FlyingGroup, Group
from typing import List, Dict, Set
from typing import List, Dict, Set, Type


def find_exact(group_name, find_name):
Expand All @@ -17,9 +19,9 @@ def find_match(group_name, find_name):


class Country:
callsign = {}
planes = []
helicopters = []
callsign: Dict[str, List[str]] = {}
planes: List[Type[PlaneType]] = []
helicopters: List[Type[HelicopterType]] = []

def __init__(self, _id, name):
self.id = _id
Expand All @@ -45,10 +47,12 @@ def add_plane_group(self, pgroup):
def add_helicopter_group(self, hgroup):
self.helicopter_group.append(hgroup)

def add_aircraft_group(self, group: FlyingGroup):
def add_aircraft_group(self, group: FlyingGroup) -> None:
if group.units[0].unit_type.helicopter:
assert isinstance(group, HelicopterGroup)
self.helicopter_group.append(group)
else:
assert isinstance(group, PlaneGroup)
self.plane_group.append(group)

def add_static_group(self, sgroup):
Expand Down
17 changes: 11 additions & 6 deletions dcs/flyingunit.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
from dcs.unit import Unit, Skill
from dcs.unittype import FlyingType
from dcs.unittype import AircraftRadioPresets, FlyingType
from dcs.terrain import ParkingSlot
from dcs.planes import PlaneType, A_10C
from dcs.helicopters import HelicopterType, Ka_50

import json
from typing import Type
from typing import Dict, Optional, Type


class FlyingUnit(Unit):
def __init__(self, _id=None, name=None, _type: Type[FlyingType] = None, _country=None):
def __init__(self, _id, name, _type: Type[FlyingType], _country=None):
super(FlyingUnit, self).__init__(_id, name, _type.id)
self.unit_type = _type # for loadout validation
self.unit_type.load_payloads()
Expand All @@ -25,11 +25,11 @@ def __init__(self, _id=None, name=None, _type: Type[FlyingType] = None, _country
self.fuel = _type.fuel_max
self.gun = 100
self.ammo_type = _type.ammo_type
self.pylons = {}
self.pylons: Dict[int, Dict[str, str]] = {}
self.callsign = None
self.callsign_dict = {1: 1, 2: 1, 3: 1, "name": ""}
self.speed = 0
self.radio = None
self.radio: Optional[AircraftRadioPresets] = None
self.hardpoint_racks = True
self.addpropaircraft = _type.property_defaults if _type.property_defaults else None

Expand Down Expand Up @@ -106,6 +106,8 @@ def set_radio_preset(self):

def num_radio_channels(self, radio_id: int) -> int:
"""Returns the number of channels available for the given radio."""
if self.radio is None:
return 0
return len(self.radio[radio_id]["channels"])

def set_radio_channel_preset(self, radio_id: int, channel: int,
Expand Down Expand Up @@ -177,7 +179,10 @@ def callsign_as_str(self) -> str:
"""
if not self.callsign_is_western:
return str(self.callsign)
return self.callsign_dict["name"]
name = self.callsign_dict["name"]
if not isinstance(name, str):
raise TypeError("Expected the 'name' entry of callsign_dict to be a str")
return name

def dict(self):
d = super(FlyingUnit, self).dict()
Expand Down
Loading

0 comments on commit 0ec449f

Please sign in to comment.