Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a list of variables in specific Python module?

Tags:

python

Let's assume I have the following file structure:

data.py

foo = [] bar = [] abc = "def" 

core.py

import data # do something here # # a = ... print a # ['foo', 'bar', 'abc'] 

I need to get all the variables defined in data.py file. How can I achieve that? I could use dir(), but it returns all the attributes of the module including __name__ and so on.

like image 930
aemdy Avatar asked Mar 18 '12 16:03

aemdy


People also ask

How do you access all functions from a specific module in Python?

We can list down all the functions present in a Python module by simply using the dir() method in the Python shell or in the command prompt shell.

Can you have a list of variables in Python?

Since a list can contain any Python variables, it can even contain other lists.

How do I list all variables in Python?

dir() is a built-in function to store all the variables inside a program along with the built-in variable functions and methods. It creates a list of all declared and built-in variables.

Can Python modules have variables?

Each Module/file has its own global variable Every command in this Python file can access, read, and modify the value of the variable, that is, it becomes a global variable. You can also explicitly make a variable defined within the functions globally by declaring it global.


1 Answers

print [item for item in dir(adfix) if not item.startswith("__")] 

Is usually the recipe for doing this, but it begs the question.

Why?

like image 200
Jakob Bowyer Avatar answered Sep 20 '22 16:09

Jakob Bowyer