short path evaluation, why is f() called here: dict(a=1).get('a', f())
Tim Chase
python.list at tim.thechases.com
Mon Jan 14 17:07:12 EST 2008
> But how can Python determine when you want the result to be *the
> callable* and when you want it to be *the result of calling the
> callable*?
>
> Functions and other callables are first-class objects, and it is quite
> reasonable to have something like this:
>
> map = {'a': Aclass, 'b': Bclass, 'c': Cclass}
> class_ = map.get(astring, default=Zclass)
>
> The result I want is the class, not the result of calling the class
> (which would be an instance). If I wanted the other semantics, I'd be
> using defaultdict instead.
For an example of the defaultdict usage without calling it the
first time:
from collections import defaultdict
def f():
print "Doing some expensive calculation"
return 42
d = defaultdict(f)
d['hello'] = 3.14159
print 'Hello:', d['hello']
print 'World:', d['world']
print 'World (again):', d['world']
This results in the expensive calculation only being executed
once and having the result stored in the defaultdict. This is a
good thing.
If you're doing as Steven suggests, you can pass and store
function objects or class objects with the same ease:
> map = {'a': Aclass, 'b': Bclass, 'c': Cclass}
> class_ = map.get(astring, default=Zclass)
Other than tromping on the "map" built-in, one can then
instantiate the given class with
my_instance = map.get(astring, default=Zclass)(params)
Perfect for the factory pattern if you groove on that sort of thing.
-tkc
More information about the Python-list
mailing list