[mousetrap/gnome3-wip: 233/240] PEP8/de-linting and adjust `make clean` to delete .coverage.



commit 560e803b5103e362560e17a0a9b726822eaffe00
Author: Stoney Jackson <dr stoney gmail com>
Date:   Tue Jul 1 00:45:50 2014 -0400

    PEP8/de-linting and adjust `make clean` to delete .coverage.

 Makefile.am                        |    1 +
 src/mousetrap/core.py              |   24 +++++++++++++-----------
 src/mousetrap/gui.py               |    9 +++++----
 src/mousetrap/i18n.py              |    8 +++-----
 src/mousetrap/image.py             |    3 +--
 src/mousetrap/main.py              |   26 +++++++++++++-------------
 src/mousetrap/plugins/interface.py |    2 +-
 src/mousetrap/vision.py            |   25 ++++++++++++++++---------
 8 files changed, 53 insertions(+), 45 deletions(-)
---
diff --git a/Makefile.am b/Makefile.am
index 2970ca7..bfe9202 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -61,6 +61,7 @@ clean-local:
        find $(builddir) -name '*.pyo' -delete
        find $(builddir) -name '*.mo' -delete
        rm -rf $(builddir)/build
+       rm -f $(builddir)/.coverage
 
 
 ##############################################################################
diff --git a/src/mousetrap/core.py b/src/mousetrap/core.py
index f120016..8a229cc 100644
--- a/src/mousetrap/core.py
+++ b/src/mousetrap/core.py
@@ -1,7 +1,7 @@
 import logging
 LOGGER = logging.getLogger(__name__)
 
-from gi.repository import GObject, Gdk, Gtk
+from gi.repository import GObject
 
 from mousetrap.i18n import _
 from mousetrap.gui import Gui, Pointer
@@ -32,12 +32,13 @@ class App(object):
         try:
             LOGGER.info('loading %s', class_)
             class_path = class_.split('.')
-            module = __import__('.'.join(class_path[:-1]), {}, {}, class_path[-1])
+            module = __import__(
+                    '.'.join(class_path[:-1]), {}, {}, class_path[-1])
             return getattr(module, class_path[-1])(self.config)
-        except ImportError as error:
-            print("ERROR")
+        except ImportError:
             LOGGER.error(
-                _('Could not import plugin `%s`. Check config file and PYTHONPATH.'),
+                _('Could not import plugin `%s`.' + \
+                        'Check config file and PYTHONPATH.'),
                 class_
                 )
             raise
@@ -46,7 +47,7 @@ class App(object):
         for plugin in self.plugins:
             self.loop.subscribe(plugin)
 
-    def run(self, app=None):
+    def run(self):
         self.loop.start()
         self.gui.start()
 
@@ -75,8 +76,10 @@ class Loop(Observable):
     def __init__(self, config, app):
         super(Loop, self).__init__()
         self._config = config
-        self._set_loops_per_second(config['loops_per_second'])
+        self._interval = None
+        self._loops_per_second = None
         self._timeout_id = None
+        self._set_loops_per_second(config['loops_per_second'])
         self._add_argument('app', app)
 
     def _set_loops_per_second(self, loops_per_second):
@@ -85,10 +88,9 @@ class Loop(Observable):
             self.MILLISECONDS_PER_SECOND / self._loops_per_second))
 
     def start(self):
-        self.timeout_id = GObject.timeout_add(self._interval, self._run)
+        self._timeout_id = GObject.timeout_add(self._interval, self._run)
 
     def _run(self):
-        CONTINUE = True
-        PAUSE = False
         self._fire(self.CALLBACK_RUN)
-        return CONTINUE
+        continue_ = True
+        return continue_
diff --git a/src/mousetrap/gui.py b/src/mousetrap/gui.py
index 0c77616..9d4246e 100644
--- a/src/mousetrap/gui.py
+++ b/src/mousetrap/gui.py
@@ -89,14 +89,15 @@ class Pointer(object):
         return self._moved
 
     def get_position(self):
-        X_INDEX = 1
-        Y_INDEX = 2
+        x_index = 1
+        y_index = 2
         position = self._pointer.get_position()
-        return (position[X_INDEX], position[Y_INDEX])
+        return (position[x_index], position[y_index])
 
     def click(self, button=BUTTON_LEFT):
         display = XlibDisplay()
-        for event, button in [(X.ButtonPress, button), (X.ButtonRelease, button)]:
+        for event, button in \
+                [(X.ButtonPress, button), (X.ButtonRelease, button)]:
             LOGGER.debug('%s %s', event, button)
             xtest.fake_input(display, event, button)
             display.sync()
diff --git a/src/mousetrap/i18n.py b/src/mousetrap/i18n.py
index 21faed9..a68ba0a 100644
--- a/src/mousetrap/i18n.py
+++ b/src/mousetrap/i18n.py
@@ -1,13 +1,11 @@
 import gettext
-import locale
 import os
 
 import logging
 LOGGER = logging.getLogger(__name__)
 
-LOCALE_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "locale"))
+LOCALE_DIR = os.path.abspath(
+        os.path.join(os.path.dirname(os.path.realpath(__file__)), "locale"))
 LOGGER.debug("LOCALE_DIR = %s", LOCALE_DIR)
 
-translations = gettext.translation("mousetrap", localedir=LOCALE_DIR)
-
-_ = translations.ugettext
+_ = gettext.translation("mousetrap", localedir=LOCALE_DIR).ugettext
diff --git a/src/mousetrap/image.py b/src/mousetrap/image.py
index 02a714b..073be7a 100644
--- a/src/mousetrap/image.py
+++ b/src/mousetrap/image.py
@@ -4,7 +4,6 @@ All things image manipulation.
 
 import cv2
 from gi.repository import GdkPixbuf
-from mousetrap.i18n import _
 
 
 _GDK_PIXBUF_BIT_PER_SAMPLE = 8
@@ -60,7 +59,7 @@ def _cvimage_to_pixbuf(cvimage):
 
     return GdkPixbuf.Pixbuf.new_from_data(
         data,
-        colorspace, # FIXME: Need to handle grayscale.
+        colorspace,
         has_alpha_channel,
         _GDK_PIXBUF_BIT_PER_SAMPLE,
         width,
diff --git a/src/mousetrap/main.py b/src/mousetrap/main.py
index 6ac965d..b23e8bc 100644
--- a/src/mousetrap/main.py
+++ b/src/mousetrap/main.py
@@ -12,6 +12,8 @@ from mousetrap.config import Config
 
 
 class Main(object):
+    DEFAULT_CONFIG_PATH = dirname(__file__) + '/mousetrap.yaml'
+    USER_CONFIG_PATH = expanduser('~/.mousetrap.yaml')
 
     def __init__(self):
         try:
@@ -24,14 +26,12 @@ class Main(object):
             sys.exit(0)
 
     def _get_config_paths(self):
-            paths = [dirname(__file__) + '/mousetrap.yaml']
-            user_config = expanduser('~/.mousetrap.yaml')
-            if exists(user_config):
-                paths.append(user_config)
-            if self._args.config is not None:
-                paths.append(self._args.config)
-            return paths
-
+        paths = [self.DEFAULT_CONFIG_PATH]
+        if exists(self.USER_CONFIG_PATH):
+            paths.append(self.USER_CONFIG_PATH)
+        if self._args.config is not None:
+            paths.append(self._args.config)
+        return paths
 
     def _handle_dump_annotated(self):
         if self._args.dump_annotated:
@@ -43,9 +43,9 @@ class Main(object):
             self._dump_config()
             raise ExitException()
 
-    @staticmethod
-    def _dump_annotated():
-        with open(Config.get_config_path('default'), 'r') as annotated_file:
+    @classmethod
+    def _dump_annotated(cls):
+        with open(cls.DEFAULT_CONFIG_PATH, 'r') as annotated_file:
             print annotated_file.read()
 
     def _dump_config(self):
@@ -72,7 +72,8 @@ class CommandLineArguments(object):
                 help="Loads and dumps current configuration to standard out.",
                 action="store_true")
         parser.add_argument("--dump-annotated",
-                help="Dumps default configuration (with comments) to standard out.",
+                help="Dumps default configuration" + \
+                    " (with comments) to standard out.",
                 action="store_true")
         parser.parse_args(namespace=self)
 
@@ -87,4 +88,3 @@ def main():
 
 if __name__ == '__main__':
     main()
-
diff --git a/src/mousetrap/plugins/interface.py b/src/mousetrap/plugins/interface.py
index 7c2752d..f718c34 100644
--- a/src/mousetrap/plugins/interface.py
+++ b/src/mousetrap/plugins/interface.py
@@ -5,7 +5,7 @@ class Plugin(object):
     def __init__(self, config):
         '''Override to initialize and configure yourself.
         (Do not call parent/this constructor.)'''
-        raise NotImplementedError(_('Must implement.'))
+        pass
 
     def run(self, app):
         '''Called each pass of the loop.'''
diff --git a/src/mousetrap/vision.py b/src/mousetrap/vision.py
index d602db8..92efae3 100644
--- a/src/mousetrap/vision.py
+++ b/src/mousetrap/vision.py
@@ -12,12 +12,14 @@ import logging
 LOGGER = logging.getLogger(__name__)
 
 class Camera(object):
-    S_CAPTURE_OPEN_ERROR = _('Device #%d does not support video capture interface')
+    S_CAPTURE_OPEN_ERROR = _(
+            'Device #%d does not support video capture interface')
     S_CAPTURE_READ_ERROR = _('Error while capturing. Camera disconnected?')
 
     def __init__(self, config):
         self._config = config
-        self._device = self._new_capture_device(config['camera']['device_index'])
+        self._device = \
+                self._new_capture_device(config['camera']['device_index'])
         self.set_dimensions(
             config['camera']['width'],
             config['camera']['height'],
@@ -103,7 +105,7 @@ class FeatureDetector(object):
 
     @classmethod
     def clear_all_detection_caches(cls):
-        for key, instance in cls._INSTANCES.items():
+        for instance in cls._INSTANCES.values():
             instance.clear_cache()
 
     def __init__(self, config, name, scale_factor=1.1, min_neighbors=3):
@@ -116,7 +118,8 @@ class FeatureDetector(object):
         min_neighbors - how many neighbors each candidate rectangle should have
                 to retain it. Default 3.
         '''
-        LOGGER.info("Building detector: %s", (name, scale_factor, min_neighbors))
+        LOGGER.info("Building detector: %s",
+                (name, scale_factor, min_neighbors))
         self._config = config
         self._name = name
         self._single = None
@@ -130,9 +133,9 @@ class FeatureDetector(object):
 
     def detect(self, image):
         if image in self._detect_cache:
-            LOGGER.debug("Detection cache hit: %(image)d -> %(result)s" %
+            message = "Detection cache hit: %(image)d -> %(result)s" % \
                     {'image':id(image), 'result':self._detect_cache[image]}
-                    )
+            LOGGER.debug(message)
             if isinstance(self._detect_cache[image], FeatureNotFoundException):
                 message = str(self._detect_cache[image])
                 raise FeatureNotFoundException(message,
@@ -168,10 +171,13 @@ class FeatureDetector(object):
         else:
             if not self._last_attempt_successful:
                 self._last_attempt_successful = True
-                LOGGER.info(_('Feature detected: %s') % (self._name))
+                message = _('Feature detected: %s') % (self._name)
+                LOGGER.info(message)
 
     def _unpack_first(self):
-        self._single = dict(zip(['x', 'y', 'width', 'height'], self._plural[0]))
+        self._single = dict(
+                zip(['x', 'y', 'width', 'height'],
+                self._plural[0]))
 
     def _calculate_center(self):
         self._single["center"] = {
@@ -198,6 +204,7 @@ class FeatureDetector(object):
 
 class FeatureDetectorClearCachePlugin(interface.Plugin):
     def __init__(self, config):
+        super(FeatureDetectorClearCachePlugin, self).__init__(config)
         self._config = config
 
     def run(self, app):
@@ -205,7 +212,7 @@ class FeatureDetectorClearCachePlugin(interface.Plugin):
 
 
 class FeatureNotFoundException(Exception):
-    def __init__(self, message, cause = None):
+    def __init__(self, message, cause=None):
         if cause is not None:
             message = message + ', caused by ' + repr(cause)
         self.cause = cause


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]