Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$ 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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading