Commits

Simon Cross committed e4a221b

Second (and final) giant PEP-8 clean-up commit for KATCP.

  • Participants
  • Parent commits b38013c

Comments (0)

Files changed (8)

katcp/tx/__init__.py

                            KatCPServer, KatCP, ServerKatCPProtocol, run_client,
                            KatCPClientFactory)
 from katcp.tx.proxy import DeviceHandler, ProxyProtocol, ProxyKatCP
-
 from twisted.protocols.basic import LineReceiver
 from twisted.internet.defer import Deferred, DeferredList
 from twisted.internet import reactor
-from twisted.internet.protocol import ClientCreator, ReconnectingClientFactory,\
-     ClientCreator
+from twisted.internet.protocol import ClientCreator, ReconnectingClientFactory
 from twisted.internet.protocol import Factory
 from twisted.python import log
-from twisted.internet.interfaces import IConsumer, IPushProducer
-from twisted.internet.error import ConnectionRefusedError
-from twisted.python import log
+from twisted.internet.interfaces import IPushProducer
 
 from katcp import MessageParser, Message, AsyncReply
 from katcp.core import FailReply
 from katcp.server import DeviceLogger, construct_name_filter
 from katcp.tx.sampling import (DifferentialStrategy, AutoStrategy,
     EventStrategy, NoStrategy, PeriodicStrategy)
-import sys, traceback
+
+import sys
+import traceback
 import time
 
+
 class UnhandledMessage(Exception):
     pass
 
+
 class NoQuerriesProcessed(Exception):
     pass
 
+
 class UnknownType(Exception):
     pass
 
+
 class DeviceNotConnected(Exception):
     pass
 
+
 class ShouldReturnMessage(Exception):
     pass
 
 TB_LIMIT = 20
 
+
 class KatCPClientFactory(ReconnectingClientFactory):
     initialDelay = 0.1
     maxDelay = 10.0
         self.resetDelay()
         return ReconnectingClientFactory.buildProtocol(self, addr)
 
+
 def run_client((host, port), ClientClass, connection_made=None,
                args=(), errback=None, errback_args=()):
     # XXX legacy interface, use the KatCPClientFactory instead
     """
 
     delimiter = '\n'
-    MAX_LENGTH = 64*(2**20) # 64 MB should be fine
+    MAX_LENGTH = 64 * (2 ** 20)  # 64 MB should be fine
     producing = True
 
     def __init__(self):
         elif msg.mtype == msg.REQUEST:
             self.handle_request(msg)
         else:
-            assert False # this could never happen since parser should complain
+            assert False  # this should never happen since the parser should
+                          # complain
 
     # some default informs
     def inform_version(self, msg):
             self.build_state = msg.arguments[0]
 
     def inform_disconnect(self, args):
-        pass # unnecessary, we have a callback on loseConnection
+        pass  # unnecessary, we have a callback on loseConnection
 
     def inform_client_connected(self, args):
-        pass # ignored by default
+        pass  # ignored by default
 
     def handle_inform(self, msg):
         # if we have a request being processed, store all the informs
         elif self.queries:
             name, d, queue = self.queries[0]
             if name != msg.name:
-                return # instead of raising WrongQueryOrder, we discard informs
-                       # that we don't know about
-            queue.append(msg) # unespace?
+                return  # instead of raising WrongQueryOrder, we discard
+                        # informs that we don't know about
+            queue.append(msg)  # unespace?
         else:
             raise UnhandledMessage(msg)
 
     def handle_request(self, msg):
         name = msg.name
         try:
-            rep_msg = getattr(self, 'request_' + name.replace('-', '_'), self._request_unknown)(msg)
+            rep_msg = getattr(self, 'request_' + name.replace('-', '_'),
+                              self._request_unknown)(msg)
             if not isinstance(rep_msg, Message):
-                raise ShouldReturnMessage('request_' + name + ' should return a'
-                                          'message or raise AsyncReply, instead'
-                                          'it returned %r' % rep_msg)
+                raise ShouldReturnMessage('request_' + name + ' should return'
+                                          ' a message or raise AsyncReply,'
+                                          ' instead it returned %r' % rep_msg)
             self.send_message(rep_msg)
         except FailReply, fr:
             self.send_message(Message.reply(name, "fail", str(fr)))
             e_type, e_value, trace = sys.exc_info()
             log.err()
             reason = "\n".join(traceback.format_exception(
-                e_type, e_value, trace, TB_LIMIT
-                ))
+                e_type, e_value, trace, TB_LIMIT))
 
             self.send_message(Message.reply(msg.name, "fail", reason))
 
         if name != msg.name:
             d.errback("Wrong request order")
             return
-        self.queries.pop(0) # hopefully it's not large
+        self.queries.pop(0)  # hopefully it's not large
         d.callback((queue, msg))
 
     # IPushProducer interface
     implements(IPushProducer)
-        
+
     def pauseProducing(self):
         self.producing = False
     stopProducing = pauseProducing
     def _request_unknown(self, msg):
         return Message.reply(msg.name, "invalid", "Unknown request.")
 
+
 class ClientKatCPProtocol(KatCP):
     def inform_log(self, msg):
         """ Default inform when logging event happens. Ignore by default,
         """
         pass
 
+
 class ServerKatCPProtocol(KatCP):
     VERSION = ("device_stub", 0, 1)
     BUILD_STATE = ("name", 0, 1, "")
-    
+
     def connectionMade(self):
         """ Called when connection is made. Send default informs - version
         and build data
         self.send_message(Message.inform("build-state", self.build_state()))
 
     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_STATE
 
     def version(self):
     def request_help(self, 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
         -------
                 count += 1
         return Message.reply(msg.name, "ok", str(count))
 
+
 class KatCPServer(Factory):
     protocol = ServerKatCPProtocol
-    
+
     def __init__(self, port, host):
         self.clients = {}
         self.listen_port = port
         self.host = host
         self.clients = {}
-    
+
     def start(self):
         self.port = reactor.listenTCP(self.listen_port, self,
                                       interface=self.host)
         for client in self.clients.itervalues():
             client.send_message(msg)
 
+
 class DeviceProtocol(ServerKatCPProtocol):
 
-    SAMPLING_STRATEGIES = {'period'       : PeriodicStrategy,
-                           'none'         : NoStrategy,
-                           'auto'         : AutoStrategy,
-                           'event'        : EventStrategy,
-                           'differential' : DifferentialStrategy}
+    SAMPLING_STRATEGIES = {'period': PeriodicStrategy,
+                           'none': NoStrategy,
+                           'auto': AutoStrategy,
+                           'event': EventStrategy,
+                           'differential': DifferentialStrategy}
 
     def __init__(self, *args, **kwds):
         KatCP.__init__(self, *args, **kwds)
 
     def send_sensor_status(self, sensor):
         def callback(sensor, timestamp_ms, status, value):
-            self.send_message(Message.inform('sensor-status', timestamp_ms, "1",
-                                             sensor.name, status, value))
+            self.send_message(Message.inform('sensor-status', timestamp_ms,
+                                             "1", sensor.name, status, value))
 
         def fail(_, sensor):
             self.send_message(Message.inform('log',
         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
         exact, name_filter = construct_name_filter(msg.arguments[0]
                     if msg.arguments else None)
         sensors = [(name, sensor) for name, sensor in
-                    sorted(self.factory.sensors.iteritems()) if name_filter(name)]
+                   sorted(self.factory.sensors.iteritems())
+                   if name_filter(name)]
 
         if exact and not sensors:
             return Message.reply(msg.name, "fail", "Unknown sensor name.")
         ----------
         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
         -------
         exact, name_filter = construct_name_filter(msg.arguments[0]
                     if msg.arguments else None)
         sensors = [(name, sensor) for name, sensor in
-                    sorted(self.factory.sensors.iteritems()) if name_filter(name)]
+                   sorted(self.factory.sensors.iteritems())
+                   if name_filter(name)]
 
         if exact and not sensors:
             return Message.reply(msg.name, "fail", "Unknown sensor name.")
 
         for name, sensor in sensors:
-            self.send_message(Message.inform(msg.name, name, sensor.description,
-                                             sensor.units, sensor.stype,
+            self.send_message(Message.inform(msg.name, name,
+                                             sensor.description, sensor.units,
+                                             sensor.stype,
                                              *sensor.formatted_params))
         return Message.reply(msg.name, "ok", len(sensors))
 
         ----------
         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
         if len(msg.arguments) == 1:
             StrategyClass = NoStrategy
         else:
-            StrategyClass = self.SAMPLING_STRATEGIES.get(msg.arguments[1], None)
+            StrategyClass = self.SAMPLING_STRATEGIES.get(msg.arguments[1],
+                                                         None)
             if StrategyClass is None:
-                return Message.reply(msg.name, "fail", "Unknown strategy name.")
+                return Message.reply(msg.name, "fail",
+                                     "Unknown strategy name.")
         # stop the previous strategy
         try:
             strategy = self.strategies[sensor.name].cancel()
 
         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
                 raise FailReply(str(e))
         return Message.reply("log-level", "ok", self.factory.log.level_name())
 
+
 class DeviceServer(KatCPServer):
     """ This is a device server listening on a given port and address
     """
         self.sensors[sensor.name] = sensor
 
     def setup_sensors(self):
-        pass # override to provide some sensors
+        pass  # override to provide some sensors
 
     def __init__(self, port, host):
-        self.log = DeviceLogger(self) # python logger is None
+        self.log = DeviceLogger(self)  # python logger is None
         KatCPServer.__init__(self, port, host)
         self.sensors = {}
         self.setup_sensors()
             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,
         )

katcp/tx/proxy.py

 from katcp import Message, AsyncReply, Sensor
 from katcp.kattypes import request, return_reply, Int
 
-import re, time
+import re
+import time
+
 
 def value_only_formatted(func):
     """ A decorator that changes a value-only read into read_formatted
     new_func.func_name = func.func_name
     return new_func
 
+
 class ProxiedSensor(Sensor):
     """ A sensor which is a proxy for other sensor on the remote device.
     Returns a deferred on read
     def read_formatted(self):
         return self.device.send_request('sensor-value', self.basename)
 
+
 class StateSensor(object):
     """ A device state sensor
     """
     def read_formatted(self):
         return DeviceHandler.STATE_NAMES[self.device.state]
 
+
 class DeviceHandler(ClientKatCPProtocol):
     SYNCING, SYNCED, UNSYNCED = range(3)
     STATE_NAMES = ['syncing', 'synced', 'unsynced']
         except:
             log.err()
 
+
 class ProxyProtocol(DeviceProtocol):
     @request(include_msg=True)
     @return_reply(Int(min=0))
         Parameters
         ----------
         name : str or pattern, optional
-            If the name is not a pattern, list just the sensor with the given name.
-            A pattern starts and ends with a slash ('/') and uses the Python re
-            module's regular expression syntax. All sensors whose names contain the
-            pattern are listed.  The default is to list all sensors.
+            If the name is not a pattern, list just the sensor with the given
+            name. A pattern starts and ends with a slash ('/') and uses the
+            Python re module's regular expression syntax. All sensors whose
+            names contain the pattern are listed.  The default is to list all
+            sensors.
 
         Inform Arguments
         ----------------
         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
         -------
     def _send_all_sensors(self, filter=None):
         """ Sends all sensor values with given filter (None = all)
         """
-        counter = [0] # this has to be a list or an object, thanks to
+        counter = [0]  # this has to be a list or an object, thanks to
         # python lexical scoping rules (we could not write count += 1
         # in a function)
 
                                                      name, status,
                                                      value))
 
-
     def request_sensor_value(self, msg):
         """Poll a sensor value or value(s).
 
         Parameters
         ----------
         name : str or pattern, optional
-            If the name is not a pattern, list just the values of sensors with the
-            given name.  A pattern starts and ends with a slash ('/') and uses the
-            Python re module's regular expression syntax. The values of all sensors
-            whose names contain the pattern are listed.  The default is to list the
-            values of all sensors.
+            If the name is not a pattern, list just the values of sensors with
+            the given name.  A pattern starts and ends with a slash ('/') and
+            uses the Python re module's regular expression syntax. The values
+            of all sensors whose names contain the pattern are listed.  The
+            default is to list the values of all sensors.
 
         Inform Arguments
         ----------------
         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
         # but currently don't.
 
         def request_returned((informs, reply)):
-            assert informs == [] # for now
+            assert informs == []  # for now
             # we *could* in theory just change message name, but let's copy
             # just in case
             self.send_message(Message.reply(dev_name + "-" + req_name,
             return object.__getattribute__(self, attr)
         return callback
 
+
 class ClientDeviceFactory(ClientFactory):
     """ A factory that does uses prebuilt device handler objects
     """
     def __init__(self, addr_mapping, max_reconnects, conn_delay_timeout,
                  proxy):
-        self.addr_mapping = addr_mapping # shared dict with proxy
+        self.addr_mapping = addr_mapping  # shared dict with proxy
         self.max_reconnects = max_reconnects
         self.conn_delay_timeout = conn_delay_timeout
         self.proxy = proxy
     def buildProtocol(self, addr):
         return self.addr_mapping[(addr.host, addr.port)]
 
+
 class ProxyKatCP(DeviceServer):
     """ This is a proxy class that will listen on a given host and port
     providing info about underlaying clients if needed
     def device_ready(self, device):
         self.ready_devices += 1
         if self.ready_devices == len(self.devices) and not self.scan_called:
-            self.scan_called = True # one shot only
+            self.scan_called = True  # one shot only
             self.devices_scan_complete()
 
     def add_device(self, device):

katcp/tx/sampling.py

 
 from twisted.internet import reactor
 
+
 class SamplingStrategy(object):
     """ Base class for all sampling strategies
     """
         """
         pass
 
+
 class PeriodicStrategy(SamplingStrategy):
     next = None
 
         self.period = float(period) / 1000
         self._run_once()
 
+
 class NoStrategy(SamplingStrategy):
     def run(self):
         pass
 
+
 class ObserverStrategy(SamplingStrategy):
     """ A common superclass for strategies that watch sensors and take
     actions accordingly
     def update(self, sensor):
         self.protocol.send_sensor_status(sensor)
 
+
 class EventStrategy(ObserverStrategy):
     def __init__(self, protocol, sensor):
         ObserverStrategy.__init__(self, protocol, sensor)
             self.value = newval
             self.protocol.send_sensor_status(sensor)
 
+
 class DifferentialStrategy(ObserverStrategy):
     def __init__(self, protocol, sensor):
         ObserverStrategy.__init__(self, protocol, sensor)

katcp/tx/test/__init__.py

 """Tests for the katcp.tx package.
    """
 
+
 def suite():
     import unittest
     import test_core

katcp/tx/test/test_core.py

 from twisted.internet import reactor
 from twisted.internet.defer import Deferred, DeferredList
 from twisted.internet.protocol import ClientCreator
-from twisted.internet.base import DelayedCall
-from twisted.internet.defer import inlineCallbacks
 
 from katcp.core import FailReply
 
 
 timeout = 5
 
+
 class TestKatCP(TestCase):
     """ A tesited test case, run with trial testing
 
             protocol.send_request('halt')
 
         def connected(protocol):
-            protocol.send_request('sensor-sampling', 'int_sensor', 'period', 10)
+            protocol.send_request('sensor-sampling', 'int_sensor',
+                                  'period', 10)
             reactor.callLater(0.3, check, protocol)
 
         d, process = run_subprocess(connected, TestClientKatCP)
         return d
 
+
 class TestProtocol(DeviceProtocol):
     notify_con_lost = None
 
         if self.notify_con_lost:
             self.notify_con_lost()
 
+
 class TestFactory(DeviceServer):
     protocol = TestProtocol
 
         sensor.set_value(sensor.value(), status=Sensor.UNKNOWN, timestamp=1)
         self.add_sensor(sensor)
 
+
 class TestClientKatCP(ClientKatCPProtocol):
     def __init__(self, *args, **kwds):
         ClientKatCPProtocol.__init__(self, *args, **kwds)
     def inform_sensor_status(self, msg):
         self.status_updates.append(msg)
 
+
 class TestDeviceServer(TestCase):
     def _end_test(self, _):
         self.peer = None
         def callback((informs, reply), protocol):
             assert protocol.version == 'device_stub-0.1'
             assert protocol.build_state == 'name-0.1'
-        
+
         return self._base_test('watchdog', callback)
 
     def test_unknown_request(self):
 
     def test_run_basic_sensors(self):
         def sensor_value_replied((informs, reply), protocol):
-            self.assertEquals(informs, [Message.inform('sensor-value', '0', '1',
-                                                       'int_sensor', 'unknown',
-                                                       '0')])
+            self.assertEquals(informs, [Message.inform('sensor-value', '0',
+                                                       '1', 'int_sensor',
+                                                       'unknown', '0')])
             self.assertEquals(reply, Message.reply('sensor-value', 'ok', '1'))
 
         return self._base_test(('sensor-value', 'int_sensor'),
             reactor.callLater(0.3, called_later, protocol)
             return True
 
-        return self._base_test(('sensor-sampling', 'int_sensor', 'period', '10'),
-                              reply)
+        return self._base_test(('sensor-sampling', 'int_sensor',
+                                'period', '10'), reply)
 
     def test_sensor_sampling_auto(self):
         def even_more((informs, reply), protocol):
                                                        '1', 'int_sensor',
                                                        'nominal', '3')])
             self.factory.sensors['int_sensor'].set(0, Sensor.NOMINAL, 5)
-            protocol.send_request('sensor-value',
-                                  'int_sensor').addCallback(even_more, protocol)
+            protocol.send_request('sensor-value', 'int_sensor').addCallback(
+                    even_more, protocol)
 
         def reply((informs, reply), protocol):
             self.assertEquals(informs, [])
                                   'int_sensor').addCallback(more, protocol)
             return True
 
-        return self._base_test(('sensor-sampling', 'int_sensor', 'auto'), reply)
-
+        return self._base_test(('sensor-sampling', 'int_sensor', 'auto'),
+                               reply)
 
     def test_sensor_sampling_event(self):
         def even_more((informs, reply), protocol):
                                                        '1', 'int_sensor',
                                                        'nominal', '3')])
             self.factory.sensors['int_sensor'].set_value(3, timestamp=0)
-            protocol.send_request('sensor-value',
-                                  'int_sensor').addCallback(even_more, protocol)
+            protocol.send_request('sensor-value', 'int_sensor').addCallback(
+                    even_more, protocol)
 
         def reply((informs, reply), protocol):
             self.assertEquals(informs, [])
                                   'int_sensor').addCallback(more, protocol)
             return True
 
-        return self._base_test(('sensor-sampling', 'int_sensor', 'event'), reply)
+        return self._base_test(('sensor-sampling', 'int_sensor', 'event'),
+                               reply)
 
     def test_sensor_sampling_differential(self):
         def first((informs, reply), protocol):
         def reply((informs, reply), protocol):
             self.assertEquals(informs, [])
             assert 'Traceback' in str(reply)
-            self.flushLoggedErrors() # clean up errors so they're not reported
+            self.flushLoggedErrors()  # clean up errors so they're not reported
             # as test failures
 
         return self._base_test(('foobar',), reply, cls=FaultyFactory)
 
         def reply((informs, reply), protocol):
             self.assertEquals(informs, [])
-            self.assertEquals(reply, Message.reply("foo-bar", "fail", "failed"))
+            self.assertEquals(reply,
+                              Message.reply("foo-bar", "fail", "failed"))
 
         return self._base_test(('foo-bar',), reply, cls=FaultyFactory)
 
             # disconnect one and check it deregisters, with notification
             # when tcp reaches the other end
             for v in self.factory.clients.values():
-                v.notify_con_lost = lambda : send_client_list(protocols[1])
+                v.notify_con_lost = lambda: send_client_list(protocols[1])
             protocols[0].transport.loseConnection()
 
         def send_client_list(protocol):
         return self._base_test(('log-level',), log_level1,
                               client_cls=TestProtocol)
 
+
 class TestClient(TestCase):
     def test_autoconnect(self):
         def f():
             self.f.start()
 
         res = Deferred()
+
         class Protocol(ClientKatCPProtocol):
             def connectionMade(_):
                 d = self.f.port.stopListening()
                 client_fac.stopTrying()
                 d.addCallback(lambda _: res.callback(None))
-                
+
         class ClientFactory(KatCPClientFactory):
             protocol = Protocol
 
         reactor.callLater(0.3, f)
         return res
 
+
 class TestMisc(TestCase):
     def test_requests(self):
         from katcp.server import DeviceServer

katcp/tx/test/test_proxy.py

 from katcp.tx.proxy import ProxyKatCP, DeviceHandler, DeviceProtocol
 from twisted.trial.unittest import TestCase
 from twisted.internet.protocol import ClientCreator
-from twisted.internet.defer import Deferred, inlineCallbacks
+from twisted.internet.defer import Deferred
 from katcp import Sensor, Message
 from katcp.kattypes import request, return_reply, Int
 from twisted.internet import reactor
 timeout = 5
 #Deferred.debug = True
 
+
 class ExampleProtocol(DeviceProtocol):
     @request(include_msg=True)
     @return_reply(Int(min=0))
 
     def setup_sensors(self):
         sensor = Sensor(int, "sensor1", "Test sensor 1", "count",
-                        [0,10])
+                        [0, 10])
         sensor.set_value(sensor.value(), status=Sensor.UNKNOWN, timestamp=1)
         self.add_sensor(sensor)
         sensor2 = Sensor(int, "sensor2", "Test sensor 2", "count",
         sensor2.set_value(sensor.value(), status=Sensor.UNKNOWN, timestamp=0)
         self.add_sensor(sensor2)
 
+
 class MyDeviceHandler(DeviceHandler):
     ready = False
-    
+
     def device_ready(self):
         self.ready = True
 
+
 class ExampleProxy(ProxyKatCP):
     on_device_ready = None
     CONN_DELAY_TIMEOUT = 0.05
         dev2._conn_counter = 100
         self.add_device(dev2)
         self.ready_devices = 1
-        self.add_device(MyDeviceHandler('device', 'localhost', self.connect_to))
+        self.add_device(MyDeviceHandler('device', 'localhost',
+                                        self.connect_to))
 
     def devices_scan_complete(self):
         self.finish.callback(None)
             self.on_device_ready = None
         ProxyKatCP.device_ready(self, device)
 
+
 class TestProxyBase(TestCase):
     def _base_test(self, request, callback):
         def devices_scan_complete(_):
     def test_forwarding_sensors(self):
         def callback((informs, reply)):
             self.assertEquals(informs,
-                    [Message.inform('sensor-value', '1000', '1', 'device.sensor1',
-                                    'unknown', '0')])
+                    [Message.inform('sensor-value', '1000', '1',
+                                    'device.sensor1', 'unknown', '0')])
             self.assertEquals(reply, Message.reply('sensor-value', 'ok', '1'))
 
         return self._base_test(('sensor-value', 'device.sensor1'), callback)
     def test_all_forwarded_sensors(self):
         def callback((informs, reply)):
             self.assertEquals(informs[2:],
-                  [Message.inform('sensor-value', '1000', '1', 'device.sensor1',
-                                  'unknown', '0'),
+                  [Message.inform('sensor-value', '1000', '1',
+                                  'device.sensor1', 'unknown', '0'),
                    Message.inform('sensor-value', '0', '1', 'device.sensor2',
                                   'unknown', '0')])
             self.assertEquals(reply, Message.reply('sensor-value', 'ok', '4'))
     def test_all_forwarded_sensors_regex(self):
         def callback((informs, reply)):
             self.assertEquals(informs,
-                  [Message.inform('sensor-value', '1000', '1', 'device.sensor1',
-                                  'unknown', '0')])
+                  [Message.inform('sensor-value', '1000', '1',
+                                  'device.sensor1', 'unknown', '0')])
             self.assertEquals(reply, Message.reply('sensor-value', 'ok', '1'))
 
         return self._base_test(('sensor-value', '/device\.sensor1/'),
         def sampling_done((informs, reply)):
             self.example_device.sensors['sensor1'].set_value(10)
             reactor.callLater(0.1, check_value)
-        
+
         def callback(arg):
             d = self.proxy.devices['device'].send_request(
                 'sensor-sampling', 'sensor1', 'period', '10')
         def callback(_):
             device = self.proxy.devices['device']
             assert device.ready == True
-        
+
         return self._base_test(None, callback)
 
     def test_halt(self):
 
     def read_formatted(self):
         for client in self.device.clients.values():
-            client.transport._closeSocket() # force a connection drop
+            client.transport._closeSocket()  # force a connection drop
         return 1, 2, 3
 
+
 class RogueDevice(DeviceServer):
     def setup_sensors(self):
         self.add_sensor(RogueSensor('rogue', self))
 
+
 class HandlingProxy(ExampleProxy):
     on_device_scan_failed = None
 
         if self.on_device_scan_failed is not None:
             self.on_device_scan_failed.callback(None)
 
+
 class TestReconnect(TestCase):
     def test_rogue_device(self):
         def devices_scan_complete(_):
             cc.connectTCP('localhost', host.port).addCallback(connected)
 
         def worked((informs, reply)):
-            self.flushLoggedErrors() # clean up error about conn lost
+            self.flushLoggedErrors()  # clean up error about conn lost
             self.proxy.on_device_ready = Deferred().addCallback(back)
-            self.assertEquals(informs, [Message.inform("sensor-value", "device.rogue",
-                                                   "Sensor reading failed.")])
+            self.assertEquals(informs, [Message.inform("sensor-value",
+                    "device.rogue", "Sensor reading failed.")])
 
         def back(_):
             self.port.stopListening()
 
         def connected(protocol):
             self.client = protocol
-            protocol.send_request('sensor-value', 'device.rogue').addCallbacks(worked)
+            protocol.send_request('sensor-value', 'device.rogue').addCallbacks(
+                    worked)
 
         d = Deferred()
         self.example_device = RogueDevice(0, '')

katcp/tx/test/testserver.py

 #!/usr/bin/env python
 
-import os, re, sys
+import os
+import re
+import sys
 
-sys.path.insert(0, '.') # not sure why python adds '.' or not depending on
+sys.path.insert(0, '.')  # not sure why python adds '.' or not depending on
 # obscure details how you run it
 from katcp.server import DeviceServer
 from katcp import Sensor
 from twisted.internet.error import ProcessDone
 from twisted.python import log
 
+
 class FloatSensor(Sensor):
     def get_value(self):
         self.__value += .1
 
     _value = property(get_value, set_value)
 
+
 class IntSensor(Sensor):
     def get_value(self):
         self.__value += 1
 
     _value = property(get_value, set_value)
 
+
 class TestServer(DeviceServer):
     def setup_sensors(self):
         self.add_sensor(FloatSensor(Sensor.FLOAT, "float_sensor", "descr",
         print "PORT: %d" % sock.getsockname()[1]
         return sock
 
+
 class ServerSubprocess(ProcessProtocol):
     initiated = False
 
 
 PORT = 0
 
+
 class Factory(KatCPClientFactory):
     def __init__(self, callback):
         self.callback = callback
-    
+
     def buildProtocol(self, addr):
         result = KatCPClientFactory.buildProtocol(self, addr)
         if self.callback is not None:
             reactor.callLater(0, self.callback, result)
         return result
 
+
 def run_subprocess(connected, ClientClass):
     factory = Factory(connected)
-    
+
     def failed_to_run(error):
         print error
         reactor.stop()