'How to get list of all variables inside a function?
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 1:[1]
You can do it inside the function with locals(). In your case
locals()["f"]
will get you what you need. Note that except in very particular cases, this is not suggested and likely to lead to code smells.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
