Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - list all inner functions of a function?

In python you can do fname.__code__.co_names to retrieve a list of functions and global things that a function references. If I do fname.__code__.co_varnames, this includes inner functions, I believe.

Is there a way to essentially do inner.__code__.co_names ? by starting with a string that looks like 'inner', as is returned by co_varnames?

like image 236
user3475234 Avatar asked Oct 28 '14 13:10

user3475234


People also ask

Can you define functions inside functions Python?

If you define a function inside another function, then you're creating an inner function, also known as a nested function. In Python, inner functions have direct access to the variables and names that you define in the enclosing function.

How do you access a function within a function Python?

A function which is defined inside another function is known as inner function or nested functio n. Nested functions are able to access variables of the enclosing scope.

How do I call an inner function from another function in Python?

You can do it using Python Closures i.e. a function instance enclosed within an enclosing scope. There is one thing you should take care of, you must have to call the outer function to call the inner function because it's scope is inside that function.


1 Answers

In Python 3.4+ you can get the names using dis.get_instructions. To support nested functions as well you need to recursively loop over each code object you encounter:

import dis
import types

def get_names(f):
    ins = dis.get_instructions(f)
    for x in ins:
        try:
            if x.opcode == 100 and '<locals>' in next(ins).argval\
                                              and next(ins).opcode == 132:
                yield next(ins).argrepr
                yield from get_names(x.argval)
        except Exception:
            pass

Demo:

def func():
    x = 1
    y = 2
    print ('foo')
    class A:
        def method(self):
            pass
    def f1():
        z = 3
        print ('bar')
        def f2():
            a = 4
            def f3():
                b = [1, 2, 3]
    def f4():
        pass

print(list(get_names(func)))

Outputs:

['f1', 'f2', 'f3', 'f4']
like image 194
Ashwini Chaudhary Avatar answered Oct 12 '22 11:10

Ashwini Chaudhary