I have a python function
def read_info():
f = open("./info.txt", "r")
print(f.read())
I want to list all the variables used inside the function, e.g. here f.
now i try
$ python
>> from read_info import read_info
>> dir(read_info)
>>> dir(read_info)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
I tried dir(read_info) but it does not show f. (As we can see in the above output of dir(read_info) we dont see the variable f)
>Solution :
From inside the function, you can use locals() to get a dict of local variables and their values.
From outside the function, use my_func.__code__.co_varnames to get the names of local variables and parameters:
>>> def f(x):
... y = 42
...
>>> f.__code__.co_varnames
('x', 'y')