[Python-ideas] Add inspect.getenclosed to return/yield source code for nested classes and functions

Un Do jsbfox at gmail.com
Wed Sep 16 18:36:58 CEST 2015


I propose adding a function into inspect module that will retrieve
definitions of classes and functions (standard and lambdas) located
inside another function/method.

In my opinion this would a small but nice and useful addition to the
standard library. It can be implemented using a couple of undocumented
function from that module (findsource and getblock) without any
performance drawbacks.

Example:

    In [9]: print(getsource(function))
    def function():
        class inner_class():
            def __init__(self):
                return

        # Some code
        # Some more code
        # Even more code

        l = lambda x: 42

        # Ugh code again

        def inner_function(with_argument):
            pass


    In [10]: for c in function.__code__.co_consts:
       ....:     if not iscode(c):
       ....:         continue
       ....:     name, starts_line = c.co_name, c.co_firstlineno
       ....:     if not name.startswith('<') or name == '<lambda>':
       ....:         lines, _ = findsource(c)
       ....:         source = ''.join(getblock(lines[starts_line-1:]))
       ....:         print(dedent(source), end='-' * 30 + '\n')
       ....:
    class inner_class():
        def __init__(self):
            return
    ------------------------------
    l = lambda x: 42
    ------------------------------
    def inner_function(with_argument):
        pass
    ------------------------------


What do you think?


More information about the Python-ideas mailing list