Dynamic Dictionary Creation

Skip Montanaro skip at pobox.com
Fri Dec 6 14:01:25 EST 2002


Instead of

    def getNoteLen(x):
       global TicksQ
       ntb = { '1': TicksQ * 4,
          '2': TicksQ * 2,                                   
          '4': TicksQ,
          '8': TicksQ
       }                                                                  
       return ntb[str(x)]  


try this:

    ntb = { '1': TicksQ * 4,
       '2': TicksQ * 2,                                   
       '4': TicksQ,
       '8': TicksQ
    }                                                                  
    def getNoteLen(x):
       return ntb[str(x)]  

or if you want the avoid the global lookup of ntb:

    def getNoteLen(x,ntb=ntb):
       return ntb[str(x)]  

It will get done once, then not repeated.  When the function is called it
will always be a local.

Also, note that you don't need to use a global statement to read global
variables, only to modify them.

-- 
Skip Montanaro - skip at pobox.com
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list