Commits

Simon Cross committed b38013c

First giant PEP-8 clean-up commit for KATCP.

  • Participants
  • Parent commits e4b882f

Comments (0)

Files changed (16)

File katcp/__init__.py

 
 import logging
 
+
 class NullHandler(logging.Handler):
     def emit(self, record):
         pass
 
 del logging, NullHandler
 
-
 from .core import Message, KatcpSyntaxError, MessageParser, \
                   DeviceMetaclass, ExcepthookThread, FailReply, \
                   AsyncReply, KatcpDeviceError, KatcpClientError, \
 
 from .client import DeviceClient, BlockingClient, CallbackClient
 
-from .sensortree import GenericSensorTree, BooleanSensorTree, AggregateSensorTree
+from .sensortree import GenericSensorTree, BooleanSensorTree, \
+                        AggregateSensorTree
 
 from .version import VERSION, VERSION_STR
 

File katcp/client.py

         msg : Message object
             The message to send.
         """
-        # TODO: should probably implement this as a queue of sockets and messages to send.
-        #       and have the queue processed in the main loop
+        # TODO: should probably implement this as a queue of sockets and
+        #       messages to send and have the queue processed in the main loop
         data = str(msg) + "\n"
         datalen = len(data)
         totalsent = 0
                 try:
                     sent = sock.send(data[totalsent:])
                 except socket.error, e:
-                    if len(e.args) == 2 and e.args[0] == errno.EAGAIN and sock is self._sock:
+                    if len(e.args) == 2 and e.args[0] == errno.EAGAIN and \
+                            sock is self._sock:
                         continue
                     else:
                         send_failed = True
             self._connect_failures += 1
             if self._connect_failures % 5 == 0:
                 # warn on every fifth failure
-                self._logger.warn("Failed to connect to %r: %s" % (self._bindaddr, e))
+                self._logger.warn("Failed to connect to %r: %s" %
+                                  (self._bindaddr, e))
             else:
-                self._logger.debug("Failed to connect to %r: %s" % (self._bindaddr, e))
+                self._logger.debug("Failed to connect to %r: %s" %
+                                   (self._bindaddr, e))
             sock.close()
             sock = None
 
                 except Exception:
                     e_type, e_value, trace = sys.exc_info()
                     reason = "\n".join(traceback.format_exception(
-                        e_type, e_value, trace, self._tb_limit
-                    ))
+                        e_type, e_value, trace, self._tb_limit))
                     self._logger.error("BAD COMMAND: %s" % (reason,))
                 else:
                     self.handle_message(msg)
         except Exception:
             e_type, e_value, trace = sys.exc_info()
             reason = "\n".join(traceback.format_exception(
-                e_type, e_value, trace, self._tb_limit
-            ))
+                e_type, e_value, trace, self._tb_limit))
             self._logger.error("Inform %s FAIL: %s" % (msg.name, reason))
 
     def handle_reply(self, msg):
         except Exception:
             e_type, e_value, trace = sys.exc_info()
             reason = "\n".join(traceback.format_exception(
-                e_type, e_value, trace, self._tb_limit
-            ))
+                e_type, e_value, trace, self._tb_limit))
             self._logger.error("Reply %s FAIL: %s" % (msg.name, reason))
 
     def handle_request(self, msg):
         except Exception:
             e_type, e_value, trace = sys.exc_info()
             reason = "\n".join(traceback.format_exception(
-                e_type, e_value, trace, self._tb_limit
-            ))
+                e_type, e_value, trace, self._tb_limit))
             self._logger.error("Request %s FAIL: %s" % (msg.name, reason))
 
     def unhandled_inform(self, msg):
 
     def run(self):
         """Process reply and inform messages from the server."""
-        self._logger.debug("Starting thread %s" % (threading.currentThread().getName()))
-        timeout = 0.5 # s
+        self._logger.debug("Starting thread %s" % (
+                threading.currentThread().getName()))
+        timeout = 0.5  # s
 
         # save globals so that the thread can run cleanly
         # even while Python is setting module globals to
         if not self._auto_reconnect:
             self._connect()
             if not self.is_connected():
-                raise KatcpClientError("Failed to connect to %r" % (self._bindaddr,))
+                raise KatcpClientError("Failed to connect to %r" %
+                                       (self._bindaddr,))
 
         self._running.set()
         while self._running.isSet():
             sock = self._sock
             if sock is not None:
                 try:
-                    readers, _writers, errors = _select(
-                        [sock], [], [sock], timeout
-                    )
+                    readers, _writers, errors = _select([sock], [], [sock],
+                                                        timeout)
                 except Exception, e:
                     # catch Exception because class of exception thrown
                     # various drastically between Mac and Linux
                         _sleep(timeout)
 
         self._disconnect()
-        self._logger.debug("Stopping thread %s" % (threading.currentThread().getName()))
+        self._logger.debug("Stopping thread %s" % (
+                threading.currentThread().getName()))
 
     def start(self, timeout=None, daemon=None, excepthook=None):
         """Start the client in a new thread.
     def __init__(self, host, port, tb_limit=20, timeout=5.0, logger=log,
                  auto_reconnect=True):
         super(BlockingClient, self).__init__(host, port, tb_limit=tb_limit,
-            logger=logger,auto_reconnect=auto_reconnect)
+                                             logger=logger,
+                                             auto_reconnect=auto_reconnect)
         self._request_timeout = timeout
 
         self._request_end = threading.Event()
     def __init__(self, host, port, tb_limit=20, timeout=5.0, logger=log,
                  auto_reconnect=True, use_ids=False):
         super(CallbackClient, self).__init__(host, port, tb_limit=tb_limit,
-            logger=logger,auto_reconnect=auto_reconnect)
+                                             logger=logger,
+                                             auto_reconnect=auto_reconnect)
 
         self._request_timeout = timeout
         self._use_ids = use_ids
         self._async_lock = threading.Lock()
 
         # pending requests
-        # msg_id -> (request_name, reply_cb, inform_cb, user_data, timer) callback tuples
+        # msg_id -> (request_name, reply_cb, inform_cb, user_data, timer)
+        #           callback tuples
         self._async_queue = {}
 
         # stack mapping request names to a stack of message ids
         # msg_name -> [ list of msg_ids ]
         self._async_id_stack = {}
 
-    def _push_async_request(self, msg_id, request_name, reply_cb, inform_cb, user_data, timer):
+    def _push_async_request(self, msg_id, request_name, reply_cb, inform_cb,
+                            user_data, timer):
         """Store the callbacks for a request we've sent so we
            can forward any replies and informs to them.
            """
         self._async_lock.acquire()
         try:
-            self._async_queue[msg_id] = (request_name, reply_cb, inform_cb, user_data, timer)
+            self._async_queue[msg_id] = (request_name, reply_cb, inform_cb,
+                                         user_data, timer)
             if request_name in self._async_id_stack:
                 self._async_id_stack[request_name].append(msg_id)
             else:
         finally:
             self._msg_id_lock.release()
 
-    def request(self, msg, reply_cb=None, inform_cb=None, user_data=None, timeout=None):
+    def request(self, msg, reply_cb=None, inform_cb=None, user_data=None,
+                timeout=None):
         """Send a request messsage.
 
         Parameters
         msg_id = self._next_id()
         timer = threading.Timer(timeout, self._handle_timeout, (msg_id,))
 
-        self._push_async_request(msg_id, msg.name, reply_cb, inform_cb, user_data, timer)
+        self._push_async_request(msg_id, msg.name, reply_cb, inform_cb,
+                                 user_data, timer)
         if self._use_ids:
             msg.mid = msg_id
         timer.start()
         def inform_cb(msg):
             informs.append(msg)
 
-        self.request(msg, reply_cb=reply_cb, inform_cb=inform_cb, timeout=timeout)
+        self.request(msg, reply_cb=reply_cb, inform_cb=inform_cb,
+                     timeout=timeout)
         done.wait()
         reply = replies[0]
 
         # inform_cb was passed to the request method.
         if self._use_ids:
             if msg.mid is not None:
-                _msg_name, _reply_cb, inform_cb, user_data, _timer = self._peek_async_request(msg.mid, None)
+                _msg_name, _reply_cb, inform_cb, user_data, _timer = \
+                    self._peek_async_request(msg.mid, None)
             else:
                 inform_cb, user_data = None, None
         else:
-            _msg_name, _reply_cb, inform_cb, user_data, _timer = self._peek_async_request(None, msg.name)
+            _msg_name, _reply_cb, inform_cb, user_data, _timer = \
+                self._peek_async_request(None, msg.name)
 
         if inform_cb is None:
             inform_cb = super(CallbackClient, self).handle_inform
         except Exception:
             e_type, e_value, trace = sys.exc_info()
             reason = "\n".join(traceback.format_exception(
-                e_type, e_value, trace, self._tb_limit
-            ))
-            self._logger.error("Callback inform %s FAIL: %s" % (msg.name, reason))
+                e_type, e_value, trace, self._tb_limit))
+            self._logger.error("Callback inform %s FAIL: %s" %
+                               (msg.name, reason))
 
     def _handle_timeout(self, msg_id):
         """Handle a timed out callback request.
         """
         # this may also result in reply_cb being None if no
         # reply_cb was passed to the request method
-        msg_name, reply_cb, _inform_cb, user_data, timer = self._pop_async_request(msg_id, None)
+        msg_name, reply_cb, _inform_cb, user_data, timer = \
+            self._pop_async_request(msg_id, None)
 
         if reply_cb is None:
             # this happens if no reply_cb was passed in to the request or
             return
 
-        timeout_msg = Message.reply(msg_name, "fail", "Timed out after %f seconds" % timer.interval)
+        timeout_msg = Message.reply(msg_name, "fail",
+                                    "Timed out after %f seconds" %
+                                    timer.interval)
 
         try:
             if user_data is None:
         except Exception:
             e_type, e_value, trace = sys.exc_info()
             reason = "\n".join(traceback.format_exception(
-                e_type, e_value, trace, self._tb_limit
-            ))
-            self._logger.error("Callback reply during timeout %s FAIL: %s" % (msg_name, reason))
+                e_type, e_value, trace, self._tb_limit))
+            self._logger.error("Callback reply during timeout %s FAIL: %s" %
+                               (msg_name, reason))
 
     def handle_reply(self, msg):
         """Handle a reply message related to the current request.
         # reply_cb was passed to the request method
         if self._use_ids:
             if msg.mid is not None:
-                _msg_name, reply_cb, _inform_cb, user_data, timer = self._pop_async_request(msg.mid, None)
+                _msg_name, reply_cb, _inform_cb, user_data, timer = \
+                    self._pop_async_request(msg.mid, None)
             else:
                 reply_cb, user_data, timer = None, None, None
         else:
-            _msg_name, reply_cb, _inform_cb, user_data, timer = self._pop_async_request(None, msg.name)
+            _msg_name, reply_cb, _inform_cb, user_data, timer = \
+                self._pop_async_request(None, msg.name)
 
         if timer is not None:
             timer.cancel()
         except Exception:
             e_type, e_value, trace = sys.exc_info()
             reason = "\n".join(traceback.format_exception(
-                e_type, e_value, trace, self._tb_limit
-            ))
-            self._logger.error("Callback reply %s FAIL: %s" % (msg.name, reason))
+                e_type, e_value, trace, self._tb_limit))
+            self._logger.error("Callback reply %s FAIL: %s" %
+                               (msg.name, reason))

File katcp/core.py

 import time
 import warnings
 
+
 class Message(object):
     """Represents a KAT device control language message.
 
 
     ## @brief Mapping from escape character to corresponding unescaped string.
     ESCAPE_LOOKUP = {
-        "\\" : "\\",
+        "\\": "\\",
         "_": " ",
         "0": "\0",
         "n": "\n",
         if arguments is None:
             self.arguments = []
         else:
-            self.arguments = [type(x) is float and repr(x) or str(x) for x in arguments]
+            self.arguments = [type(x) is float and repr(x) or str(x)
+                              for x in arguments]
 
         # check message type
 
 
         if not name:
             raise KatcpSyntaxError("Command missing command name.")
-        if not name.replace("-","").isalnum():
+        if not name.replace("-", "").isalnum():
             raise KatcpSyntaxError("Command name should consist only of"
                                 " alphanumeric characters and dashes (got %r)."
                                 % (name,))
         else:
             mid_str = ""
 
-        return "%s%s%s%s" % (self.TYPE_SYMBOLS[self.mtype], self.name, mid_str, arg_str)
+        return "%s%s%s%s" % (self.TYPE_SYMBOLS[self.mtype], self.name,
+                             mid_str, arg_str)
 
     def __repr__(self):
         """ Return message displayed in a readable form
         return "\\" + self.REVERSE_ESCAPE_LOOKUP[match.group()]
 
     def reply_ok(self):
-        """Return True if the message is a reply and its first argument is 'ok'."""
-        return self.mtype == self.REPLY and self.arguments and self.arguments[0] == self.OK
+        """Return True if this is a reply and its first argument is 'ok'."""
+        return (self.mtype == self.REPLY and self.arguments and
+                self.arguments[0] == self.OK)
 
     # * and ** magic useful here
     # pylint: disable-msg = W0142
     WHITESPACE_RE = re.compile(r"[ \t]+")
 
     ## @brief Regular expression matching name and ID
-    NAME_RE = re.compile(r"^(?P<name>[a-zA-Z][a-zA-Z0-9\-]*)(\[(?P<id>[0-9]+)\])?$")
+    NAME_RE = re.compile(
+        r"^(?P<name>[a-zA-Z][a-zA-Z0-9\-]*)(\[(?P<id>[0-9]+)\])?$")
 
     def _unescape_match(self, match):
         """Given an re.Match, unescape the escape code it represents."""
         mtype = self.TYPE_SYMBOL_LOOKUP[type_char]
 
         # find command and arguments name
-        # (removing possible empty argument resulting from whitespace at end of command)
+        # (removing possible empty argument resulting from whitespace at end
+        #  of command)
         parts = self.WHITESPACE_RE.split(line)
         if not parts[-1]:
             del parts[-1]
             name = match.group('name')
             mid = match.group('id')
         else:
-            raise KatcpSyntaxError("Bad message name (and possibly id) %r." % (name,))
+            raise KatcpSyntaxError("Bad message name (and possibly id) %r." %
+                                   (name,))
 
         return Message(mtype, name, arguments, mid)
 
         mcs._request_handlers = {}
         mcs._inform_handlers = {}
         mcs._reply_handlers = {}
+
         def convert(prefix, name):
             """Convert a method name to the corresponding command name."""
-            return name[len(prefix):].replace("_","-")
+            return name[len(prefix):].replace("_", "-")
+
         for name in dir(mcs):
             if not callable(getattr(mcs, name)):
                 continue
     """
     def __init__(self, excepthook=None, *args, **kwargs):
         if excepthook is None:
-            excepthook = getattr(threading.currentThread(), "_excepthook", None)
+            excepthook = getattr(threading.currentThread(), "_excepthook",
+                                 None)
         self._excepthook = excepthook
         # evil hack to support subclasses that override run
         self._old_run = self.run
 
 from .kattypes import Int, Float, Bool, Discrete, Lru, Str, Timestamp
 
+
 class Sensor(object):
     """Instantiate a new sensor object.
 
     # @brief String contain the units for the sensor value.
 
     ## @var params
-    # @brief List of strings containing the additional parameters (length and interpretation
-    # are specific to the sensor type)
+    # @brief List of strings containing the additional parameters (length and
+    #        interpretation are specific to the sensor type)
 
-    def __init__(self, sensor_type, name, description, units, params=None, default=None):
+    def __init__(self, sensor_type, name, description, units, params=None,
+                 default=None):
         if params is None:
             params = []
 
         if type_string in cls.SENSOR_TYPE_LOOKUP:
             return cls.SENSOR_TYPE_LOOKUP[type_string]
         else:
-            raise KatcpSyntaxError("Invalid sensor type string %s" % type_string)
+            raise KatcpSyntaxError("Invalid sensor type string %s" %
+                                   type_string)
 
     @classmethod
     def parse_params(cls, sensor_type, formatted_params):

File katcp/kattypes.py

 # XXX how about a mapping from python types -> kattypes, so creating
 #     a sensor would not require importing kattypes
 
+
 class KatcpType(object):
     """Class representing a KATCP type.
 
     def __init__(self, values, case_insensitive=False, **kwargs):
         super(Discrete, self).__init__(**kwargs)
         self._case_insensitive = case_insensitive
-        self._values = list(values) # just to preserve ordering
+        self._values = list(values)  # just to preserve ordering
         self._valid_values = set(values)
         if self._case_insensitive:
-            self._valid_values_lower = set([val.lower() for val in self._values])
+            self._valid_values_lower = set([val.lower()
+                                            for val in self._values])
 
     def check(self, value):
         """Check whether the value in the set of allowed values.
 
     name = "timestamp"
 
-    encode = lambda self, value: "%i" % (int(float(value)*1000),)
+    encode = lambda self, value: "%i" % (int(float(value) * 1000),)
 
     def decode(self, value):
         try:
-            return float(value)/1000
+            return float(value) / 1000
         except:
-            raise ValueError("Could not parse value '%s' as timestamp." % value)
+            raise ValueError("Could not parse value '%s' as timestamp." %
+                             value)
 
 
 class TimestampOrNow(Timestamp):
-    """KatcpType representing either a Timestamp or the special value :const:`katcp.kattypes.TimestampOrNow.NOW`.
+    """KatcpType representing either a Timestamp or the special value
+       :const:`katcp.kattypes.TimestampOrNow.NOW`.
 
-       Floats are encoded as for :class:`katcp.kattypes.Timestamp`. :const:`katcp.kattypes.TimestampOrNow.NOW`
-       is encoded as the string "now".
+       Floats are encoded as for :class:`katcp.kattypes.Timestamp`.
+       :const:`katcp.kattypes.TimestampOrNow.NOW` is encoded as the string
+       "now".
        """
 
     name = "timestamp_or_now"
         try:
             return "%.15g" % (value * 1000.0)
         except:
-            raise ValueError("Could not encode value %r as strict timestamp." % value)
+            raise ValueError("Could not encode value %r as strict timestamp." %
+                             value)
 
     def decode(self, value):
         try:
             _int_parts = [int(x) for x in parts]
             return float(value) / 1000.0
         except:
-            raise ValueError("Could not parse value '%s' as strict timestamp." % value)
+            raise ValueError("Could not parse value '%s' as strict timestamp."
+                             % value)
 
     def check(self, value):
         """Check whether the value is positive.
         try:
             return struct.pack(self._fmt, *value)
         except struct.error, e:
-            raise ValueError("Could not pack %s into struct with format %s: %s" % (value, self._fmt, e))
+            raise ValueError("Could not pack %s into struct with format "
+                             "%s: %s" % (value, self._fmt, e))
 
     def decode(self, value):
         try:
             return struct.unpack(self._fmt, value)
         except struct.error, e:
-            raise ValueError("Could not unpack %s from struct with format %s: %s" % (value, self._fmt, e))
+            raise ValueError("Could not unpack %s from struct with format "
+                             "%s: %s" % (value, self._fmt, e))
 
 
 class Regex(Str):
 
     _re_flags = [
         ('I', re.I), ('L', re.L), ('M', re.M),
-        ('S', re.S), ('U', re.U), ('X', re.X)
+        ('S', re.S), ('U', re.U), ('X', re.X),
     ]
 
     def __init__(self, regex, **kwargs):
 
     def check(self, value):
         if not self._compiled.match(value):
-            raise ValueError("Value '%s' does not match regex '%s' with flags '%s'."
-                % (value, self._pattern, self._flags))
+            raise ValueError("Value '%s' does not match regex '%s' with flags"
+                             " '%s'." % (value, self._pattern, self._flags))
 
 
 class DiscreteMulti(Discrete):
     def decode(self, value):
         if self.all_keyword and value == self.all_keyword:
             return sorted(list(self._valid_values), key=str.lower)
-        return sorted([v.strip() for v in value.split(self.separator)], key=str.lower)
+        return sorted([v.strip() for v in value.split(self.separator)],
+                      key=str.lower)
 
     def __init__(self, values, all_keyword="all", separator=",", **kwargs):
         self.all_keyword = all_keyword
         try:
             return self._kattype.unpack(value)
         except ValueError, message:
-            raise FailReply("Error in parameter %s (%s): %s" % (self.position, self.name, message))
+            raise FailReply("Error in parameter %s (%s): %s" %
+                            (self.position, self.name, message))
 
 
 ## request, return_reply and inform method decorators
     def decorator(handler):
         argnames = []
 
-        # If this decorator is on the outside, get the parameter names which have been preserved by the other decorator
+        # If this decorator is on the outside, get the parameter names which
+        # have been preserved by the other decorator
         all_argnames = getattr(handler, "_orig_argnames", None)
 
         if all_argnames is None:
         has_sock = len(all_argnames) > 1 and all_argnames[1] == "sock"
 
         params_start = 1
-        if has_sock: params_start += 1
-        if include_msg: params_start += 1
+        if has_sock:
+            params_start += 1
+        if include_msg:
+            params_start += 1
         # Get other parameter names
         argnames = all_argnames[params_start:]
 
 
         raw_handler.__name__ = handler.__name__
         raw_handler.__doc__ = handler.__doc__
-        # explicitly note that this decorator has been run, so that return_reply can know if it's on the outside.
+        # explicitly note that this decorator has been run, so that
+        # return_reply can know if it's on the outside.
         raw_handler._request_decorated = True
         return raw_handler
 
        thus an alias.
        """
 
+
 def return_reply(*types):
     """Decorator for returning replies from request handler methods
 
     """
     def decorator(handler):
         if not handler.__name__.startswith("request_"):
-            raise ValueError("This decorator can only be used on a katcp request handler.")
-        msgname = handler.__name__[8:].replace("_","-")
+            raise ValueError("This decorator can only be used on a katcp"
+                             " request handler.")
+        msgname = handler.__name__[8:].replace("_", "-")
+
         def raw_handler(self, *args):
             reply_args = handler(self, *args)
             return make_reply(msgname, types, reply_args)
 
         if not getattr(handler, "_request_decorated", False):
             # We are on the inside.
-            # We must preserve the original function parameter names for the request decorator
+            # We must preserve the original function parameter names for the
+            # request decorator
             raw_handler._orig_argnames = inspect.getargspec(handler)[0]
 
         return raw_handler
 
     return decorator
 
+
 def send_reply(*types):
     """Decorator for sending replies from request callback methods
 
 
     return decorator
 
+
 def make_reply(msgname, types, arguments):
     """Helper method for constructing a reply message from a list or tuple
 
         return Message.reply(msgname, *pack_types((Str(),) + types, arguments))
     raise ValueError("First returned value must be 'ok' or 'fail'.")
 
+
 def unpack_types(types, args, argnames):
     """Parse arguments according to types list.
 
         name = ""
         if i < len(argnames):
             name = argnames[i]
-        params.append(Parameter(i+1, name, kattype))
+        params.append(Parameter(i + 1, name, kattype))
 
     # if len(args) < len(types) this passes in None for missing args
     return map(lambda param, arg: param.unpack(arg), params, args)
 
+
 def pack_types(types, args):
     """Pack arguments according the the types list.
 

File katcp/sampling.py

 
 # pylint: disable-msg=W0142
 
+
 class SampleStrategy(object):
     """Base class for strategies for sampling sensors.
 
     def __init__(self, inform_callback, sensor, *params):
         SampleStrategy.__init__(self, inform_callback, sensor, *params)
         if len(params) > 1:
-            raise ValueError("The 'event' strategy takes one or zero parameters.")
+            raise ValueError("The 'event' strategy takes one or"
+                             " zero parameters.")
         elif len(params) == 1:
             self._minTimeSep = float(params[0]) / 1000.0
         else:
     def __init__(self, inform_callback, sensor, *params):
         SampleStrategy.__init__(self, inform_callback, sensor, *params)
         if len(params) != 1:
-            raise ValueError("The 'differential' strategy takes one parameter.")
-        if sensor._sensor_type not in (Sensor.INTEGER, Sensor.FLOAT, Sensor.TIMESTAMP):
-            raise ValueError("The 'differential' strategy is only valid for float, integer and timestamp sensors.")
+            raise ValueError("The 'differential' strategy takes"
+                             " one parameter.")
+        if sensor._sensor_type not in (Sensor.INTEGER, Sensor.FLOAT,
+                                       Sensor.TIMESTAMP):
+            raise ValueError("The 'differential' strategy is only valid for"
+                             " float, integer and timestamp sensors.")
         if sensor._sensor_type == Sensor.INTEGER:
             self._threshold = int(params[0])
             if self._threshold <= 0:
                 raise ValueError("The diff amount must be a positive float.")
         else:
             # _sensor_type must be Sensor.TIMESTAMP
-            self._threshold = int(params[0]) / 1000.0 # convert threshold in ms to s
+            self._threshold = int(params[0]) / 1000.0  # convert threshold to s
             if self._threshold <= 0:
-                raise ValueError("The diff amount must be a positive number of milliseconds.")
+                raise ValueError("The diff amount must be a positive number"
+                                 " of milliseconds.")
         self._lastStatus = None
         self._lastValue = None
 
     def update(self, sensor):
         _timestamp, status, value = sensor.read()
-        if status != self._lastStatus or abs(value - self._lastValue) > self._threshold:
+        if status != self._lastStatus or \
+                abs(value - self._lastValue) > self._threshold:
             self._lastStatus = status
             self._lastValue = value
             self.inform()
         self._wakeEvent = threading.Event()
         self._heap = []
         self._logger = logger
-        # set daemon True so that the app can stop even if the thread is running
+        # set daemon True so that the app can stop even if the thread
+        # is running
         self.setDaemon(True)
 
     def add_strategy(self, strategy):
 
     def run(self):
         """Run the sample reactor."""
-        self._logger.debug("Starting thread %s" % (threading.currentThread().getName()))
+        self._logger.debug("Starting thread %s" %
+                           (threading.currentThread().getName()))
         heap = self._heap
         wake = self._wakeEvent
 
                     _push(heap, (next_time, strategy))
                 except Exception, e:
                     self._logger.exception(e)
-                    # push ten seconds into the future and hope whatever was wrong
-                    # sorts itself out
+                    # push ten seconds into the future and hope whatever was
+                    # wrong sorts itself out
                     _push(heap, (next_time + 10.0, strategy))
             else:
                 wake.wait()

File katcp/sensortree.py

 
         Any sensors that have no dependency links are removed from the tree and
         the tree detaches from each sensor removed. After all dependency links
-        have been removed the parent is recalculated. Links that don't exist are
-        ignored.
+        have been removed the parent is recalculated. Links that don't exist
+        are ignored.
 
         Parameters
         ----------
                     continue
                 self._parent_to_children[parent].discard(child)
                 self._child_to_parents[child].discard(parent)
-                if not self._child_to_parents[child] and not self._parent_to_children[child]:
+                if not self._child_to_parents[child] and \
+                        not self._parent_to_children[child]:
                     self._remove_sensor(child)
                     old_sensors.append(child)
-            if not self._child_to_parents[parent] and not self._parent_to_children[parent]:
+            if not self._child_to_parents[parent] and \
+                    not self._parent_to_children[parent]:
                 self._remove_sensor(parent)
                 old_sensors.append(parent)
 
     >>> tree = AggregateSensorTree()
     >>> def add_rule(parent, children):
     >>>     parent.set_value(sum(child.value() for child in children))
-    >>> sensor1 = Sensor(Sensor.INTEGER, "sensor1", "First sensor", "", [-1000, 1000])
-    >>> sensor2 = Sensor(Sensor.INTEGER, "sensor2", "Second sensor", "", [-1000, 1000])
+    >>> sensor1 = Sensor(Sensor.INTEGER, "sensor1", "First sensor", "",
+    ...                  [-1000, 1000])
+    >>> sensor2 = Sensor(Sensor.INTEGER, "sensor2", "Second sensor", "",
+    ...                  [-1000, 1000])
     >>> agg = Sensor(Sensor.INTEGER, "sum", "The total", "", [-2000, 2000])
     >>> tree.add(agg, add_rule, (sensor1, sensor2))
     >>> agg.value()
     >>> tree.remove(agg)
     >>> agg.value()
 
-    Example where rules need to be added before dependent sensors are available::
+    Example where rules need to be added before dependent sensors are
+    available::
 
     >>> from katcp import Sensor, AggregateSensorTree
     >>> tree = AggregateSensorTree()
     >>> agg = Sensor(Sensor.INTEGER, "sum", "The total", "", [-2000, 2000])
     >>> tree.add_delayed(agg, add_rule, ("sensor1", "sensor2"))
     >>> agg.value()
-    >>> sensor1 = Sensor(Sensor.INTEGER, "sensor1", "First sensor", "", [-1000, 1000])
+    >>> sensor1 = Sensor(Sensor.INTEGER, "sensor1", "First sensor", "",
+    ...                  [-1000, 1000])
     >>> sensor1.set_value(5)
     >>> tree.register_sensor(sensor1)
     >>> agg.value() # still 0
-    >>> sensor2 = Sensor(Sensor.INTEGER, "sensor2", "Second sensor", "", [-1000, 1000])
+    >>> sensor2 = Sensor(Sensor.INTEGER, "sensor2", "Second sensor", "",
+    ...                  [-1000, 1000])
     >>> sensor2.set_value(3)
     >>> tree.register_sensor(sensor2)
     >>> agg.value() # now 8
             The sensors the aggregate sensor depends on.
         """
         if parent in self._aggregates or parent in self._incomplete_aggregates:
-            raise ValueError("Sensor %r already has an aggregate rule associated" % parent)
+            raise ValueError("Sensor %r already has an aggregate rule"
+                             " associated" % parent)
         self._aggregates[parent] = (rule_function, children)
         self.add_links(parent, children)
 
         rule_function : f(parent, children)
             Function to update the parent sensor value.
         child_names : sequence of str
-            The names of the sensors the aggregate sensor depends on. These sensor
-            must be registered using :meth:`register_sensor` to become active.
+            The names of the sensors the aggregate sensor depends on. These
+            sensor must be registered using :meth:`register_sensor` to become
+            active.
         """
         if parent in self._aggregates or parent in self._incomplete_aggregates:
-            raise ValueError("Sensor %r already has an aggregate rule associated" % parent)
+            raise ValueError("Sensor %r already has an aggregate rule"
+                             " associated" % parent)
         reg = self._registered_sensors
         names = set(name for name in child_names if name not in reg)
         sensors = set(reg[name] for name in child_names if name in reg)
         if names:
-            self._incomplete_aggregates[parent] = (rule_function, names, sensors)
+            self._incomplete_aggregates[parent] = (rule_function, names,
+                                                   sensors)
         else:
             self.add(parent, rule_function, sensors)
 
     def register_sensor(self, child):
-        """Register a sensor required by an aggregate sensor registered with add_delayed.
+        """Register a sensor required by an aggregate sensor registered with
+        add_delayed.
 
         Parameters
         ----------
             A child sensor required by one or more delayed aggregate sensors.
         """
         if child.name in self._registered_sensors:
-            raise ValueError("Sensor %r already registered with aggregate tree" % child)
+            raise ValueError("Sensor %r already registered with aggregate"
+                             " tree" % child)
         child_name = child.name
         self._registered_sensors[child_name] = child
         completed = []
-        for parent, (_rule, names, sensors) in self._incomplete_aggregates.iteritems():
+        for parent, (_rule, names, sensors) in \
+                self._incomplete_aggregates.iteritems():
             if child_name in names:
                 names.remove(child_name)
                 sensors.add(child)
                 if not names:
                     completed.append(parent)
         for parent in completed:
-            rule_function, _names, sensors = self._incomplete_aggregates[parent]
+            rule_function, _names, sensors = \
+                self._incomplete_aggregates[parent]
             del self._incomplete_aggregates[parent]
             self.add(parent, rule_function, sensors)
 
             The aggregate sensor to remove.
         """
         if parent not in self._aggregates:
-            raise ValueError("Sensor %r does not have an aggregate rule associated" % parent)
+            raise ValueError("Sensor %r does not have an aggregate rule"
+                             " associated" % parent)
         children = self.children(parent)
         self.remove_links(parent, children)
         del self._aggregates[parent]

File katcp/server.py

 
         # sockets and data
         self._data_lock = threading.Lock()
-        self._socks = [] # list of client sockets
-        self._waiting_chunks = {} # map from client sockets to partial messages
-        self._sock_locks = {} # map from client sockets to socket sending locks
+        self._socks = []  # list of client sockets
+        self._waiting_chunks = {}  # map from client sockets to messages pieces
+        self._sock_locks = {}  # map from client sockets to sending locks
 
     def _log_msg(self, level_name, msg, name, timestamp=None):
         """Create a katcp logging inform message.
             timestamp = time.time()
         return Message.inform("log",
                 level_name,
-                str(int(timestamp * 1000.0)), # time since epoch in ms
+                str(int(timestamp * 1000.0)),  # time since epoch in ms
                 name,
                 msg,
         )
                 except Exception:
                     e_type, e_value, trace = sys.exc_info()
                     reason = "\n".join(traceback.format_exception(
-                        e_type, e_value, trace, self._tb_limit
-                    ))
+                        e_type, e_value, trace, self._tb_limit))
                     self._logger.error("BAD COMMAND: %s" % (reason,))
                     self.inform(sock, self._log_msg("error", reason, "root"))
                 else:
             except Exception:
                 e_type, e_value, trace = sys.exc_info()
                 reason = "\n".join(traceback.format_exception(
-                    e_type, e_value, trace, self._tb_limit
-                ))
+                    e_type, e_value, trace, self._tb_limit))
                 self._logger.error("Request %s FAIL: %s" % (msg.name, reason))
                 reply = Message.reply(msg.name, "fail", reason)
         else:
             except Exception:
                 e_type, e_value, trace = sys.exc_info()
                 reason = "\n".join(traceback.format_exception(
-                    e_type, e_value, trace, self._tb_limit
-                ))
+                    e_type, e_value, trace, self._tb_limit))
                 self._logger.error("Inform %s FAIL: %s" % (msg.name, reason))
         else:
             self._logger.warn("%s INVALID: Unknown inform." % (msg.name,))
             except Exception:
                 e_type, e_value, trace = sys.exc_info()
                 reason = "\n".join(traceback.format_exception(
-                    e_type, e_value, trace, self._tb_limit
-                ))
+                    e_type, e_value, trace, self._tb_limit))
                 self._logger.error("Reply %s FAIL: %s" % (msg.name, reason))
         else:
             self._logger.warn("%s INVALID: Unknown reply." % (msg.name,))
         msg : Message object
             The message to send.
         """
-        # TODO: should probably implement this as a queue of sockets and messages to send.
-        #       and have the queue processed in the main loop
+        # TODO: should probably implement this as a queue of sockets and
+        #       messages to send and have the queue processed in the main
+        #       loop.
         data = str(msg) + "\n"
         datalen = len(data)
         totalsent = 0
         # Log all sent messages here so no one else has to.
         self._logger.debug(data)
 
-        # sends are locked per-socket -- i.e. only one send per socket at a time
+        # sends are locked per-socket -- i.e. only one send per socket at
+        # a time
         lock = self._sock_locks.get(sock)
         if lock is None:
             try:
                 client_name = sock.getpeername()
             except socket.error:
                 client_name = "<disconnected client>"
-            msg = "Attempt to send to a socket %s which is no longer a client." % (client_name,)
+            msg = "Attempt to send to a socket %s which is no longer a" \
+                " client." % (client_name,)
             self._logger.warn(msg)
             return
 
 
     def run(self):
         """Listen for clients and process their requests."""
-        timeout = 0.5 # s
+        timeout = 0.5  # s
 
         # save globals so that the thread can run cleanly
         # even while Python is setting module globals to
             all_socks = self._socks + [self._sock]
             try:
                 readers, _writers, errors = _select(
-                    all_socks, [], all_socks, timeout
-                )
+                    all_socks, [], all_socks, timeout)
             except Exception, e:
                 # catch Exception because class of exception thrown
                 # varies drastically between Mac and Linux
                 # search for broken socket
                 for sock in list(self._socks):
                     try:
-                        _readers, _writers, _errors = _select([sock], [], [], 0)
+                        _readers, _writers, _errors = _select([sock], [], [],
+                                                              0)
                     except Exception, e:
                         self._remove_socket(sock)
-                        self.on_client_disconnect(sock, "Client socket died with error %s" % (e,), False)
+                        self.on_client_disconnect(sock, "Client socket died"
+                                                  " with error %s" % (e,),
+                                                  False)
                 # check server socket
                 try:
-                    _readers, _writers, _errors = _select([self._sock], [], [], 0)
+                    _readers, _writers, _errors = _select([self._sock], [], [],
+                                                          0)
                 except:
-                    self._logger.warn("Server socket died, attempting to restart it.")
+                    self._logger.warn("Server socket died, attempting to"
+                                      " restart it.")
                     self._sock = self._bind(self._bindaddr)
                 # try select again
                 continue
                 else:
                     # client socket died, remove it
                     self._remove_socket(sock)
-                    self.on_client_disconnect(sock, "Client socket died", False)
+                    self.on_client_disconnect(sock, "Client socket died",
+                                              False)
 
             for sock in readers:
                 if sock is self._sock:
                         self.on_client_disconnect(sock, "Socket EOF", False)
 
         for sock in list(self._socks):
-            self.on_client_disconnect(sock, "Device server shutting down.", True)
+            self.on_client_disconnect(sock, "Device server shutting down.",
+                                      True)
             self._remove_socket(sock)
 
         self._sock.close()
         super(DeviceServer, self).__init__(*args, **kwargs)
         self.log = DeviceLogger(self, python_logger=self._logger)
         self._restart_queue = None
-        self._sensors = {} # map names to sensor objects
-        self._reactor = None # created in run
+        self._sensors = {}  # map names to sensor objects
+        self._reactor = None  # created in run
         # map client sockets to map of sensors -> sampling strategies
         self._strategies = {}
         # strat lock (should be held for updates to _strategies)
         """
         self._strat_lock.acquire()
         try:
-            self._strategies[sock] = {} # map of sensors -> sampling strategies
+            self._strategies[sock] = {}  # map sensors -> sampling strategies
         finally:
             self._strat_lock.release()
         self.inform(sock, Message.inform("version", self.version()))
             self.inform(sock, Message.inform("disconnect", msg))
 
     def build_state(self):
-        """Return a build state string in the form name-major.minor[(a|b|rc)n]"""
+        """Return a build state string in the form
+        name-major.minor[(a|b|rc)n]
+        """
         return "%s-%s.%s%s" % self.BUILD_INFO
 
     def version(self):
     def add_sensor(self, sensor):
         """Add a sensor to the device.
 
-        Usually called inside .setup_sensors() but may be called from elsewhere.
+        Usually called inside .setup_sensors() but may be called from
+        elsewhere.
 
         Parameters
         ----------
     def set_restart_queue(self, restart_queue):
         """Set the restart queue.
 
-        When the device server should be restarted, it will be added to the queue.
+        When the device server should be restarted, it will be added to the
+        queue.
 
         Parameters
         ----------
     def request_help(self, sock, msg):
         """Return help on the available requests.
 
-        Return a description of the available requests using a seqeunce of #help informs.
+        Return a description of the available requests using a seqeunce of
+        #help informs.
 
         Parameters
         ----------
         request : str, optional
-            The name of the request to return help for (the default is to return help for all requests).
+            The name of the request to return help for (the default is to
+            return help for all requests).
 
         Informs
         -------
 
         Parameters
         ----------
-        level : {'all', 'trace', 'debug', 'info', 'warn', 'error', 'fatal', 'off'}, optional
-            Name of the logging level to set the device server to (the default is to leave the log level unchanged).
+        level : {'all', 'trace', 'debug', 'info', 'warn', 'error', 'fatal', \
+                 'off'}, optional
+            Name of the logging level to set the device server to (the default
+            is to leave the log level unchanged).
 
         Returns
         -------
         success : {'ok', 'fail'}
             Whether the request succeeded.
-        level : {'all', 'trace', 'debug', 'info', 'warn', 'error', 'fatal', 'off'}
+        level : {'all', 'trace', 'debug', 'info', 'warn', 'error', 'fatal', \
+                 'off'}
             The log level after processing the request.
 
         Examples
         ----------
         name : str, optional
             Name of the sensor to list (the default is to list all sensors).
-            If name starts and ends with '/' it is treated as a regular expression and
-            all sensors whose names contain the regular expression are returned.
+            If name starts and ends with '/' it is treated as a regular
+            expression and all sensors whose names contain the regular
+            expression are returned.
 
         Informs
         -------
         type : str
             Type of the named sensor.
         params : list of str, optional
-            Additional sensor parameters (type dependent). For integer and float
-            sensors the additional parameters are the minimum and maximum sensor
-            value. For discrete sensors the additional parameters are the allowed
-            values. For all other types no additional parameters are sent.
+            Additional sensor parameters (type dependent). For integer and
+            float sensors the additional parameters are the minimum and maximum
+            sensor value. For discrete sensors the additional parameters are
+            the allowed values. For all other types no additional parameters
+            are sent.
 
         Returns
         -------
         Parameters
         ----------
         name : str, optional
-            Name of the sensor to poll (the default is to send values for all sensors).
-            If name starts and ends with '/' it is treated as a regular expression and
-            all sensors whose names contain the regular expression are returned.
+            Name of the sensor to poll (the default is to send values for all
+            sensors). If name starts and ends with '/' it is treated as a
+            regular expression and all sensors whose names contain the regular
+            expression are returned.
 
         Informs
         -------
         timestamp : float
-            Timestamp of the sensor reading in milliseconds since the Unix epoch.
+            Timestamp of the sensor reading in milliseconds since the Unix
+            epoch.
         count : {1}
-            Number of sensors described in this #sensor-value inform. Will always
-            be one. It exists to keep this inform compatible with #sensor-status.
+            Number of sensors described in this #sensor-value inform. Will
+            always be one. It exists to keep this inform compatible with
+            #sensor-status.
         name : str
             Name of the sensor whose value is being reported.
         value : object
                     sorted(self._sensors.iteritems()) if name_filter(name)]
 
         if exact and not sensors:
-            return Message.reply("sensor-value", "fail", "Unknown sensor name.")
+            return Message.reply("sensor-value", "fail",
+                                 "Unknown sensor name.")
 
         for name, sensor in sensors:
             timestamp_ms, status, value = sensor.read_formatted()
         ----------
         name : str
             Name of the sensor whose sampling strategy to query or configure.
-        strategy : {'none', 'auto', 'event', 'differential', 'period'}, optional
-            Type of strategy to use to report the sensor value. The differential
-            strategy type may only be used with integer or float sensors.
+        strategy : {'none', 'auto', 'event', 'differential', \
+                    'period'}, optional
+            Type of strategy to use to report the sensor value. The
+            differential strategy type may only be used with integer or float
+            sensors.
         params : list of str, optional
             Additional strategy parameters (dependent on the strategy type).
             For the differential strategy, the parameter is an integer or float
             giving the amount by which the sensor value may change before an
-            updated value is sent. For the period strategy, the parameter is the
-            period to sample at in milliseconds. For the event strategy, an
+            updated value is sent. For the period strategy, the parameter is
+            the period to sample at in milliseconds. For the event strategy, an
             optional minimum time between updates in milliseconds may be given.
 
         Returns
 
         current_strategy = self._strategies[sock].get(sensor, None)
         if not current_strategy:
-            current_strategy = SampleStrategy.get_strategy("none", lambda msg: None, sensor)
+            current_strategy = SampleStrategy.get_strategy("none",
+                                                           lambda msg: None,
+                                                           sensor)
 
         strategy, params = current_strategy.get_sampling_formatted()
         return Message.reply("sensor-sampling", "ok", name, strategy, *params)
 
-
     def request_watchdog(self, sock, msg):
         """Check that the server is still alive.
 
     ALL, TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF = range(8)
 
     ## @brief List of logging level names.
-    LEVELS = [ "all", "trace", "debug", "info", "warn",
-               "error", "fatal", "off" ]
+    LEVELS = ["all", "trace", "debug", "info", "warn",
+              "error", "fatal", "off"]
 
     ## @brief Map of Python logging level to corresponding to KATCP levels
     PYTHON_LEVEL = {
             Arguments to pass to log format string. Final message text is
             created using: msg % args.
         kwargs : additional keyword parameters
-            Allowed keywords are 'name' and 'timestamp'. The name is the name of the logger to
-            log the message to. If not given the name defaults to the root logger. The timestamp
-            is a float in seconds. If not given the timestamp defaults to the current time.
+            Allowed keywords are 'name' and 'timestamp'. The name is the name
+            of the logger to log the message to. If not given the name defaults
+            to the root logger. The timestamp is a float in seconds. If not
+            given the timestamp defaults to the current time.
         """
         if self._python_logger is not None:
             self._python_logger.log(self.PYTHON_LEVEL[level], msg, *args)
             if name is None:
                 name = self._root_logger_name
             self._device_server.mass_inform(
-                self._device_server._log_msg(self.level_name(level), msg % args,
-                    name, timestamp=timestamp
-                )
-            )
+                self._device_server._log_msg(self.level_name(level),
+                                             msg % args, name,
+                                             timestamp=timestamp))
 
     def trace(self, msg, *args, **kwargs):
         """Log a trace message."""
             The #log message to create a log entry from.
         """
         (level, timestamp, name, message) = tuple(msg.arguments)
-        #created = float(timestamp) * 1e-6
-        #msecs = int(timestamp) % 1000
         log_string = "%s %s: %s" % (timestamp, name, message)
         logger.log({"trace": 0,
                     "debug": logging.DEBUG,
                     "info": logging.INFO,
                     "warn": logging.WARN,
                     "error": logging.ERROR,
-                    "fatal": logging.FATAL}[level], log_string)#, extra={"created": created})
+                    "fatal": logging.FATAL}[level], log_string)

File katcp/test/__init__.py

 except ImportError:
     ply = None
 
+
 def suite():
     loader = unittest.TestLoader()
     suite = unittest.TestSuite()
     if ply is not None:
         suite.addTests(loader.loadTestsFromModule(test_katcp_bnf))
     return suite
-

File katcp/test/test_client.py

         time.sleep(1.25)
 
         # check that client reconnected
-        self.assertTrue(sock is not self.client._sock, "Expected %r to not be %r" % (sock, self.client._sock))
+        self.assertTrue(sock is not self.client._sock,
+                        "Expected %r to not be %r" % (sock, self.client._sock))
         self.assertEqual(sockname, self.client._sock.getpeername())
 
     def test_daemon_value(self):
         """Test passing in an excepthook to client start method."""
         exceptions = []
         except_event = threading.Event()
+
         def excepthook(etype, value, traceback):
             """Keep track of exceptions."""
             exceptions.append(etype)
                 katcp.Message.request("slow-command", "0.5"),
                 timeout=0.001)
         except RuntimeError, e:
-            self.assertEqual(str(e), "Request slow-command timed out after 0.001 seconds.")
+            self.assertEqual(str(e), "Request slow-command timed out after"
+                             " 0.001 seconds.")
         else:
             self.assertFalse("Expected timeout on request")
 
         self.client._inform_handlers["help"] = handle_help_message
         self.client._reply_handlers["help"] = handle_help_message
 
-        self.client.request(
-            katcp.Message.request("help")
-        )
+        self.client.request(katcp.Message.request("help"))
 
         time.sleep(0.1)
 
         self._assert_msgs_like(help_messages,
-            [("#help ", "")]*13 +
-            [("!help ok 13", "")]
-        )
+            [("#help ", "")] * 13 +
+            [("!help ok 13", "")])
 
     def test_timeout(self):
         """Test requests that timeout."""
         self.assertEqual(len(replies), 1)
         self.assertEqual(len(informs), 0)
         self.assertEqual([msg.name for msg in replies], ["slow-command"])
-        self.assertEqual([msg.arguments for msg in replies], [["fail", "Timed out after %f seconds" % timeout]])
+        self.assertEqual([msg.arguments for msg in replies], [
+                ["fail", "Timed out after %f seconds" % timeout]])
 
         del replies[:]
         del informs[:]
         time.sleep(0.2)
         self.assertEqual(len(replies), 1)
         self.assertEqual(len(informs), 0)
-        self.assertEqual([msg.name for msg in replies + informs], ["slow-command"]*len(replies+informs))
+        self.assertEqual([msg.name for msg in replies + informs],
+                         ["slow-command"] * len(replies + informs))
         self.assertEqual([msg.arguments for msg in replies], [["ok"]])
 
     def test_user_data(self):
             katcp.Message.request("help"),
             reply_cb=help_reply,
             inform_cb=help_inform,
-            user_data=(5, "foo")
-        )
+            user_data=(5, "foo"))
 
         time.sleep(0.1)
         self.assertEqual(len(help_replies), 1)
 
         reply, informs = self.client.blocking_request(
             katcp.Message.request("slow-command", "0.5"),
-            timeout = 0.001,
-        )
+            timeout=0.001)
 
         self.assertEqual(reply.name, "slow-command")
         self.assertEqual(reply.arguments[0], "fail")
         self.client.send_message = raise_error
 
         replies = []
+
         def reply_cb(msg):
             replies.append(msg)
 

File katcp/test/test_core.py

         self.assertEqual(katcp.Message.reply("foo", "ok").reply_ok(), True)
         self.assertEqual(katcp.Message.reply("foo", "ok", 1).reply_ok(), True)
         self.assertEqual(katcp.Message.reply("foo", "fail").reply_ok(), False)
-        self.assertEqual(katcp.Message.reply("foo", "fail", "ok").reply_ok(), False)
+        self.assertEqual(katcp.Message.reply("foo", "fail", "ok").reply_ok(),
+                         False)
         self.assertEqual(katcp.Message.request("foo", "ok").reply_ok(), False)
 
     def test_request(self):
         """Test request method."""
         self.assertEqual(str(katcp.Message.request("foo")), "?foo")
-        self.assertEqual(str(katcp.Message.request("foo", mid=123)), "?foo[123]")
-        self.assertEqual(str(katcp.Message.request("foo", "a", "b", mid=123)), "?foo[123] a b")
+        self.assertEqual(str(katcp.Message.request("foo", mid=123)),
+                         "?foo[123]")
+        self.assertEqual(str(katcp.Message.request("foo", "a", "b", mid=123)),
+                         "?foo[123] a b")
 
     def test_reply(self):
         """Test reply method."""
         self.assertEqual(str(katcp.Message.reply("foo")), "!foo")
         self.assertEqual(str(katcp.Message.reply("foo", mid=123)), "!foo[123]")
-        self.assertEqual(str(katcp.Message.reply("foo", "a", "b", mid=123)), "!foo[123] a b")
+        self.assertEqual(str(katcp.Message.reply("foo", "a", "b", mid=123)),
+                         "!foo[123] a b")
 
     def test_inform(self):
         """Test inform method."""
         self.assertEqual(str(katcp.Message.inform("foo")), "#foo")
-        self.assertEqual(str(katcp.Message.inform("foo", mid=123)), "#foo[123]")
-        self.assertEqual(str(katcp.Message.inform("foo", "a", "b", mid=123)), "#foo[123] a b")
+        self.assertEqual(str(katcp.Message.inform("foo", mid=123)),
+                         "#foo[123]")
+        self.assertEqual(str(katcp.Message.inform("foo", "a", "b", mid=123)),
+                         "#foo[123] a b")
 
     def test_equality(self):
         class AlwaysEqual(object):
         assert msg != 3
         assert msg == AlwaysEqual()
 
+
 class TestMessageParser(unittest.TestCase):
     def setUp(self):
         self.p = katcp.MessageParser()
 
     def test_empty_params(self):
         """Test parsing messages with empty parameters."""
-        m = self.p.parse("!foo \@") # 1 empty parameter
+        m = self.p.parse("!foo \@")  # 1 empty parameter
         self.assertEqual(m.arguments, [""])
-        m = self.p.parse("!foo \@ \@") # 2 empty parameter
+        m = self.p.parse("!foo \@ \@")  # 2 empty parameter
         self.assertEqual(m.arguments, ["", ""])
-        m = self.p.parse("!foo \_ \_ \@") # space, space, empty
+        m = self.p.parse("!foo \_ \_ \@")  # space, space, empty
         self.assertEqual(m.arguments, [" ", " ", ""])
 
     def test_whitespace(self):
         """Test parsing of whitespace between parameters."""
-        m = self.p.parse("!baz   \@   ") # 1 empty parameter
+        m = self.p.parse("!baz   \@   ")  # 1 empty parameter
         self.assertEqual(m.arguments, [""])
-        m = self.p.parse("!baz\t\@\t\@") # 2 empty parameter
+        m = self.p.parse("!baz\t\@\t\@")  # 2 empty parameter
         self.assertEqual(m.arguments, ["", ""])
-        m = self.p.parse("!baz\t \t\_\t\t\t \_\t\@   \t") # space, space, empty
+        m = self.p.parse("!baz\t \t\_\t\t\t \_\t\@   \t")  # space, space, \@
         self.assertEqual(m.arguments, [" ", " ", ""])
 
     def test_formfeed(self):
         s = DeviceTestSensor(
                 katcp.Sensor.INTEGER, "an.int", "An integer.", "count",
                 [-4, 3],
-                timestamp=12345, status=katcp.Sensor.NOMINAL, value=3
-        )
+                timestamp=12345, status=katcp.Sensor.NOMINAL, value=3)
         self.assertEqual(s.read_formatted(), ("12345000", "nominal", "3"))
         self.assertEquals(s.parse_value("3"), 3)
         self.assertRaises(ValueError, s.parse_value, "4")
         self.assertRaises(ValueError, s.parse_value, "-10")
         self.assertRaises(ValueError, s.parse_value, "asd")
 
-        s = katcp.Sensor(katcp.Sensor.INTEGER, "an.int", "An integer.", "count", [-20, 20])
+        s = katcp.Sensor(katcp.Sensor.INTEGER, "an.int", "An integer.",
+                         "count", [-20, 20])
         self.assertEquals(s.value(), 0)
-        s = katcp.Sensor(katcp.Sensor.INTEGER, "an.int", "An integer.", "count", [2, 20])
+        s = katcp.Sensor(katcp.Sensor.INTEGER, "an.int", "An integer.",
+                         "count", [2, 20])
         self.assertEquals(s.value(), 2)
-        s = katcp.Sensor(katcp.Sensor.INTEGER, "an.int", "An integer.", "count", [2, 20], default=5)
+        s = katcp.Sensor(katcp.Sensor.INTEGER, "an.int", "An integer.",
+                         "count", [2, 20], default=5)
         self.assertEquals(s.value(), 5)
 
     def test_float_sensor(self):
         s = DeviceTestSensor(
                 katcp.Sensor.FLOAT, "a.float", "A float.", "power",
                 [0.0, 5.0],
-                timestamp=12345, status=katcp.Sensor.WARN, value=3.0
-        )
+                timestamp=12345, status=katcp.Sensor.WARN, value=3.0)
         self.assertEqual(s.read_formatted(), ("12345000", "warn", "3"))
         self.assertEquals(s.parse_value("3"), 3.0)
         self.assertRaises(ValueError, s.parse_value, "10")
         self.assertRaises(ValueError, s.parse_value, "-10")
         self.assertRaises(ValueError, s.parse_value, "asd")
 
-        s = katcp.Sensor(katcp.Sensor.FLOAT, "a.float", "A float.", "", [-20.0, 20.0])
+        s = katcp.Sensor(katcp.Sensor.FLOAT, "a.float", "A float.", "",
+                         [-20.0, 20.0])
         self.assertEquals(s.value(), 0.0)
-        s = katcp.Sensor(katcp.Sensor.FLOAT, "a.float", "A float.", "", [2.0, 20.0])
+        s = katcp.Sensor(katcp.Sensor.FLOAT, "a.float", "A float.", "",
+                         [2.0, 20.0])
         self.assertEquals(s.value(), 2.0)
-        s = katcp.Sensor(katcp.Sensor.FLOAT, "a.float", "A float.", "", [2.0, 20.0], default=5.0)
+        s = katcp.Sensor(katcp.Sensor.FLOAT, "a.float", "A float.", "",
+                         [2.0, 20.0], default=5.0)
         self.assertEquals(s.value(), 5.0)
 
     def test_boolean_sensor(self):
         s = DeviceTestSensor(
                 katcp.Sensor.BOOLEAN, "a.boolean", "A boolean.", "on/off",
                 None,
-                timestamp=12345, status=katcp.Sensor.UNKNOWN, value=True
-        )
+                timestamp=12345, status=katcp.Sensor.UNKNOWN, value=True)
         self.assertEqual(s.read_formatted(), ("12345000", "unknown", "1"))
         self.assertEquals(s.parse_value("1"), True)
         self.assertEquals(s.parse_value("0"), False)
     def test_discrete_sensor(self):
         """Test discrete sensor."""
         s = DeviceTestSensor(
-                katcp.Sensor.DISCRETE, "a.discrete", "A discrete sensor.", "state",
-                ["on", "off"],
-                timestamp=12345, status=katcp.Sensor.ERROR, value="on"
-        )
+                katcp.Sensor.DISCRETE, "a.discrete", "A discrete sensor.",
+                "state", ["on", "off"],
+                timestamp=12345, status=katcp.Sensor.ERROR, value="on")
         self.assertEqual(s.read_formatted(), ("12345000", "error", "on"))
         self.assertEquals(s.parse_value("on"), "on")
         self.assertRaises(ValueError, s.parse_value, "fish")
                 katcp.Sensor.LRU, "an.lru", "An LRU sensor.", "state",
                 None,
                 timestamp=12345, status=katcp.Sensor.FAILURE,
-                value=katcp.Sensor.LRU_ERROR
-        )
+                value=katcp.Sensor.LRU_ERROR)
         self.assertEqual(s.read_formatted(), ("12345000", "failure", "error"))
         self.assertEquals(s.parse_value("nominal"), katcp.Sensor.LRU_NOMINAL)
         self.assertRaises(ValueError, s.parse_value, "fish")
         s = DeviceTestSensor(
             katcp.Sensor.STRING, "a.string", "A string sensor.", "filename",
             None,
-            timestamp=12345, status=katcp.Sensor.NOMINAL, value="zwoop"
-        )
+            timestamp=12345, status=katcp.Sensor.NOMINAL, value="zwoop")
         self.assertEqual(s.read_formatted(), ("12345000", "nominal", "zwoop"))
         self.assertEquals(s.parse_value("bar foo"), "bar foo")
 
         s = DeviceTestSensor(
             katcp.Sensor.TIMESTAMP, "a.timestamp", "A timestamp sensor.", "ms",
             None,
-            timestamp=12345, status=katcp.Sensor.NOMINAL, value=1001.9
-        )
-        self.assertEqual(s.read_formatted(), ("12345000", "nominal", "1001900"))
+            timestamp=12345, status=katcp.Sensor.NOMINAL, value=1001.9)
+        self.assertEqual(s.read_formatted(),
+                         ("12345000", "nominal", "1001900"))
         self.assertAlmostEqual(s.parse_value("1002100"), 1002.1)
         self.assertRaises(ValueError, s.parse_value, "bicycle")
 
         s = DeviceTestSensor(
                 katcp.Sensor.INTEGER, "an.int", "An integer.", "count",
                 [-4, 3],
-                timestamp=12345, status=katcp.Sensor.NOMINAL, value=3
-        )
+                timestamp=12345, status=katcp.Sensor.NOMINAL, value=3)
 
         self.assertEqual(s.value(), 3)
 

File katcp/test/test_katcp_bnf.py

                <id> ::= "" | "[" digit+ "]"
        <whitespace> ::= (space | tab) [<whitespace>]
               <eol> ::= newline | carriage-return
-        <arguments> ::= (<whitespace> <argument> <arguments>) | <whitespace> | ""
+        <arguments> ::= (<whitespace> <argument> <arguments>) | <whitespace> |
+                        ""
          <argument> ::= (<plain> | <escape>)+
            <escape> ::= "\" <escapecode>
        <escapecode> ::= "\" | "_" | zero | "n" | "r" | "e" | "t" | "@"
-          <special> ::= backslash | space | null | newline | carriage-return | escape | tab
+          <special> ::= backslash | space | null | newline | carriage-return |
+                        escape | tab
             <plain> ::= character / <special>
 
     Uses the ply library from http://www.dabeaz.com/ply/.
 import katcp
 import unittest
 
+
 class DclLexer(object):
     """Lexer definition for the DCL."""
 
         if t is None:
             raise katcp.KatcpSyntaxError("Argument syntax error.")
         else:
-            raise katcp.KatcpSyntaxError("Invalid argument token: %s " % t.value)
-
+            raise katcp.KatcpSyntaxError("Invalid argument token: %s " %
+                                         t.value)
 
 
 class DclGrammar(object):
     """Wraps Lexer and Grammar Objects"""
 
     def __init__(self):
-        self._lexer = lex.lex(object = DclLexer(), debug=0)
-        self._parser = yacc.yacc(module = DclGrammar(), debug=0, write_tables=0)
+        self._lexer = lex.lex(object=DclLexer(), debug=0)
+        self._parser = yacc.yacc(module=DclGrammar(), debug=0, write_tables=0)
 
     def parse(self, line):
         """Parse a line, return a Message."""
         """Test errors which should be raised by the lexer."""
         self.assertRaises(katcp.KatcpSyntaxError, self.p.parse, "")
         self.assertRaises(katcp.KatcpSyntaxError, self.p.parse, "^foo")
-        self.assertRaises(katcp.KatcpSyntaxError, self.p.parse, "!foo tab\0arg")
+        self.assertRaises(katcp.KatcpSyntaxError, self.p.parse,
+                          "!foo tab\0arg")
 
     def test_empty_params(self):
         """Test parsing messages with empty parameters."""
-        m = self.p.parse("!foo \@") # 1 empty parameter
+        m = self.p.parse("!foo \@")  # 1 empty parameter
         self.assertEqual(m.arguments, [""])
-        m = self.p.parse("!foo \@ \@") # 2 empty parameter
+        m = self.p.parse("!foo \@ \@")  # 2 empty parameter
         self.assertEqual(m.arguments, ["", ""])
-        m = self.p.parse("!foo \_  \_  \@") # space, space, empty
+        m = self.p.parse("!foo \_  \_  \@")  # space, space, \@
         self.assertEqual(m.arguments, [" ", " ", ""])
 
     def test_extra_whitespace(self):
         """Test extra whitespace around parameters."""
-        m = self.p.parse("!foo \t\@  ") # 1 empty parameter
+        m = self.p.parse("!foo \t\@  ")  # 1 empty parameter
         self.assertEqual(m.arguments, [""])
-        m = self.p.parse("!foo   \@    \@") # 2 empty parameter
+        m = self.p.parse("!foo   \@    \@")  # 2 empty parameter
         self.assertEqual(m.arguments, ["", ""])
-        m = self.p.parse("!foo \_  \t\t\_\t  \@\t") # space, space, empty
+        m = self.p.parse("!foo \_  \t\t\_\t  \@\t")  # space, space, \@
         self.assertEqual(m.arguments, [" ", " ", ""])
 
     def test_formfeed(self):

File katcp/test/test_kattypes.py

                            Str, Struct, Regex, DiscreteMulti, TimestampOrNow, \
                            StrictTimestamp
 
+
 class TestType(unittest.TestCase):
     def setUp(self):
         self._pack = []
 class TestInt(TestType):
 
     def setUp(self):
-        basic =  Int()
+        basic = Int()
         default = Int(default=11)
         optional = Int(optional=True)
         default_optional = Int(default=11, optional=True)
             (optional, None, None),
         ]
 
+
 class TestFloat(TestType):
 
     def setUp(self):
-        basic =  Float()
+        basic = Float()
         default = Float(default=11.0)
         optional = Float(optional=True)
         default_optional = Float(default=11.0, optional=True)
 class TestBool(TestType):
 
     def setUp(self):
-        basic =  Bool()
+        basic = Bool()
         default = Bool(default=True)
         optional = Bool(optional=True)
         default_optional = Bool(default=True, optional=True)
 class TestDiscrete(TestType):
 
     def setUp(self):
-        basic =  Discrete(("VAL1", "VAL2"))
+        basic = Discrete(("VAL1", "VAL2"))
         default = Discrete(("VAL1", "VAL2"), default="VAL1")
         optional = Discrete(("VAL1", "VAL2"), optional=True)
-        default_optional = Discrete(("VAL1", "VAL2"), default="VAL1", optional=True)
+        default_optional = Discrete(("VAL1", "VAL2"), default="VAL1",
+                                    optional=True)
         case_insensitive = Discrete(("val1", "VAL2"), case_insensitive=True)
 
         self._pack = [
 class TestLru(TestType):
 
     def setUp(self):
-        basic =  Lru()
+        basic = Lru()
         default = Lru(default=Lru.LRU_NOMINAL)
         optional = Lru(optional=True)
         default_optional = Lru(default=Lru.LRU_NOMINAL, optional=True)
 class TestTimestamp(TestType):
 
     def setUp(self):
-        basic =  Timestamp()
+        basic = Timestamp()
         default = Timestamp(default=1235475793.0324881)
         optional = Timestamp(optional=True)
         default_optional = Timestamp(default=1235475793.0324881, optional=True)
 class TestStrictTimestamp(TestType):
 
     def setUp(self):
-        basic =  StrictTimestamp()
+        basic = StrictTimestamp()
         default = StrictTimestamp(default=1235475793.03249)
         optional = StrictTimestamp(optional=True)
-        default_optional = StrictTimestamp(default=1235475793.03249, optional=True)
+        default_optional = StrictTimestamp(default=1235475793.03249,
+                                           optional=True)
 
         self._pack = [
             (basic, 1235475381.69669, "1235475381696.69"),
 class TestTimestampOrNow(TestType):
 
     def setUp(self):
-        basic =  TimestampOrNow()
+        basic = TimestampOrNow()
         default = TimestampOrNow(default=1235475793.0324881)
         optional = TimestampOrNow(optional=True)
-        default_optional = TimestampOrNow(default=1235475793.0324881, optional=True)
+        default_optional = TimestampOrNow(default=1235475793.0324881,
+                                          optional=True)
         default_now = TimestampOrNow(default=TimestampOrNow.NOW)
 
         self._pack = [
 class TestStr(TestType):
 
     def setUp(self):
-        basic =  Str()
+        basic = Str()
         default = Str(default="something")
         optional = Str(optional=True)
         default_optional = Str(default="something", optional=True)
 class TestStruct(TestType):
 
     def setUp(self):
-        basic =  Struct(">isf")
+        basic = Struct(">isf")
         default = Struct(">isf", default=(1, "f", 3.4))
         optional = Struct(">isf", optional=True)
         default_optional = Struct(">isf", default=(1, "f", 3.4), optional=True)
 class TestRegex(TestType):
 
     def setUp(self):
-        basic =  Regex("\d\d:\d\d:\d\d")
+        basic = Regex("\d\d:\d\d:\d\d")
         default = Regex("\d\d:\d\d:\d\d", default="00:00:00")
         optional = Regex("\d\d:\d\d:\d\d", optional=True)
-        default_optional = Regex("\d\d:\d\d:\d\d", default="00:00:00", optional=True)
+        default_optional = Regex("\d\d:\d\d:\d\d", default="00:00:00",
+                                 optional=True)
 
         self._pack = [
             (basic, "12:34:56", "12:34:56"),
 class TestDiscreteMulti(TestType):
 
     def setUp(self):
-        basic =  DiscreteMulti(("VAL1", "VAL2"))
+        basic = DiscreteMulti(("VAL1", "VAL2"))
         default = DiscreteMulti(("VAL1", "VAL2"), default=["VAL1"])
         optional = DiscreteMulti(("VAL1", "VAL2"), optional=True)
-        default_optional = DiscreteMulti(("VAL1", "VAL2"), default=["VAL1"], optional=True)
-        case_insensitive = DiscreteMulti(("val1", "VAL2"), case_insensitive=True)
+        default_optional = DiscreteMulti(("VAL1", "VAL2"), default=["VAL1"],
+                                         optional=True)
+        case_insensitive = DiscreteMulti(("val1", "VAL2"),
+                                         case_insensitive=True)
 
         self._pack = [
             (basic, ["VAL1"], "VAL1"),
             (basic, ["VAL2"], "VAL2"),
-            (basic, ["VAL1","VAL2"], "VAL1,VAL2"),
+            (basic, ["VAL1", "VAL2"], "VAL1,VAL2"),
             (basic, "a", ValueError),
             (basic, "VAL1", ValueError),
             (basic, ["aaa"], ValueError),
             (basic, ["val1"], ValueError),
-            (basic, ["VAL1","val2"], ValueError),
-            (basic, ["VAL1","aaa"], ValueError),
+            (basic, ["VAL1", "val2"], ValueError),
+            (basic, ["VAL1", "aaa"], ValueError),
             (basic, None, ValueError),
             (default, None, "VAL1"),
             (default_optional, None, "VAL1"),
             (optional, None, ValueError),
             (case_insensitive, ["VAL1"], "VAL1"),
             (case_insensitive, ["vAl2"], "vAl2"),
-            (case_insensitive, ["VAL1","val2"], "VAL1,val2"),
+            (case_insensitive, ["VAL1", "val2"], "VAL1,val2"),
             (case_insensitive, ["aaa"], ValueError),
         ]
 
         self._unpack = [
             (basic, "VAL1", ["VAL1"]),
             (basic, "VAL2", ["VAL2"]),
-            (basic, "VAL1,VAL2", ["VAL1","VAL2"]),
-            (basic, "all", ["VAL1","VAL2"]),
+            (basic, "VAL1,VAL2", ["VAL1", "VAL2"]),
+            (basic, "all", ["VAL1", "VAL2"]),
             (basic, "VAL1,aaa", ValueError),
             (basic, "VAL1,val2", ValueError),
             (basic, "a", ValueError),
             (optional, None, None),
             (case_insensitive, "val1", ["val1"]),
             (case_insensitive, "vAl2", ["vAl2"]),
-            (case_insensitive, "VAL1,val2", ["VAL1","val2"]),
+            (case_insensitive, "VAL1,val2", ["VAL1", "val2"]),
             (case_insensitive, "VAL1,aaa", ValueError),
             (case_insensitive, "a", ValueError),
         ]
     def __init__(self):
         self.sent_messages = []
 
-    @request(Int(min=1,max=10), Discrete(("on","off")), Bool())
-    @return_reply(Int(min=1,max=10),Discrete(("on","off")),Bool())
+    @request(Int(min=1, max=10), Discrete(("on", "off")), Bool())
+    @return_reply(Int(min=1, max=10), Discrete(("on", "off")), Bool())
     def request_one(self, sock, i, d, b):
         if i == 3:
             return ("fail", "I failed!")
             raise AsyncReply()
         return ("ok", i, d, b)
 
-    @send_reply(Int(min=1,max=10),Discrete(("on","off")),Bool())
+    @send_reply(Int(min=1, max=10), Discrete(("on", "off")), Bool())
     def finish_request_one(self, msg, sock, i, d, b):
         return (sock, msg, "ok", i, d, b)
 
     def reply(self, sock, msg, orig_msg):
         self.sent_messages.append([sock, msg])
 
-    @request(Int(min=1,max=3,default=2), Discrete(("on","off"),default="off"), Bool(default=True))
-    @return_reply(Int(min=1,max=3),Discrete(("on","off")),Bool())
+    @request(Int(min=1, max=3, default=2),
+             Discrete(("on", "off"), default="off"), Bool(default=True))
+    @return_reply(Int(min=1, max=3), Discrete(("on", "off")), Bool())
     def request_two(self, sock, i, d, b):
         return ("ok", i, d, b)
 
-    @return_reply(Int(min=1,max=3),Discrete(("on","off")),Bool())
-    @request(Int(min=1,max=3), Discrete(("on","off")), Bool())
+    @return_reply(Int(min=1, max=3), Discrete(("on", "off")), Bool())
+    @request(Int(min=1, max=3), Discrete(("on", "off")), Bool())
     def request_three(self, sock, i, d, b):
         return ("ok", i, d, b)
 
     def request_four(self, sock):
         return ["ok"]
 
-    @inform(Int(min=1,max=3), Discrete(("on","off")), Bool())
+    @inform(Int(min=1, max=3), Discrete(("on", "off")), Bool())
     def inform_one(self, sock, i, d, b):
         pass
 
-    @request(Int(min=1,max=3), Discrete(("on","off")), Bool())
-    @return_reply(Int(min=1,max=3),Discrete(("on","off")),Bool())
+    @request(Int(min=1, max=3), Discrete(("on", "off")), Bool())
+    @return_reply(Int(min=1, max=3), Discrete(("on", "off")), Bool())
     def request_five(self, i, d, b):
         return ("ok", i, d, b)
 
-    @return_reply(Int(min=1,max=3),Discrete(("on","off")),Bool())
-    @request(Int(min=1,max=3), Discrete(("on","off")), Bool())
+    @return_reply(Int(min=1, max=3), Discrete(("on", "off")), Bool())
+    @request(Int(min=1, max=3), Discrete(("on", "off")), Bool())
     def request_six(self, i, d, b):
         return ("ok", i, d, b)
 
     def test_request_one(self):
         """Test request with no defaults."""
         sock = ""
-        self.assertEqual(str(self.device.request_one(sock, Message.request("one", "2", "on", "0"))), "!one ok 2 on 0")
-        self.assertRaises(FailReply, self.device.request_one, sock, Message.request("one", "14", "on", "0"))
-        self.assertRaises(FailReply, self.device.request_one, sock, Message.request("one", "2", "dsfg", "0"))
-        self.assertRaises(FailReply, self.device.request_one, sock, Message.request("one", "2", "on", "3"))
-        self.assertRaises(FailReply, self.device.request_one, sock, Message.request("one", "2", "on", "0", "3"))
+        self.assertEqual(str(self.device.request_one(sock, Message.request(
+                        "one", "2", "on", "0"))), "!one ok 2 on 0")
+        self.assertRaises(FailReply, self.device.request_one, sock,
+                          Message.request("one", "14", "on", "0"))
+        self.assertRaises(FailReply, self.device.request_one, sock,
+                          Message.request("one", "2", "dsfg", "0"))
+        self.assertRaises(FailReply, self.device.request_one, sock,
+                          Message.request("one", "2", "on", "3"))
+        self.assertRaises(FailReply, self.device.request_one, sock,
+                          Message.request("one", "2", "on", "0", "3"))
 
-        self.assertRaises(FailReply, self.device.request_one, sock, Message.request("one", "2", "on"))
+        self.assertRaises(FailReply, self.device.request_one, sock,
+                          Message.request("one", "2", "on"))
 
-        self.assertEqual(str(self.device.request_one(sock, Message.request("one", "3", "on", "0"))), "!one fail I\\_failed!")
-        self.assertRaises(ValueError, self.device.request_one, sock, Message.request("one", "5", "on", "0"))
-        self.assertRaises(ValueError, self.device.request_one, sock, Message.request("one", "6", "on", "0"))
+        self.assertEqual(str(self.device.request_one(sock, Message.request(
+                        "one", "3", "on", "0"))), "!one fail I\\_failed!")
+        self.assertRaises(ValueError, self.device.request_one, sock,
+                          Message.request("one", "5", "on", "0"))
+        self.assertRaises(ValueError, self.device.request_one, sock,
+                          Message.request("one", "6", "on", "0"))
 
-        self.assertRaises(AsyncReply, self.device.request_one, "mysock", Message.request("one", "9", "on", "0"))
+        self.assertRaises(AsyncReply, self.device.request_one, "mysock",
+                          Message.request("one", "9", "on", "0"))
         self.assertEqual(len(self.device.sent_messages), 1)
         self.assertEqual(self.device.sent_messages[0][0], "mysock")
-        self.assertEqual(str(self.device.sent_messages[0][1]), "!one ok 9 on 0")
+        self.assertEqual(str(self.device.sent_messages[0][1]),
+                         "!one ok 9 on 0")
 
     def test_request_two(self):
         """Test request with defaults."""
         sock = ""
-        self.assertEqual(str(self.device.request_two(sock, Message.request("two", "2", "on", "0"))), "!two ok 2 on 0")
-        self.assertRaises(FailReply, self.device.request_two, sock, Message.request("two", "4", "on", "0"))
-        self.assertRaises(FailReply, self.device.request_two, sock, Message.request("two", "2", "dsfg", "0"))
-        self.assertRaises(FailReply, self.device.request_two, sock, Message.request("two", "2", "on", "3"))
+        self.assertEqual(str(self.device.request_two(sock, Message.request(
+                        "two", "2", "on", "0"))), "!two ok 2 on 0")
+        self.assertRaises(FailReply, self.device.request_two, sock,
+                          Message.request("two", "4", "on", "0"))
+        self.assertRaises(FailReply, self.device.request_two, sock,
+                          Message.request("two", "2", "dsfg", "0"))
+        self.assertRaises(FailReply, self.device.request_two, sock,
+                          Message.request("two", "2", "on", "3"))
 
-        self.assertEqual(str(self.device.request_two(sock, Message.request("two", "2", "on"))), "!two ok 2 on 1")
-        self.assertEqual(str(self.device.request_two(sock, Message.request("two", "2"))), "!two ok 2 off 1")
-        self.assertEqual(str(self.device.request_two(sock, Message.request("two"))), "!two ok 2 off 1")
+        self.assertEqual(str(self.device.request_two(sock, Message.request(
+                        "two", "2", "on"))), "!two ok 2 on 1")
+        self.assertEqual(str(self.device.request_two(sock, Message.request(
+                        "two", "2"))), "!two ok 2 off 1")
+        self.assertEqual(str(self.device.request_two(sock, Message.request(
+                        "two"))), "!two ok 2 off 1")
 
     def test_request_three(self):
         """Test request with no defaults and decorators in reverse order."""
         sock = ""
-        self.assertEqual(str(self.device.request_three(sock, Message.request("three", "2", "on", "0"))), "!three ok 2 on 0")
-        self.assertRaises(FailReply, self.device.request_three, sock, Message.request("three", "4", "on", "0"))
-        self.assertRaises(FailReply, self.device.request_three, sock, Message.request("three", "2", "dsfg", "0"))
-        self.assertRaises(FailReply, self.device.request_three, sock, Message.request("three", "2", "on", "3"))
+        self.assertEqual(str(self.device.request_three(sock, Message.request(
+                        "three", "2", "on", "0"))), "!three ok 2 on 0")
+        self.assertRaises(FailReply, self.device.request_three, sock,
+                          Message.request("three", "4", "on", "0"))
+        self.assertRaises(FailReply, self.device.request_three, sock,
+                          Message.request("three", "2", "dsfg", "0"))
+        self.assertRaises(FailReply, self.device.request_three, sock,
+                          Message.request("three", "2", "on", "3"))
 
-        self.assertRaises(FailReply, self.device.request_three, sock, Message.request("three", "2", "on"))
+        self.assertRaises(FailReply, self.device.request_three, sock,
+                          Message.request("three", "2", "on"))
 
     def test_request_four(self):
-        """Test request with no defaults and no parameters / return parameters"""
+        """Test request with no defaults and no parameters or return values"""
         sock = ""
-        self.assertEqual(str(self.device.request_four(sock, Message.request("four"))), "!four ok")
+        self.assertEqual(str(self.device.request_four(sock, Message.request(
+                        "four"))), "!four ok")
 
     def test_inform_one(self):
         """Test inform with no defaults."""
         sock = ""