]> git.donarmstrong.com Git - lilypond.git/commitdiff
MusicXML: coding style fixes.
authorReinhold Kainhofer <reinhold@kainhofer.com>
Mon, 20 Aug 2007 08:42:57 +0000 (10:42 +0200)
committerHan-Wen Nienhuys <hanwen@xs4all.nl>
Sat, 1 Sep 2007 03:07:33 +0000 (00:07 -0300)
-) instead of accessing dicts by dict[key], use dict.get (key)
-) instead of try:... except KeyError:.. use dict.get (key)
and test for None afterward

python/musicexp.py
python/musicxml.py
scripts/musicxml2ly.py

index b543dbc2e6056d5267406d485c13137d4dc25d15..38f772c38ad6f8168b332c87d8ac6365c23fcea6 100644 (file)
@@ -481,13 +481,13 @@ class SlurEvent (SpanEvent):
     def ly_expression (self):
         return {-1: '(',
             0:'',
-            1:')'}[self.span_direction]
+            1:')'}.get (self.span_direction, '')
 
 class BeamEvent (SpanEvent):
     def ly_expression (self):
         return {-1: '[',
             0:'',
-            1:']'}[self.span_direction]
+            1:']'}.get (self.span_direction, '')
 
 class ArpeggioEvent(Event):
     def ly_expression (self):
@@ -503,11 +503,7 @@ class HairpinEvent (Event):
     def __init__ (self, type):
         self.type = type
     def hairpin_to_ly (self):
-        val = ''
-        tp = { 0: '\!', 1: '\<', -1: '\>' }.get (self.type)
-        if tp:
-            val += tp
-        return val
+        return { 0: '\!', 1: '\<', -1: '\>' }.get (self.type, '')
     
     def ly_expression (self):
         return self.hairpin_to_ly ()
@@ -549,11 +545,7 @@ class ArticulationEvent (Event):
         self.force_direction = None
 
     def direction_mod (self):
-        dirstr = { 1: '^', -1: '_', 0: '-' }.get (self.force_direction)
-        if dirstr:
-            return dirstr
-        else:
-            return ''
+        return { 1: '^', -1: '_', 0: '-' }.get (self.force_direction, '')
 
     def ly_expression (self):
         return '%s\\%s' % (self.direction_mod (), self.type)
@@ -679,7 +671,7 @@ class ClefChange (Music):
         }
     
     def lisp_expression (self):
-        (glyph, pos, c0) = self.clef_dict [self.type]
+        (glyph, pos, c0) = self.clef_dict.get (self.type)
         clefsetting = """
         (make-music 'SequentialMusic
         'elements (list
index 132ce5a752021d2798d60f0c86425873cb37b628..f7b962dba8ff929d8df54b83232faf38e7dade7a 100644 (file)
@@ -57,7 +57,7 @@ class Xml_node:
        return self._children
 
     def get_maybe_exist_named_child (self, name):
-       return self.get_maybe_exist_typed_child (class_dict[name])
+       return self.get_maybe_exist_typed_child (class_dict.get (name))
 
     def get_maybe_exist_typed_child (self, klass):
        cn = self.get_typed_children (klass)
@@ -93,17 +93,17 @@ class Hash_comment (Music_xml_node):
 
 class Pitch (Music_xml_node):
     def get_step (self):
-       ch = self.get_unique_typed_child (class_dict[u'step'])
+       ch = self.get_unique_typed_child (class_dict.get (u'step'))
        step = ch.get_text ().strip ()
        return step
     def get_octave (self):
-       ch = self.get_unique_typed_child (class_dict[u'octave'])
+       ch = self.get_unique_typed_child (class_dict.get (u'octave'))
 
        step = ch.get_text ().strip ()
        return int (step)
 
     def get_alteration (self):
-       ch = self.get_maybe_exist_typed_child (class_dict[u'alter'])
+       ch = self.get_maybe_exist_typed_child (class_dict.get (u'alter'))
        alter = 0
        if ch:
            alter = int (ch.get_text ().strip ())
@@ -135,7 +135,7 @@ class Attributes (Measure_element):
            self._dict[c.get_name()] = c
 
     def get_named_attribute (self, name):
-       return self._dict[name]
+       return self._dict.get (name)
 
     def get_measure_length (self):
         (n,d) = self.get_time_signature ()
@@ -183,7 +183,7 @@ class Note (Measure_element):
         self.instrument_name = ''
         
     def get_duration_log (self):
-       ch = self.get_maybe_exist_typed_child (class_dict[u'type'])
+       ch = self.get_maybe_exist_typed_child (class_dict.get (u'type'))
 
        if ch:
            log = ch.get_text ().strip()
@@ -194,7 +194,7 @@ class Note (Measure_element):
                     '32nd': 5,
                     'breve': -1,
                     'long': -2,
-                    'whole': 0} [log]
+                    'whole': 0}.get (log)
        else:
            return 0
 
@@ -202,7 +202,7 @@ class Note (Measure_element):
        return 1
 
     def get_pitches (self):
-       return self.get_typed_children (class_dict[u'pitch'])
+       return self.get_typed_children (class_dict.get (u'pitch'))
 
 class Part_list (Music_xml_node):
     def __init__ (self):
@@ -225,15 +225,16 @@ class Part_list (Music_xml_node):
         if not self._id_instrument_name_dict:
             self.generate_id_instrument_dict()
 
-        try:
-            return self._id_instrument_name_dict[id]
-        except KeyError:
+        instrument_name = self._id_instrument_name_dict.get (id)
+        if instrument_name:
+            return instrument_name
+        else:
             print "Opps, couldn't find instrument for ID=", id
             return "Grand Piano"
         
 class Measure(Music_xml_node):
     def get_notes (self):
-       return self.get_typed_children (class_dict[u'note'])
+       return self.get_typed_children (class_dict.get (u'note'))
 
     
 class Musicxml_voice:
@@ -294,7 +295,7 @@ class Part (Music_xml_node):
                     attributes_object = n
                     
                    factor = Rational (1,
-                                      int (attributes_dict['divisions'].get_text ()))
+                                      int (attributes_dict.get ('divisions').get_text ()))
 
                 
                if (n.get_maybe_exist_typed_child (Duration)):
@@ -355,7 +356,7 @@ class Part (Music_xml_node):
 
        start_attr = None
        for n in elements:
-           voice_id = n.get_maybe_exist_typed_child (class_dict['voice'])
+           voice_id = n.get_maybe_exist_typed_child (class_dict.get ('voice'))
 
             # TODO: If the first element of a voice is a dynamics entry,
             #       then voice_id is not yet set! Thus it will currently be ignored
@@ -400,8 +401,8 @@ class Notations (Music_xml_node):
 
 class Time_modification(Music_xml_node):
     def get_fraction (self):
-       b = self.get_maybe_exist_typed_child (class_dict['actual-notes'])
-       a = self.get_maybe_exist_typed_child (class_dict['normal-notes'])
+       b = self.get_maybe_exist_typed_child (class_dict.get ('actual-notes'))
+       a = self.get_maybe_exist_typed_child (class_dict.get ('normal-notes'))
        return (int(a.get_text ()), int (b.get_text ()))
 
 class Accidental (Music_xml_node):
@@ -532,9 +533,10 @@ def name2class_name (name):
     return str (name)
 
 def get_class (name):
-    try:
-        return class_dict[name]
-    except KeyError:
+    classname = class_dict.get (name)
+    if classname:
+        return classname
+    else:
        class_name = name2class_name (name)
        klass = new.classobj (class_name, (Music_xml_node,) , {})
        class_dict[name] = klass
index 373dd5d1f10e25e78f84dea438388df5c6d4a91e..9e48b1f53ebfc2b936862c5c95042e40df3457a0 100644 (file)
@@ -49,7 +49,7 @@ def group_tuplets (music_list, events):
     j = 0
     for (ev_chord, tuplet_elt, fraction) in events:
         while (j < len (music_list)):
-            if music_list[j]== ev_chord:
+            if music_list[j] == ev_chord:
                 break
             j += 1
         if tuplet_elt.type == 'start':
@@ -154,26 +154,23 @@ def musicxml_spanner_to_lily_event (mxl_event):
     ev = None
     
     name = mxl_event.get_name()
-    try:
-        func = spanner_event_dict[name]
+    func = spanner_event_dict.get (name)
+    if func:
         ev = func()
-    except KeyError:
+    else:
         print 'unknown span event ', mxl_event
 
-    try:
-        key = mxl_event.get_type ()
-        ev.span_direction = spanner_type_dict[key]
-    except KeyError:
+    key = mxl_event.get_type ()
+    span_direction = spanner_type_dict.get (key)
+    if span_direction:
+        ev.span_direction = span_direction
+    else:
         print 'unknown span type', key, 'for', name
 
     return ev
 
 def musicxml_direction_to_indicator (direction):
-    val = { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction)
-    if val:
-        return val
-    else:
-        return ''
+    return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
 
 def musicxml_fermata_to_lily_event (mxl_event):
     ev = musicexp.ArticulationEvent ()
@@ -286,6 +283,8 @@ def musicxml_direction_to_lily( n ):
                 wedgetype = entry.type;
                 wedgetypeval = {"crescendo" : 1, "decrescendo" : -1, 
                                 "diminuendo" : -1, "stop" : 0 }.get (wedgetype)
+                # Really check for != None, becaus otherwise 0 will also cause 
+                # the code to be executed!
                 if wedgetypeval != None:
                     event = musicexp.HairpinEvent (wedgetypeval)
                     res.append (event)
@@ -320,9 +319,10 @@ def musicxml_note_to_lily_main_event (n):
         event = musicexp.RestEvent()
     elif n.instrument_name:
         event = musicexp.NoteEvent ()
-        try:
-            event.drum_type = instrument_drumtype_dict[n.instrument_name]
-        except KeyError:
+        drum_type = instrument_drumtype_dict.get (n.instrument_name)
+        if drum_type:
+            event.drum_type = drum_type
+        else:
             n.message ("drum %s type unknow, please add to instrument_drumtype_dict" % n.instrument_name)
             event.drum_type = 'acousticsnare'
     
@@ -475,11 +475,8 @@ def musicxml_voice_to_lily_voice (voice):
         
         main_event = musicxml_note_to_lily_main_event (n)
 
-        try:
-            if main_event.drum_type:
-                modes_found['drummode'] = True
-        except AttributeError:
-            pass
+        if hasattr (main_event, 'drum_type') and main_event.drum_type:
+            modes_found['drummode'] = True
 
 
         ev_chord = voice_builder.last_event_chord (n._when)
@@ -706,7 +703,7 @@ def print_voice_definitions (printer, part_list, voices):
         part_dict[part.id] = (part, nv_dict)
 
     for part in part_list:
-        (part, nv_dict) = part_dict[part.id]
+        (part, nv_dict) = part_dict.get (part.id, (None, {}))
         for (name, (voice, mxlvoice)) in nv_dict.items ():
             k = music_xml_voice_name_to_lily_name (part, name)
             printer.dump ('%s = ' % k)
@@ -724,13 +721,12 @@ def print_score_setup (printer, part_list, voices):
     printer.newline ()
     for part_definition in part_list:
         part_name = part_definition.id
-        try:
-            part = part_dict[part_name]
-        except KeyError:
+        part = part_dict.get (part_name)
+        if not part:
             print 'unknown part in part-list:', part_name
             continue
 
-        nv_dict = voices[part]
+        nv_dict = voices.get (part)
         staves = reduce (lambda x,y: x+ y,
                 [mxlvoice._staves.keys ()
                  for (v, mxlvoice) in nv_dict.values ()],