getattr() on nested functions?

Hrvoje Niksic hniksic at xemacs.org
Wed Aug 20 05:05:04 EDT 2008


Gabriel Rossetti <gabriel.rossetti at arimaz.com> writes:

> I can't get getattr() to return nested functions, I tried this :
>
>>>> def toto():
> ...     def titi():
> ...             pass
> ...     f = getattr(toto, "titi")
> ...     print str(f)
> ...
>>>> toto()
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
>  File "<stdin>", line 4, in toto
> AttributeError: 'function' object has no attribute 'titi'
>>>>
>
> I thought that since functions are objects, that I could obtain it's
> nested functions.

Note that the nested function is created anew each time you call
toto(), so there's no reason for it to be stored anywhere.  What is
stored is the internal compiled code object used to create the inner
function, but it's not easy to get to it, nor is it all that useful to
try.  If you really need this, you can explicitly store the inner
function in the outer one's dict:

def outer():
    if not hasattr(outer, 'inner'):
        def inner():
            pass
        outer.inner = inner
    f = outer.inner    # same as getattr(outer, 'inner')
    print f            # same as print str(f)

>>> outer()
<function inner at 0xb7cfc294>
>>> outer.inner
<function inner at 0xb7cfc294>

> def __test(self, action, *args):
>        def request(params):
>            pass
>                def submit(params, values):
>            pass
>                def update(params, values):
>            pass
>                def delete(params):
>            pass
>            result = getattr(__test, action)(*args)
>            return resultToXml(result)
>
> where "action" is a string containing either "request", "submit",
> "update", or "delete".

Use locals()[action](*args).



More information about the Python-list mailing list