Python : How to call dictionnary-contained callables at a given time?
Question: I'm working with a dictionary object in python which contains numerous keys.
Some of their associated value type is of callable type.

Something like :

    
    
    dico = {
        'key1' : 1,
        'key2' : 'cars',
        'key3' : <bound method MyClass.MyMethod_A of <MyClass: MyClass object >>,
        'deeperkeys':{
                      subkey1 : 'space',
                      subkey2 : <bound method MyClass.MyMethod_B of <MyClass: MyClass object >>,
                     },
           }
    

I know i can do:

    
    
    dico['key3'] = dico['key3']()
    dico['deeperkeys']['subkey2'] = dico['deeperkeys']['subkey2']()
    

Furthermore, notice that i do not work on a unic `dico` as presented above,
but on a huge list of `dico`-like dictionaries. Also, i sometimes do not know
which keys must be called. What is the best way to discriminately and
transcendentally call all callables ?

# upd

Following Jon Kiparsky, i added a `@property` decorator above each method
definition. And it did the trick by taking the problem upside down. No
callables but called methods with this decorator to the source definition of
`MyClass`. And my lists of dictionaries are generated from it !


Answer: The literal answer to your question is the `callable` function, which returns
true if you pass it something callable and false if you don't.

For example:

    
    
    def undefer(func_or_value):
        if callable(func_or_value):
            return func_or_value()
        else:
            return func_or_value
    

And now you can write:

    
    
    dico['key3'] = undefer(dico['key3'])
    

However, this is probably going to turn out to be a very bad idea. You might
not care about the limitations (e.g., now you can't actually store anything
callable as a value, and you might want to, say, store a type in there one
day), but you obviously care about the confusion engendered by mixing up
nullary functions and values as the same kind of thing, because that confusion
is what leads to this question in the first place.

What I think you _want_ to do is store a dict of nothing but callables, so you
always call the value. Some of these callables just return a constant value,
but that's fine: just store `lambda: 42` instead of 42.

Or you might want to make things even more explicit. It's not really
callability that you care about here; the point of those methods is that they
act like deferred values, or futures. You can write a very simple
deferred/future class that can be constructed from either a constant or a
function call. That also lets you add features like "only call this function
the first time, from then on cache the value". But, more importantly, it makes
it explicit what you're doing; there's no way to confuse a Future with
anything else, error messages from missing a deferral or undeferral will be
obvious and trivial to fix, etc.

