I have imported another file and how can I list those names in order as they appear. I am trying as below
functions_list = [o for o in getmembers(unit7_conversion_methods) if isfunction(o[1])]
names_list = [o[0] for o in functions_list]
-
What is your end-goal/use-case that you are trying to accomplish?Ming– Ming2015年02月02日 04:54:30 +00:00Commented Feb 2, 2015 at 4:54
-
I want to apply timeit on each moduleRock Star– Rock Star2015年02月02日 05:17:19 +00:00Commented Feb 2, 2015 at 5:17
-
@RockStar, you can apply timeit without any knowledge about the order in which a module defined its function, or (as you very differently indicated in a comment) the order in which a module imported other modules.Alex Martelli– Alex Martelli2015年02月02日 14:56:31 +00:00Commented Feb 2, 2015 at 14:56
1 Answer 1
Looks like you've done a from inspect import * but aren't using inspect optimally (though your code should work if my guess about the import is correct).
namelist = [name
for name, _ in getmembers(unit7_conversion_methods, isfunction)]
would be equivalent but faster. However, you do say "in order as they appear" (presumably the textual order in which they appear in the module), and that doesn't happen -- as https://docs.python.org/2/library/inspect.html#inspect.getmembers says, the members are returned sorted by name.
But wait -- not all is lost! A function object has a func_code attribute, a code object which in turns has a co_firstlineno attribute, the first line number of the function in the module defining it.
So, you can sort by that -- and get the function names in the order they appear in the module, as you seem to require.
nflist = getmembers(unit7_conversion_methods, isfunction)
def firstline(nf):
return nf[1].func_code.co_firstlineno
nflist.sort(key=firstline)
nameslist = [n for n, _ in nflist]
2 Comments
dis), a much harder problem (indeed Turing-complete, thus provably insoluble in the general case). In your shoes I'd be customizing __import__ instead, a slightly more invasive and still extremely advanced technique -- and meat for at least another question at least, with much clearer subject and text:-)