Dynamic Dictionary Creation

Greg Chapman glc at well.com
Sat Dec 7 11:57:14 EST 2002


On Fri, 06 Dec 2002 11:37:07 -0700, Bob van der Poel <bvdpoel at kootenay.com>
wrote:

>
>I'm writing a program which needs to convert note lengths specified in
>somewhat standard musical notation to midi ticks. I have a function
>which does this with
>a dictionary lookup. An abreviated version is shown here:
>
>def getNoteLen(x):
>   global TicksQ
>   ntb = { '1': TicksQ *
>4,                                                               
>      '2': TicksQ * 2,                                   
>      '4': TicksQ,
>      '8': TicksQ
>}                                                                  
>                                                                                                
>   return ntb[str(x)]  
>

I have no idea if this is more or less efficient than using default arguments,
but you could also do something like this:

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

getNoteLen = new.instancemethod(getNoteLen, {DEFINE ntb HERE}, dict)

Now getNoteLen is a bound method with ntb as the instance (and the only
reference to ntb is getNoteLen.im_self).  When you call getNoteLen, it will take
only one parameter (x), unlike when default arguments are used (where some code
might pass a second argument by mistake).

You can extend this trick for any amount of data you want to bind to a function:

def someFunc((rx1, rx2), param):
    pass

someFunc = new.instancemethod(
    someFunc, 
    (re.compile(pat1), re.compile(pat2), 
    tuple
)

---
Greg Chapman




More information about the Python-list mailing list