Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ordered list of attributes of a Python module

Tags:

python

I need to retrieve the list of attributes of a Python module.

The catch, and this is where this question differs e.g. from this one, is that I want the list ordered according to the order they appear in the module.

As an example, consider the module

# a_module.py
b1 = 1
a0 = 1
a1 = 2

I want the list ['b1', 'a0', 'a1'].

What I've tried:

>>> import a_module
>>> dir(a)
[..., 'a0', 'a1', 'b1']

>>> from inspect import getmembers
>>> [x[0] for x in getmembers(a_module)]
[..., 'a0', 'a1', 'b1']

Is there any way of getting the list without having to parse the file?

like image 307
Jorge Leitao Avatar asked Feb 06 '16 08:02

Jorge Leitao


People also ask

How do I print all attributes of a module?

After you import the os module, then we pass the os module into the dir() function. This outputs all of the attributes and functions of the os module. This prints out all of the attributes and functions of the os module. You can see there are functions such as listdir, mkdir, makedirs, etc.

Which function is used to get all attributes of a module?

dir() is a built-in function that also returns the list of all attributes and functions in a module.

How do you get attributes in Python?

Python getattr() function. Python getattr() function is used to get the value of an object's attribute and if no attribute of that object is found, default value is returned. Basically, returning the default value is the main reason why you may need to use Python getattr() function.

How do I get all the functions in a Python module?

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.


1 Answers

Yes, you will have to parse the file. You don't have to write your own parser though, you can use the ast libary.

Using your example file

# a_module.py
b1 = 1
a0 = 1
a1 = 2

You could parse the attributes this way.

import ast

members = []
with open('file.py', 'r') as f:
    src = f.read()

tree = ast.parse(src)

for child in tree.body:
    if isinstance(child, ast.Assign):
        for target in child.targets:
            members.append(target.id)

print members
# ['b1', 'a0', 'a1']

This small script only looks at top-level attributes. It's ignoring things like imports and class and function definitions. You may have more complex logic depending on how much information you want to extract from the parsed file.

like image 122
Brendan Abel Avatar answered Oct 12 '22 08:10

Brendan Abel