[Sugar-devel] Simplification help request

Aleksey Lim alsroot at activitycentral.org
Wed Aug 24 10:21:02 EDT 2011


On Tue, Aug 23, 2011 at 03:27:22PM -0400, Art Hunkins wrote:
> In my current activity (SamplePlay), I've got 26 buttons that allow a user 
> to select (from the Journal) up to 26 audio samples/loops to play. AFAIK, 
> the "filename" must be sent to Csound as a discrete variable, on its own 
> channel (see below).
> 
> As a result, I've 26 iterations(!) (0-25) of the same basic code. I'd like 
> to simplify it if possible (the code itself works fine). Any suggestions are 
> very much welcomed.
> 
>    self.path0 = "0"
>   .....
>    self.path25 = "0"
> 
>    self.jobject0 = None
>   .....
>    self.jobject25 = None
> 
>  def choose0(self, widget):
>    chooser = ObjectChooser(parent=self, what_filter=mime.GENERIC_TYPE_AUDIO)
>    result = chooser.run()
>    if result == gtk.RESPONSE_ACCEPT:
>      self.jobject0 = chooser.get_selected_object()
>      self.path0 = str(self.jobject0.get_file_path())
>    else:
>      self.jobject0 = None
>      self.path0 = "0"
>   .....
> def choose25(self, widget):
>    chooser = ObjectChooser(parent=self, what_filter=mime.GENERIC_TYPE_AUDIO)
>    result = chooser.run()
>    if result == gtk.RESPONSE_ACCEPT:
>      self.jobject25 = chooser.get_selected_object()
>      self.path25 = str(self.jobject25.get_file_path())
>    else:
>      self.jobject25 = None
>      self.path25 = "0"
> 
> def send_data(self):
>    self.w.set_filechannel("file0", self.path0)
>    self.w.set_filechannel("file1", self.path1)
>   .....
>    self.w.set_filechannel("file24", self.path24)
>    self.w.set_filechannel("file25", self.path25)
> 
> Hoping (as a Python novice) to be shown a better way -

starting from the code you posted, the optimization might look like:

    MAX_EXAMPLES = 26

    class ...:
        def __init__(self):
            ...
            self._examples = []

            for num in range(MAX_EXAMPLES):
                widget = ...
                widget.connect('...', self.__choose_cb, num)

        def __choose_cb(self, widget, num):
            chooser = ObjectChooser(parent=self,
                    what_filter=mime.GENERIC_TYPE_AUDIO)
            result = chooser.run()
            if result == gtk.RESPONSE_ACCEPT:
                self._examples[num] = chooser.get_selected_object()
            else:
                self._examples[num] = None

        def send_data(self):
            for num in range(MAX_EXAMPLES):
                if self._examples[num] is not None:
                    self.w.set_filechannel('file%s' % num,
                            self._examples[num].get_file_path())

-- 
Aleksey


More information about the Sugar-devel mailing list