lilypond-devel
[Top][All Lists]
Advanced

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

Re: Replace deprecated functions from string module (issue 566920044 by


From: jonas . hahnfeld
Subject: Re: Replace deprecated functions from string module (issue 566920044 by address@hidden)
Date: Wed, 23 Oct 2019 23:33:49 -0700

Reviewers: Malte Meyn,

Message:
On 2019/10/23 21:22:16, Malte Meyn wrote:
For someone who doesn’t know python two questions come up:

1. Why do you sometimes use " " and sometimes ' '?

AFAIK there is no difference between the two ways of writing a constant
string (or not relevant here), so I've tried to stay consistent with the
surrounding code.

2. Is a space (" " or ' ') the default for the old string.join? Or
should you
use an empty string ("".join()) instead in some places of the new
version?

A space is the old default. I quoted the relevant documentation in the
commit message of the separate patches I posted in the issue, but
unfortunately this is lost when uploading for review here :-(

Description:
Replace deprecated functions from string module

These methods have been deprecated since at least Python 2.4 and their
replacements are available since at least that version.

Individual changes:
 * Replace string.atoi() by int()
 * Replace string.split() by str.split()
 * Replace string.join() by sep.join()
 * Replace string.strip() by str.strip()
 * Replace string.replace() by str.replace()
 * Drop now unused 'import string'

Please review this at https://codereview.appspot.com/566920044/

Affected files (+33, -41 lines):
  M python/convertrules.py
  M python/musicexp.py
  M python/musicxml.py
  M python/utilities.py
  M scripts/auxiliar/fixcc.py
  M scripts/build/install.py
  M scripts/build/text2html.py
  M scripts/lilymidi.py
  M scripts/musicxml2ly.py


Index: python/convertrules.py
diff --git a/python/convertrules.py b/python/convertrules.py
index 356c6882311e68ba8555f70f58861afedc76de34..29f13f222b0a87b20b21006d0ef36aa919ba40d2 100644
--- a/python/convertrules.py
+++ b/python/convertrules.py
@@ -3436,7 +3436,7 @@ grob_path = symbol_list + r"(?:\s+" + symbol_list + r")*"
 grob_spec = wordsyntax + r"(?:\s*\.\s*" + wordsyntax + r")?"

 def path_replace (m):
- return m.group (1) + string.join (re.findall (wordsyntax, m.group (2)), ".")
+    return m.group (1) + ".".join (re.findall (wordsyntax, m.group (2)))

 # The following regexp appears to be unusually expensive to compile,
 # so we do it only once instead of for every file
@@ -3452,7 +3452,7 @@ footnotec = re.compile ("(" + matchfullmarkup + ")|"
 def conv (str):
     def patrep (m):
         def fn_path_replace (m):
-            x = string.join (re.findall (wordsyntax, m.group (2)), ".")
+            x = ".".join (re.findall (wordsyntax, m.group (2)))
             if x in ["TimeSignature", "KeySignature", "BarLine",
                      "Clef", "StaffSymbol", "OttavaBracket",
                      "LedgerLineSpanner"]:
@@ -3895,7 +3895,7 @@ def conv (str):
@rule ((2, 19, 46), r"\context ... \modification -> \context ... \with \modification")
 def conv (str):
     word=r'(?:#?"[^"]*"|\b' + wordsyntax + r'\b)'
- mods = string.join (re.findall ("\n(" + wordsyntax + r")\s*=\s*\\with(?:\s|\\|\{)", str) + mods = str.join (re.findall ("\n(" + wordsyntax + r")\s*=\s*\\with(?:\s|\\|\{)") + ['RemoveEmptyStaves','RemoveAllEmptyStaves'], "|")
     str = re.sub (r"(\\(?:drums|figures|chords|lyrics|addlyrics|"
                   + r"(?:new|context)\s*" + word
Index: python/musicexp.py
diff --git a/python/musicexp.py b/python/musicexp.py
index c29b11b1543befc0aa6ea9fc843a336f519f0ca3..b7940bdb02a0b0bca2f2b553c1bd5cc64bd1117c 100644
--- a/python/musicexp.py
+++ b/python/musicexp.py
@@ -1,7 +1,6 @@
 # -*- coding: utf-8 -*-
 import inspect
 import sys
-import string
 import re
 import math
 import lilylib as ly
@@ -19,7 +18,7 @@ whatOrnament = ""
 ly_dur = None # stores lilypond durations

 def escape_instrument_string (input_string):
-    retstring = string.replace (input_string, "\"", "\\\"")
+    retstring = input_string.replace ("\"", "\\\"")
     if re.match ('.*[\r\n]+.*', retstring):
         rx = re.compile (r'[\n\r]+')
         strings = rx.split (retstring)
@@ -529,7 +528,7 @@ class Music:
             printer.newline ()
             return

-        lines = string.split (text, '\n')
+        lines = text.split ('\n')
         for l in lines:
             if l:
                 printer.unformatted_output ('% ' + l)
@@ -692,12 +691,12 @@ class NestedMusic(Music):

     def get_properties (self):
         return ("'elements (list %s)"
-            % string.join (map (lambda x: x.lisp_expression(),
+            % " ".join (map (lambda x: x.lisp_expression(),
                       self.elements)))

     def get_subset_properties (self, predicate):
         return ("'elements (list %s)"
-            % string.join (map (lambda x: x.lisp_expression(),
+            % " ".join (map (lambda x: x.lisp_expression(),
                       filter (predicate, self.elements))))
     def get_neighbor (self, music, dir):
         assert music.parent == self
@@ -1038,7 +1037,7 @@ class ChordEvent (NestedMusic):
                     basepitch = previous_pitch
             if stem:
                 printer (stem.ly_expression ())
-            printer ('<%s>' % string.join (pitches))
+            printer ('<%s>' % ' '.join (pitches))
             previous_pitch = basepitch
             duration = self.get_duration ()
             if duration:
@@ -1477,7 +1476,7 @@ class FretBoardEvent (NestedMusic):
           notes = []
           for n in fretboard_notes:
               notes.append (n.ly_expression ())
-          contents = string.join (notes)
+          contents = ' '.join (notes)
           printer ('<%s>%s' % (contents,self.duration))

 class FunctionWrapperEvent (Event):
@@ -1667,7 +1666,7 @@ class RhythmicEvent(Event):
return [ev.pre_note_ly (is_chord_element) for ev in self.associated_events]

     def ly_expression_pre_note (self, is_chord_element):
-        res = string.join (self.pre_note_ly (is_chord_element), ' ')
+        res = ' '.join (self.pre_note_ly (is_chord_element))
         if res != '':
             res = res + ' '
         return res
@@ -1815,7 +1814,7 @@ class KeySignatureChange (Music):
         elif self.non_standard_alterations:
             alterations = [self.format_non_standard_alteration (a) for
                                         a in self.non_standard_alterations]
- return "\\set Staff.keyAlterations = #`(%s)" % string.join (alterations, " ") + return "\\set Staff.keyAlterations = #`(%s)" % " ".join (alterations)
         else:
             return ''

@@ -1859,7 +1858,7 @@ class TimeSignatureChange (Music):
     def format_fraction (self, frac):
         if isinstance (frac, list):
             l = [self.format_fraction (f) for f in frac]
-            return "(" + string.join (l, " ") + ")"
+            return "(" + " ".join (l) + ")"
         else:
             return "%s" % frac

@@ -2076,7 +2075,7 @@ class FiguredBassEvent (NestedMusic):
           notes = []
           for x in figured_bass_events:
               notes.append (x.ly_expression ())
-          contents = string.join (notes)
+          contents = ' '.join (notes)
           if self.parentheses:
               contents = '[%s]' % contents
           printer ('<%s>' % contents)
Index: python/musicxml.py
diff --git a/python/musicxml.py b/python/musicxml.py
index 6b70e02cc580434436bedd82ac502a16bea94c98..82a76398501fe42670490f11d28177e64a2aabb8 100644
--- a/python/musicxml.py
+++ b/python/musicxml.py
@@ -1,6 +1,5 @@
 # -*- coding: utf-8 -*-
 import new
-import string
 from rational import *
 import re
 import sys
@@ -198,7 +197,7 @@ class Identification(Xml_node):
                 ret.append(result)
             else:
                 ret.append(text)
-        return string.join(ret, "\n")
+        return "\n".join(ret)

# get contents of the source-element(usually used for publishing information).(These contents are saved in a custom variable named "source" in the header of the .ly file.)
     def get_source(self):
@@ -206,7 +205,7 @@ class Identification(Xml_node):
         ret = []
         for r in source:
           ret.append(r.get_text())
-        return string.join(ret, "\n")
+        return "\n".join(ret)

     def get_creator(self, type):
         creators = self.get_named_children('creator')
@@ -386,7 +385,7 @@ class Duration(Music_xml_node):
 class Hash_text(Music_xml_node):

     def dump(self, indent=''):
-        ly.debug_output('%s' % string.strip(self._data))
+        ly.debug_output(self._data.strip())


 class Pitch(Music_xml_node):
@@ -519,7 +518,7 @@ class Attributes(Measure_element):
                 current_sig = []
                 for i in mxl.get_all_children():
                     if isinstance(i, Beats):
-                        beats = string.split(i.get_text().strip(), "+")
+                        beats = i.get_text().strip().split("+")
                         current_sig = [int(j) for j in beats]
                     elif isinstance(i, BeatType):
                         current_sig.append(int(i.get_text()))
Index: python/utilities.py
diff --git a/python/utilities.py b/python/utilities.py
index e77b96adc21c2abe25521e028620cfb55be1203b..e124539d3bf2b6ecfe5e0c136d9a73ce2da72758 100644
--- a/python/utilities.py
+++ b/python/utilities.py
@@ -1,6 +1,5 @@
 # -*- coding: utf-8 -*-
 import re
-import string

 def string_to_number(s):
     try:
@@ -19,7 +18,7 @@ def escape_ly_output_string (input_string):
     return_string = input_string
     needs_quotes = not re.match (u"^[a-zA-ZäöüÜÄÖßñ]*$", return_string);
     if needs_quotes:
- return_string = "\"" + string.replace (return_string, "\"", "\\\"") + "\""
+        return_string = "\"" + return_string.replace ("\"", "\\\"") + "\""
     return return_string

 def interpret_alter_element (alter_elm):
Index: scripts/auxiliar/fixcc.py
diff --git a/scripts/auxiliar/fixcc.py b/scripts/auxiliar/fixcc.py
index 4e5b2e5a1ebfa98bd95d585791178e0ff4d51ccc..54d5ddd3fd24bbb76e79a561b18c88ff3c55e738 100755
--- a/scripts/auxiliar/fixcc.py
+++ b/scripts/auxiliar/fixcc.py
@@ -28,7 +28,6 @@ import __main__
 import getopt
 import os
 import re
-import string
 import sys
 import time
 import subprocess
@@ -323,7 +322,7 @@ def nitpick_file (outdir, file):
     #code = filter (lambda x: is_derived_class (x.__class__, Substring),
     #               chunks)

-    t = string.join (map (lambda x: x.filter_text (), chunks), '')
+    t = ''.join (map (lambda x: x.filter_text (), chunks))
     fixt = file
     if s != t:
         if not outdir:
Index: scripts/build/install.py
diff --git a/scripts/build/install.py b/scripts/build/install.py
index 9818543a3f15022d74c0d1d0638e77b3af8cace8..2bc6d5b213e710706ad9b654b4d5674ff29e9977 100644
--- a/scripts/build/install.py
+++ b/scripts/build/install.py
@@ -1,5 +1,4 @@
 #!@PYTHON@
-import string
 import getopt
 import sys
 import os
@@ -23,7 +22,7 @@ for (o,a) in opts:
     elif o == '-g':
         group = a
     elif o == '-m':
-        mode = string.atoi (a, 8)
+        mode = int (a, base=8)
     elif o == '-o':
         owner = a
     elif o == '-s':
Index: scripts/build/text2html.py
diff --git a/scripts/build/text2html.py b/scripts/build/text2html.py
index 245620277839f8b9a34061775a0ec68e8c0b1a7b..01b6b0d6497621fcee85dcd7e1f14e90a55804b5 100644
--- a/scripts/build/text2html.py
+++ b/scripts/build/text2html.py
@@ -1,7 +1,6 @@
 #!@PYTHON@
 import os
 import re
-import string
 import sys


Index: scripts/lilymidi.py
diff --git a/scripts/lilymidi.py b/scripts/lilymidi.py
index b515a877524d5c589f429cf415652f201865921f..4892f0b0191e8a59cecb0b32a5ee480bbd8084e1 100644
--- a/scripts/lilymidi.py
+++ b/scripts/lilymidi.py
@@ -220,8 +220,7 @@ def go ():
         if numbers:
             if options.prefix:
                 sys.stdout.write ('%s ' % (options.prefix,))
-            import string
-            sys.stdout.write (string.join (numbers, ','))
+            sys.stdout.write (','.join (numbers))
             sys.stdout.write ('\n')
     else:
         for n, name in info:
Index: scripts/musicxml2ly.py
diff --git a/scripts/musicxml2ly.py b/scripts/musicxml2ly.py
index 94b314da4bdebcde71fc2a153186b33c1c4f3288..6798124a95229f07f399fe4b1374fcffc1716e59 100755
--- a/scripts/musicxml2ly.py
+++ b/scripts/musicxml2ly.py
@@ -4,7 +4,6 @@ import optparse
 import sys
 import re
 import os
-import string
 import codecs
 import zipfile
 import tempfile
@@ -310,14 +309,14 @@ def staff_attributes_to_string_tunings(mxl_attr):
     lines = 6
     staff_lines = details.get_maybe_exist_named_child('staff-lines')
     if staff_lines:
-        lines = string.atoi(staff_lines.get_text())
+        lines = int(staff_lines.get_text())
     tunings = [musicexp.Pitch()] * lines
     staff_tunings = details.get_named_children('staff-tuning')
     for i in staff_tunings:
         p = musicexp.Pitch()
         line = 0
         try:
-            line = string.atoi(i.line) - 1
+            line = int(i.line) - 1
         except ValueError:
             pass
         tunings[line] = p
@@ -357,7 +356,7 @@ def staff_attributes_to_lily_staff(mxl_attr):
     for d in details:
         staff_lines = d.get_maybe_exist_named_child('staff-lines')
         if staff_lines:
-            lines = string.atoi(staff_lines.get_text())
+            lines = int(staff_lines.get_text())

     # TODO: Handle other staff attributes like staff-space, etc.

@@ -848,8 +847,8 @@ def musicxml_transpose_to_lily(attributes):
     shift = musicexp.Pitch()
     octave_change = transpose.get_maybe_exist_named_child('octave-change')
     if octave_change:
-        shift.octave = string.atoi(octave_change.get_text())
- chromatic_shift = string.atoi(transpose.get_named_child('chromatic').get_text())
+        shift.octave = int(octave_change.get_text())
+ chromatic_shift = int(transpose.get_named_child('chromatic').get_text())
     chromatic_shift_normalized = chromatic_shift % 12;
     (shift.step, shift.alteration) = [
         (0, 0), (0, 1), (1, 0), (2, -1), (2, 0),
@@ -860,7 +859,7 @@ def musicxml_transpose_to_lily(attributes):

     diatonic = transpose.get_maybe_exist_named_child('diatonic')
     if diatonic:
-        diatonic_step = string.atoi(diatonic.get_text()) % 7
+        diatonic_step = int(diatonic.get_text()) % 7
         if diatonic_step != shift.step:
             # We got the alter incorrect!
             old_semitones = shift.semitones()
@@ -882,7 +881,7 @@ def musicxml_staff_details_to_lily(attributes):

     stafflines = details.get_maybe_exist_named_child('staff-lines')
     if stafflines:
-        lines = string.atoi(stafflines.get_text());
+        lines = int(stafflines.get_text());
         lines_event = musicexp.StaffLinesEvent(lines);
         ret.append(lines_event);

@@ -1242,7 +1241,7 @@ def musicxml_dynamics_to_lily_event(dynentry):
     if not dynamicsname in dynamics_available:
         # Get rid of - in tag names (illegal in ly tags!)
         dynamicstext = dynamicsname
-        dynamicsname = string.replace(dynamicsname, "-", "")
+        dynamicsname = dynamicsname.replace("-", "")
         additional_definitions[dynamicsname] = dynamicsname + \
               " = #(make-dynamic-script \"" + dynamicstext + "\")"
         needed_additional_definitions.append(dynamicsname)
@@ -1312,7 +1311,7 @@ def musicxml_words_to_lily_event(words):
if hasattr(words, 'default-y') and hasattr(options, 'convert_directions') and options.convert_directions:
         offset = getattr(words, 'default-y')
         try:
-            off = string.atoi(offset)
+            off = int(offset)
             if off > 0:
                 event.force_direction = 1
             else:
@@ -1372,7 +1371,7 @@ def musicxml_accordion_to_markup(mxl_event):
         # MusicXML spec is quiet about this case...
         txt = 1
         try:
-          txt = string.atoi(middle.get_text())
+          txt = int(middle.get_text())
         except ValueError:
             pass
         if txt == 3:
@@ -1782,7 +1781,7 @@ def musicxml_harmony_to_lily_chordname(n):
             # require you to know the chord and calculate either the fifth
             # pitch (for the first inversion) or the third pitch (for the
             # second inversion) so they may not be helpful for musicxml2ly.
-            inversion_count = string.atoi(inversion.get_text())
+            inversion_count = int(inversion.get_text())
             if inversion_count == 1:
               # TODO: Calculate the bass note for the inversion...
               pass
@@ -1874,7 +1873,7 @@ def musicxml_lyrics_to_text(lyrics, ignoremelismata):
         elif isinstance(e, musicxml.Text):
# We need to convert soft hyphens to -, otherwise the ascii codec as well
             # as lilypond will barf on that character
-            text += string.replace(e.get_text(), u'\xad', '-')
+            text += e.get_text().replace(u'\xad', '-')
         elif isinstance(e, musicxml.Elision):
             if text:
                 text += " "



reply via email to

[Prev in Thread] Current Thread [Next in Thread]