[Tutor] easy way to populate a dict with functions

bob gailer bgailer at gmail.com
Tue Aug 11 16:22:07 CEST 2009


Albert-Jan Roskam wrote:
> Hi Bob,
>
> Sorry for the late reply, but thank you for your code. I still haven't completely wrappped my brain around decorator functions, but thanks to your reply at least now my frontal lobe is touching it. ;-)
>   

Decorator functions:

def collect(func):
 'a "decorator" that adds each function to the cmds list'
 cmds.append((func.__name__, func))

# once collect is defined it may be used as a decorator:

@collect
def foo (a):
  return "foo" * a

# this means
# 1 - define foo
# 2 - run the following statement
foo = collect(foo)

# that
#  1 - appends foo to the cmds list
#  2 - returns None
#  3 - assigns None to foo (since we no longer need that name)

Admittedly this is not how decorators were intended to be used. The 
intention was to create some new function (presumably derived from foo 
in some useful way), return that and assign it to foo.

> Re: the ordering of functions: I thought it mattered because the inspect module returns a list of two-tuples (in this case, a list of four two-tuples). Therefore, e.g. option #1 should always cause the same function to be run. But apparently I'm wrong here somewhere.
>   
The only "wrong" is expecting order to be preserved, which dictionaries 
do not guarantee.

-- 
Bob Gailer
Chapel Hill NC
919-636-4239


More information about the Tutor mailing list