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
?
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.
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.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With