Skip to content

Commit

Permalink
more type annotations and fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
jabdoa2 committed Mar 15, 2017
1 parent 9a4530c commit 15afcda
Show file tree
Hide file tree
Showing 19 changed files with 146 additions and 107 deletions.
2 changes: 1 addition & 1 deletion mpf/assets/show.py
Expand Up @@ -32,7 +32,7 @@ class Show(Asset):
path_string = 'shows'
config_section = 'shows'
disk_asset_section = 'file_shows'
extensions = 'yaml'
extensions = tuple('yaml')
class_priority = 100
pool_config_section = 'show_pools'
asset_group_class = ShowPool
Expand Down
1 change: 0 additions & 1 deletion mpf/config_players/event_player.py
Expand Up @@ -11,7 +11,6 @@ class EventPlayer(FlatConfigPlayer):

config_file_section = 'event_player'
show_section = 'events'
device_collection = None

def __init__(self, machine):
"""Initialise EventPlayer."""
Expand Down
1 change: 0 additions & 1 deletion mpf/config_players/random_event_player.py
Expand Up @@ -10,7 +10,6 @@ class RandomEventPlayer(ConfigPlayer):

config_file_section = 'random_event_player'
show_section = 'random_events'
device_collection = None

def __init__(self, machine):
"""Initialise random event player."""
Expand Down
11 changes: 9 additions & 2 deletions mpf/core/assets.py
Expand Up @@ -7,6 +7,8 @@

import asyncio

from typing import Iterable

from mpf.core.case_insensitive_dict import CaseInsensitiveDict
from mpf.core.mpf_controller import MpfController
from mpf.core.utility_functions import Util
Expand Down Expand Up @@ -763,9 +765,14 @@ class Asset(object):
path_string = '' # entry from mpf-mc:paths: for asset folder name
config_section = '' # section in the config files for this asset
disk_asset_section = '' # option is assets: config name is different
extensions = ('', '', '') # tuple of strings, no dots

# tuple of strings, no dots
extensions = tuple() # type: Iterable[str]
class_priority = 0 # Order asset classes will be loaded. Higher is first.
pool_config_section = None # Create an associated AssetPool instance

# Create an associated AssetPool instance
pool_config_section = None # type: str

asset_group_class = AssetPool # replace with your own asset group class

@classmethod
Expand Down
8 changes: 6 additions & 2 deletions mpf/core/config_validator.py
Expand Up @@ -3,6 +3,9 @@
import re
from copy import deepcopy

from typing import Any
from typing import Dict

from mpf.core.config_spec import mpf_config_spec
from mpf.core.rgb_color import named_rgb_colors, RGBColor
from mpf.exceptions.ConfigFileError import ConfigFileError
Expand All @@ -11,14 +14,15 @@

from mpf.core.case_insensitive_dict import CaseInsensitiveDict

# log = logging.getLogger('ConfigValidator')
# TODO: improve this
ConfigDict = Dict[str, Any]


class ConfigValidator(object):

"""Validates config against config specs."""

config_spec = None
config_spec = None # type: ConfigDict

def __init__(self, machine):
"""Initialise validator."""
Expand Down
32 changes: 23 additions & 9 deletions mpf/core/device.py
@@ -1,20 +1,34 @@
"""Contains the Device base class."""
import abc

from typing import List
from typing import TYPE_CHECKING

from mpf.core.machine import MachineController
from mpf.core.logging import LogMixin

if TYPE_CHECKING:
from mpf.core.config_validator import ConfigDict
from mpf.core.platform import BasePlatform


class Device(LogMixin, metaclass=abc.ABCMeta):

"""Generic parent class of for every hardware device in a pinball machine."""

config_section = None # String of the config section name
collection = None # String name of the collection
class_label = None # String of the friendly name of the device class
allow_empty_configs = False # Can a config for this device be empty?
# String of the config section name
config_section = None # type: str

# String name of the collection
collection = None # type: str

# String of the friendly name of the device class
class_label = None # type: str

# Can a config for this device be empty?
allow_empty_configs = False

def __init__(self, machine: MachineController, name: str):
def __init__(self, machine: MachineController, name: str) -> None:
"""Set up default attributes of every device.
Args:
Expand All @@ -24,10 +38,10 @@ def __init__(self, machine: MachineController, name: str):
super().__init__()
self.machine = machine
self.name = name.lower()
self.tags = []
self.label = None
self.platform = None
self.config = dict()
self.tags = [] # type: List[str]
self.label = None # type: str
self.platform = None # type: BasePlatform
self.config = dict() # type: ConfigDict

@classmethod
def get_config_spec(cls):
Expand Down
15 changes: 9 additions & 6 deletions mpf/core/logic_blocks.py
Expand Up @@ -3,7 +3,10 @@
import copy
import logging

from typing import Set

from mpf.core.delays import DelayManager
from mpf.core.events import EventHandlerKey
from mpf.core.machine import MachineController
from mpf.core.mode import Mode
from mpf.core.player import Player
Expand All @@ -16,7 +19,7 @@ class LogicBlocks(MpfController):

"""LogicBlock Manager."""

def __init__(self, machine: MachineController):
def __init__(self, machine: MachineController) -> None:
"""Initialize LogicBlock manager."""
super().__init__(machine)

Expand Down Expand Up @@ -103,7 +106,7 @@ def _process_config(self, config: dict, mode: Mode, priority: int=0):
def _create_logic_blocks(self, config: dict, player: Player):
# config is localized for LogicBlock

blocks_added = set()
blocks_added = set() # type: Set[LogicBlock]

if 'counters' in config:
for item in config['counters']:
Expand Down Expand Up @@ -138,13 +141,13 @@ class LogicBlock(LogMixin):

"""Parent class for each of the logic block classes."""

def __init__(self, machine: MachineController, name: str, player: Player, config: dict):
def __init__(self, machine: MachineController, name: str, player: Player, config: dict) -> None:
"""Initialize logic block."""
super().__init__()
self.machine = machine
self.name = name
self.player = player
self.handler_keys = set()
self.handler_keys = set() # type: Set[EventHandlerKey]

# LogicBlocks are loaded multiple times and config_validator changes the config
# therefore we have to copy the config
Expand Down Expand Up @@ -403,7 +406,7 @@ def config_section_name(self):
"""Return config section."""
return 'counter'

def __init__(self, machine: MachineController, name: str, player: Player, config: dict):
def __init__(self, machine: MachineController, name: str, player: Player, config: dict) -> None:
"""Initialise counter."""
if 'events_when_hit' not in config:
# for compatibility post the same default as previously for
Expand Down Expand Up @@ -611,7 +614,7 @@ def config_section_name(self):
"""Return config section."""
return "sequence"

def __init__(self, machine: MachineController, name: str, player: Player, config: dict):
def __init__(self, machine: MachineController, name: str, player: Player, config: dict) -> None:
"""Initialise sequence."""
super().__init__(machine, name, player, config)

Expand Down
50 changes: 21 additions & 29 deletions mpf/core/machine.py
Expand Up @@ -7,23 +7,30 @@
import pickle
import tempfile

import queue
import sys
import threading

from pkg_resources import iter_entry_points
from typing import Any, TYPE_CHECKING, Callable, Dict, List, Set

from mpf._version import __version__
from mpf.core.case_insensitive_dict import CaseInsensitiveDict
from mpf.core.clock import ClockBase
from mpf.core.config_processor import ConfigProcessor
from mpf.core.config_validator import ConfigDict
from mpf.core.config_validator import ConfigValidator
from mpf.core.data_manager import DataManager
from mpf.core.delays import DelayManager, DelayManagerRegistry
from mpf.core.device_manager import DeviceCollection
from mpf.core.utility_functions import Util
from mpf.core.logging import LogMixin

if TYPE_CHECKING:
from mpf.modes.game.code.game import Game
from mpf.core.events import EventManager
from mpf.core.scriptlet import Scriptlet
from mpf.core.platform import BasePlatform


# pylint: disable-msg=too-many-instance-attributes
class MachineController(LogMixin):
Expand Down Expand Up @@ -51,7 +58,7 @@ class MachineController(LogMixin):
"""

def __init__(self, mpf_path: str, machine_path: str, options: dict):
def __init__(self, mpf_path: str, machine_path: str, options: dict) -> None:
"""Initialize machine controller."""
super().__init__()
self.log = logging.getLogger("Machine")
Expand All @@ -67,35 +74,32 @@ def __init__(self, mpf_path: str, machine_path: str, options: dict):
self.machine_path = machine_path

self.verify_system_info()
self._exception = None
self._exception = None # type: Any

self._boot_holds = set()
self._boot_holds = set() # type: Set[str]
self.is_init_done = False
self.register_boot_hold('init')

self._done = False
self.monitors = dict()
self.plugins = list()
self.scriptlets = list()
self.monitors = dict() # type: Dict[str, Set[Callable]]
self.plugins = list() # type: List[Any]
self.scriptlets = list() # type: List[Scriptlet]
self.modes = DeviceCollection(self, 'modes', None)
self.game = None
self.active_debugger = dict()
self.game = None # type: Game
self.machine_vars = CaseInsensitiveDict()
self.machine_var_monitor = False
self.machine_var_data_manager = None
self.machine_var_data_manager = None # type: DataManager
self.thread_stopper = threading.Event()

self.crash_queue = queue.Queue()

self.config = None
self.events = None
self.config = None # type: ConfigDict
self.events = None # type: EventManager

self._set_machine_path()

self.config_validator = ConfigValidator(self)

self._load_config()
self.machine_config = self.config
self.machine_config = self.config # type: ConfigDict
self.configure_logging(
'Machine',
self.config['logging']['console']['machine_controller'],
Expand All @@ -105,10 +109,9 @@ def __init__(self, mpf_path: str, machine_path: str, options: dict):
self.delay = DelayManager(self.delayRegistry)

self.clock = self._load_clock()
self._crash_queue_checker = self.clock.schedule_interval(self._check_crash_queue, 1)

self.hardware_platforms = dict()
self.default_platform = None
self.hardware_platforms = dict() # type: Dict[str, BasePlatform]
self.default_platform = None # type: BasePlatform

self._load_hardware_platforms()

Expand Down Expand Up @@ -277,17 +280,6 @@ def _load_machine_vars(self):

self.create_machine_var(name=name, value=settings['value'])

def _check_crash_queue(self, time):
del time
try:
crash = self.crash_queue.get(block=False)
except queue.Empty:
pass
else:
print("MPF Shutting down due to child thread crash")
print("Crash details: %s", crash)
self.stop()

def _set_machine_path(self):
# Add the machine folder to sys.path so we can import modules from it
sys.path.insert(0, self.machine_path)
Expand Down
16 changes: 9 additions & 7 deletions mpf/core/mode.py
Expand Up @@ -5,13 +5,15 @@
from typing import Callable
from typing import Dict
from typing import List
from typing import Set
from typing import Tuple

from mpf.core.case_insensitive_dict import CaseInsensitiveDict
from mpf.core.delays import DelayManager
from mpf.core.device import Device
from mpf.core.events import EventHandlerKey
from mpf.core.events import QueuedEvent
from mpf.core.player import Player
from mpf.core.switch_controller import SwitchHandler

from mpf.core.timer import Timer
Expand Down Expand Up @@ -46,18 +48,18 @@ def __init__(self, machine, config: dict, name: str, path) -> None:
self._mode_start_wait_queue = None # type: QueuedEvent
self.stop_methods = list() # type: List[Tuple[Callable, Any]]
self.timers = dict() # type: Dict[str, Timer]
self.start_callback = None # type: Callable
self.stop_callback = None # type: Callable
self.event_handlers = set() # type: List[EventHandlerKey]
self.start_callback = None # type: callable
self.stop_callback = None # type: callable
self.event_handlers = set() # type: Set[EventHandlerKey]
self.switch_handlers = list() # type: List[SwitchHandler]
self.mode_stop_kwargs = dict() # type: Dict[str, Any]
self.mode_devices = set() # type: List[Device]
self.start_event_kwargs = None
self.mode_devices = set() # type: Set[Device]
self.start_event_kwargs = None # type: Dict[str, Any]
self.stopping = False

self.delay = DelayManager(self.machine.delayRegistry)

self.player = None
self.player = None # type: Player
'''Reference to the current player object.'''

self._validate_mode_config()
Expand Down Expand Up @@ -552,7 +554,7 @@ def _setup_timers(self):
for timer, settings in self.config['timers'].items():

self.timers[timer] = Timer(machine=self.machine, mode=self,
name=timer, config=settings)
name=timer, config=settings)

return self._kill_timers

Expand Down
4 changes: 1 addition & 3 deletions mpf/core/mode_controller.py
Expand Up @@ -7,9 +7,7 @@
from mpf.core.utility_functions import Util
from mpf.core.mpf_controller import MpfController

RemoteMethod = namedtuple('RemoteMethod',
'method config_section kwargs priority',
verbose=False)
RemoteMethod = namedtuple('RemoteMethod', ['method', 'config_section', 'kwargs', 'priority'])
"""RemotedMethod is used by other modules that want to register a method to
be called on mode_start or mode_stop.
Expand Down

0 comments on commit 15afcda

Please sign in to comment.