My collection of python tricks and small utilities

I have decided to collect here some Python tricks that I find interesting and useful:

How to show a function’s variables:

    print vars() #Inside the function

How to show an object’s methods:

    def getMethods(self, object):
        temp = inspect.getmembers(object, predicate=inspect.ismethod)
        for method in temp:
            print method[0]

How to re-scale one value:

    def scale(Value, OldMin, OldMax, NewMin, NewMax):
        OldRange = (OldMax - OldMin)
        if OldRange == 0:
            NewValue = NewMin
        else:
            NewRange = (NewMax - NewMin)
        NewValue = (((Value - OldMin) * NewRange) / OldRange) + NewMin
        return NewValue

How to show a (i.e. right-click) pop-up menu in wxPython:

    def onLearn(self, event, track, widget):
        def MenuSelectionCb(event):
            operation = menu_title_by_id[event.GetId()]
            target    = self.parent_button_label
            print 'PERFORM: ' + str(operation) + ' ON BUTTON: ' + str(target)
            #if operation == 'MIDI Learn':
            #    self.midiLearn(event,track, target)

        menu_titles = [ "MIDI Learn", "Cancel"]
        menu_title_by_id = {}
        for title in menu_titles:
            menu_title_by_id[ menu_titles.index(title) ] = title
        self.list_item_clicked = right_click_context = event.GetEventObject().GetLabel()
        menu = wx.Menu()
        for (id,title) in menu_title_by_id.items():
            menu.Append( id, title )
            wx.EVT_MENU( menu, id, MenuSelectionCb )
        self.PopupMenu( menu)
        menu.Destroy() # destroy to avoid mem leak

How to create a listener:

    import time
    from functools import partial

    def testFunction():
        print 'REXECUTED FUNCTION FROM LISTENER, FINAL VALUE IS: ', a._masterRMS


    class test(object):
        def __init__(self):
            self._masterRMS = (0,0)
            self._masterRMS_listeners = []


        @property
        def masterRMS(self):
            return self._masterRMS

        @masterRMS.setter
        def masterRMS(self, value):
            self._masterRMS = value
            print 'UPDATED VALUE OF VARIABLE TO: ', value
            for callback in self._masterRMS_listeners:
                print 'GOING TO EXECUTE CALLBACK ACTION'
                callback()

        def add_masterRMS_listener(self, callback):
            print 'ADDED LISTENER: ', callback
            self._masterRMS_listeners.append(callback)

        def remove_masterRMS_listener(self, callback):
            self._masterRMS_listeners.remove(callback)


    a = test()
    print 'INITIAL RMS VALUE: ', a.masterRMS
    time.sleep (2)
    a.add_masterRMS_listener(testFunction)
    time.sleep (2)
    print 'GOING TO CHANGE THE RMS VALUE'
    time.sleep (2)
    a.masterRMS = (2,2)
    time.sleep (5)