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.
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.
Since a list can contain any Python variables, it can even contain other lists.
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.
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.
print [item for item in dir(adfix) if not item.startswith("__")]
Is usually the recipe for doing this, but it begs the question.
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