Dynamic Dictionary Creation

Skip Montanaro skip at pobox.com
Fri Dec 6 22:29:05 EST 2002


    Bob> Thanks, Skip, for the suggestion. Guess I should have been a bit
    Bob> more clear, but the reason for sticking the table inside the
    Bob> function was to hide the table name. Not a big deal to define it
    Bob> 'globally'.

Just define it with a leading underscore.  That way if somebody imports '*'
from your module they won't pick up the dict you don't want them to have.
It's also a visual cue to anyone reading the code that it's meant to be
private.

    Bob> Is there a reason for the ntb=ntb in your function declaration? If
    Bob> the table is external to the function, would:

    Bob>        def getNoteLen(x):
    Bob>                return ntb[str(x)]

    Bob> be the same?

Functionally, yes, however in the ntb=ntb case, the default argument gets
mapped to the global at function definition time and is thereafter seen as a
local variable.  If you're referring to it a lot you should find a
performance boost.  I misunderstood why you wanted ntb local.  I thought it
was to get faster access, but you just wanted to hide it from the outside
world.  

    Bob> Guess another solution would be to have this all wrapped in a
    Bob> class.

Yup, that was going to be my next suggestion.  Depends on how much state you
need to keep around between calls.  If it's just this one dict it doesn't
seem worth it, but if there are a lot of functions operating on the same
data passed as parameters, then a class makes a lot of sense.

Skip





More information about the Python-list mailing list