Get ordered list of attributes of a Python module -


i need retrieve list of attributes of python module.

the catch, , question differs e.g. this one, want list ordered according order appear in module.

as example, consider module

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

i want list ['b1', 'a0', 'a1'].

what i've tried:

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

is there way of getting list without having parse file?

yes, have parse file. don't have write own parser though, can use ast libary.

using example file

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

you parse attributes way.

import ast  members = [] open('file.py', 'r') f:     src = f.read()  tree = ast.parse(src)  child in tree.body:     if isinstance(child, ast.assign):         target in child.targets:             members.append(target.id)  print members # ['b1', 'a0', 'a1'] 

this small script looks @ top-level attributes. it's ignoring things imports , class , function definitions. may have more complex logic depending on how information want extract parsed file.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -