changeset 590:56531f9e9ac7

Fix pep8 support in src/tools.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Fri, 18 Jan 2013 17:55:35 +0100
parents d1b4805124a1
children 65821b3fa7ab
files src/tools/games.py src/tools/jid.py src/tools/misc.py src/tools/xml_tools.py
diffstat 4 files changed, 79 insertions(+), 79 deletions(-) [+]
line wrap: on
line diff
--- a/src/tools/games.py	Fri Jan 18 17:55:35 2013 +0100
+++ b/src/tools/games.py	Fri Jan 18 17:55:35 2013 +0100
@@ -20,12 +20,11 @@
 """
 
 from logging import debug, info, error
-
 """This library help manage general games (e.g. card games)"""
 
+SUITS_ORDER = ['pique', 'coeur', 'trefle', 'carreau', 'atout']  # I have switched the usual order 'trefle' and 'carreau' because card are more easy to see if suit colour change (black, red, black, red)
+VALUES_ORDER = [str(i) for i in xrange(1, 11)] + ["valet", "cavalier", "dame", "roi"]
 
-suits_order = ['pique', 'coeur', 'trefle', 'carreau', 'atout'] #I have switched the usual order 'trefle' and 'carreau' because card are more easy to see if suit colour change (black, red, black, red)
-values_order = map(str,range(1,11))+["valet","cavalier","dame","roi"]
 
 class TarotCard(object):
     """This class is used to represent a car logically"""
@@ -34,7 +33,7 @@
     def __init__(self, tuple_card):
         """@param tuple_card: tuple (suit, value)"""
         self.suit, self.value = tuple_card
-        self.bout = True if self.suit=="atout" and self.value in ["1","21","excuse"] else False
+        self.bout = self.suit == "atout" and self.value in ["1", "21", "excuse"]
         if self.bout or self.value == "roi":
             self.points = 4.5
         elif self.value == "dame":
@@ -47,7 +46,7 @@
             self.points = 0.5
 
     def get_tuple(self):
-        return (self.suit,self.value)
+        return (self.suit, self.value)
 
     @staticmethod
     def from_tuples(tuple_list):
@@ -57,11 +56,11 @@
         return result
 
     def __cmp__(self, other):
-        if other == None:
+        if other is None:
             return 1
         if self.suit != other.suit:
-            idx1 = suits_order.index(self.suit)
-            idx2 = suits_order.index(other.suit)
+            idx1 = SUITS_ORDER.index(self.suit)
+            idx2 = SUITS_ORDER.index(other.suit)
             return idx1.__cmp__(idx2)
         if self.suit == 'atout':
             if self.value == other.value == 'excuse':
@@ -71,9 +70,9 @@
             if other.value == 'excuse':
                 return 1
             return int(self.value).__cmp__(int(other.value))
-        #at this point we have the same suit which is not 'atout'
-        idx1 = values_order.index(self.value)
-        idx2 = values_order.index(other.value)
+        # at this point we have the same suit which is not 'atout'
+        idx1 = VALUES_ORDER.index(self.value)
+        idx2 = VALUES_ORDER.index(other.value)
         return idx1.__cmp__(idx2)
 
     def __str__(self):
--- a/src/tools/jid.py	Fri Jan 18 17:55:35 2013 +0100
+++ b/src/tools/jid.py	Fri Jan 18 17:55:35 2013 +0100
@@ -20,7 +20,6 @@
 """
 
 
-
 class JID(unicode):
     """This class help manage JID (Node@Domaine/Resource)"""
 
@@ -31,19 +30,19 @@
 
     def __parse(self):
         """find node domaine and resource"""
-        node_end=self.find('@')
-        if node_end<0:
-            node_end=0
-        domain_end=self.find('/')
-        if domain_end<1:
-            domain_end=len(self)
-        self.node=self[:node_end]
-        self.domain=self[(node_end+1) if node_end else 0:domain_end]
-        self.resource=self[domain_end+1:]
+        node_end = self.find('@')
+        if node_end < 0:
+            node_end = 0
+        domain_end = self.find('/')
+        if domain_end < 1:
+            domain_end = len(self)
+        self.node = self[:node_end]
+        self.domain = self[(node_end + 1) if node_end else 0:domain_end]
+        self.resource = self[domain_end + 1:]
         if not node_end:
-            self.short=self
+            self.short = self
         else:
-            self.short=self.node+'@'+self.domain
+            self.short = self.node + '@' + self.domain
 
     def is_valid(self):
         """return True if the jid is xmpp compliant"""
--- a/src/tools/misc.py	Fri Jan 18 17:55:35 2013 +0100
+++ b/src/tools/misc.py	Fri Jan 18 17:55:35 2013 +0100
@@ -19,34 +19,38 @@
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 """
 
-from logging import debug, info, error
+"""Misc usefull classes"""
 
-"""Misc usefull classes"""
 
 class TriggerException(Exception):
     pass
 
+
 class SkipOtherTriggers(Exception):
     """ Exception to raise if normal behaviour must be followed instead of
         followind triggers list """
     pass
 
+
 class TriggerManager(object):
-    """This class manage triggers: code which interact to change de behaviour of SàT"""
+    """This class manage triggers: code which interact to change de behaviour
+    of SàT"""
 
     def __init__(self):
-        self.__triggers={}
+        self.__triggers = {}
 
     def add(self, point_name, callback, priority=0):
         """Add a trigger to a point
         @param point_name: name of the point when the trigger should be run
         @param callback: method to call at the trigger point
-        @param priority: callback will be called in priority order, biggest first
+        @param priority: callback will be called in priority order, biggest
+        first
         """
-        if not self.__triggers.has_key(point_name):
-            self.__triggers[point_name]=[]
+        if point_name not in self.__triggers:
+            self.__triggers[point_name] = []
         self.__triggers[point_name].append((priority, callback))
-        self.__triggers[point_name].sort(key=lambda trigger_tuple: trigger_tuple[0], reverse=True)
+        self.__triggers[point_name].sort(key=lambda trigger_tuple:
+                                         trigger_tuple[0], reverse=True)
 
     def remove(self, point_name, callback):
         """Remove a trigger from a point
@@ -63,7 +67,7 @@
         All the trigger for that point will be run
         @param point_name: name of the trigger point
         @return: True if the action must be continued, False else"""
-        if not self.__triggers.has_key(point_name):
+        if point_name not in self.__triggers:
             return True
 
         for priority,trigger in self.__triggers[point_name]:
@@ -73,4 +77,3 @@
             except SkipOtherTriggers:
                 break
         return True
-
--- a/src/tools/xml_tools.py	Fri Jan 18 17:55:35 2013 +0100
+++ b/src/tools/xml_tools.py	Fri Jan 18 17:55:35 2013 +0100
@@ -22,7 +22,6 @@
 from logging import debug, info, error
 from xml.dom import minidom
 from wokkel import data_form
-import pdb
 from twisted.words.xish import domish
 
 """This library help manage XML used in SàT (parameters, registration, etc) """
@@ -36,9 +35,9 @@
     if form.instructions:
         form_ui.addText('\n'.join(form.instructions), 'instructions')
 
-    labels = filter(lambda field:field.label,form.fieldList)
+    labels = [field for field in form.fieldList if field.label]
     if labels:
-        #if there is no label, we don't need to use pairs
+        # if there is no label, we don't need to use pairs
         form_ui.changeLayout("pairs")
 
     for field in form.fieldList:
@@ -51,7 +50,7 @@
         elif field.fieldType == 'list-single':
             __field_type = "list"
         else:
-            error (u"FIXME FIXME FIXME: Type [%s] is not managed yet by SàT" % field.fieldType)
+            error(u"FIXME FIXME FIXME: Type [%s] is not managed yet by SàT" % field.fieldType)
             __field_type = "string"
 
         if labels:
@@ -60,9 +59,10 @@
             else:
                 form_ui.addEmpty()
 
-        elem = form_ui.addElement(__field_type, field.var, field.value, [option.value for option in field.options])
+        form_ui.addElement(__field_type, field.var, field.value, [option.value for option in field.options])
     return form_ui.toXml()
 
+
 def tupleList2dataForm(values):
     """convert a list of tuples (name,value) to a wokkel submit data form"""
     form = data_form.Form('submit')
@@ -72,6 +72,7 @@
 
     return form
 
+
 def paramsXml2xmlUI(xml):
     """Convert the xml for parameter to a SàT XML User Interface"""
     params_doc = minidom.parseString(xml.encode('utf-8'))
@@ -93,20 +94,18 @@
             if not name:
                 error(_('INTERNAL ERROR: params must have a name'))
                 assert(False)
-            type = param.getAttribute('type')
+            type_ = param.getAttribute('type')
             value = param.getAttribute('value') or None
             callback_id = param.getAttribute('callback_id') or None
-            if type == "button":
+            if type_ == "button":
                 param_ui.addEmpty()
             else:
                 param_ui.addLabel(label or name)
-            param_ui.addElement(name=name, type=type, value=value, callback_id=callback_id)
+            param_ui.addElement(name=name, type_=type_, value=value, callback_id=callback_id)
 
     return param_ui.toXml()
 
 
-
-
 class XMLUI(object):
     """This class is used to create a user interface (form/window/parameters/etc) using SàT XML"""
 
@@ -127,7 +126,7 @@
         if not panel_type in ['window', 'form', 'param']:
             error(_("Unknown panel type [%s]") % panel_type)
             assert(False)
-        self.type = panel_type
+        self.type_ = panel_type
         impl = minidom.getDOMImplementation()
 
         self.doc = impl.createDocument(None, "sat_xmlui", None)
@@ -135,8 +134,9 @@
         top_element.setAttribute("type", panel_type)
         if title:
             top_element.setAttribute("title", title)
-        self.parentTabsLayout = None #used only we have 'tabs' layout
-        self.currentCategory = None #used only we have 'tabs' layout
+        self.parentTabsLayout = None  # used only we have 'tabs' layout
+        self.currentCategory = None  # used only we have 'tabs' layout
+        self.currentLayout = None
         self.changeLayout(layout)
 
     def __del__(self):
@@ -148,17 +148,17 @@
         @parent: parent element or None
         """
         if not layout in ['vertical', 'horizontal', 'pairs', 'tabs']:
-            error (_("Unknown layout type [%s]") % layout)
-            assert (False)
+            error(_("Unknown layout type [%s]") % layout)
+            assert False
         layout_elt = self.doc.createElement('layout')
-        layout_elt.setAttribute('type',layout)
-        if parent != None:
+        layout_elt.setAttribute('type', layout)
+        if parent is not None:
             parent.appendChild(layout_elt)
         return layout_elt
 
-    def __createElem(self, type, name=None, parent = None):
+    def __createElem(self, type_, name=None, parent=None):
         """Create an element
-        @param type: one of
+        @param type_: one of
             - empty: empty element (usefull to skip something in a layout, e.g. skip first element in a PAIRS layout)
             - text: text to be displayed in an multi-line area, e.g. instructions
         @param name: name of the element or None
@@ -167,8 +167,8 @@
         elem = self.doc.createElement('elem')
         if name:
             elem.setAttribute('name', name)
-        elem.setAttribute('type', type)
-        if parent != None:
+        elem.setAttribute('type', type_)
+        if parent is not None:
             parent.appendChild(elem)
         return elem
 
@@ -178,10 +178,9 @@
         if layout == "tabs":
             self.parentTabsLayout = self.currentLayout
 
-
     def addEmpty(self, name=None):
         """Add a multi-lines text"""
-        elem = self.__createElem('empty', name, self.currentLayout)
+        self.__createElem('empty', name, self.currentLayout)
 
     def addText(self, text, name=None):
         """Add a multi-lines text"""
@@ -214,15 +213,15 @@
 
     def addBool(self, name=None, value="true"):
         """Add a string box"""
-        assert value in ["true","false"]
+        assert value in ["true", "false"]
         elem = self.__createElem('bool', name, self.currentLayout)
         elem.setAttribute('value', value)
 
     def addList(self, options, name=None, value=None, style=set()):
         """Add a list of choices"""
         styles = set(style)
-        assert (options)
-        assert (styles.issubset(['multi']))
+        assert options
+        assert styles.issubset(['multi'])
         elem = self.__createElem('list', name, self.currentLayout)
         self.addOptions(options, elem)
         if value:
@@ -244,31 +243,29 @@
             fback_el.setAttribute('name', field)
             elem.appendChild(fback_el)
 
-
-
-    def addElement(self, type, name = None, value = None, options = None, callback_id = None):
+    def addElement(self, type_, name=None, value=None, options=None, callback_id=None):
         """Convenience method to add element, the params correspond to the ones in addSomething methods"""
-        if type == 'empty':
+        if type_ == 'empty':
             self.addEmpty(name)
-        elif type == 'text':
-            assert(value!=None)
+        elif type_ == 'text':
+            assert value is not None
             self.addText(value, name)
-        elif type == 'label':
+        elif type_ == 'label':
             assert(value)
             self.addLabel(value)
-        elif type == 'string':
+        elif type_ == 'string':
             self.addString(name, value)
-        elif type == 'password':
+        elif type_ == 'password':
             self.addPassword(name, value)
-        elif type == 'textbox':
+        elif type_ == 'textbox':
             self.addTextBox(name, value)
-        elif type == 'bool':
+        elif type_ == 'bool':
             if not value:
                 value = "true"
             self.addBool(name, value)
-        elif type == 'list':
+        elif type_ == 'list':
             self.addList(options, name, value)
-        elif type == 'button':
+        elif type_ == 'button':
             assert(callback_id and value)
             self.addButton(callback_id, name, value)
 
@@ -303,26 +300,28 @@
         return self.doc.toxml()
 
 
-
 class ElementParser(object):
     """callable class to parse XML string into Element
     Found at http://stackoverflow.com/questions/2093400/how-to-create-twisted-words-xish-domish-element-entirely-from-raw-xml/2095942#2095942
     (c) Karl Anderson"""
 
-    def __call__(self, s):
+    def __call__(self, string):
         self.result = None
-        def onStart(el):
-            self.result = el
+
+        def onStart(elem):
+            self.result = elem
+
         def onEnd():
             pass
-        def onElement(el):
-            self.result.addChild(el)
+
+        def onElement(elem):
+            self.result.addChild(elem)
 
         parser = domish.elementStream()
         parser.DocumentStartEvent = onStart
         parser.ElementEvent = onElement
         parser.DocumentEndEvent = onEnd
         tmp = domish.Element((None, "s"))
-        tmp.addRawXml(s.replace('\n','').replace('\t',''))
+        tmp.addRawXml(string.replace('\n', '').replace('\t', ''))
         parser.parse(tmp.toXml().encode('utf-8'))
         return self.result.firstChildElement()