0

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] 
3
  • What is your end-goal/use-case that you are trying to accomplish? Commented Feb 2, 2015 at 4:54
  • I want to apply timeit on each module Commented 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. Commented Feb 2, 2015 at 14:56

1 Answer 1

4

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] 
Sign up to request clarification or add additional context in comments.

2 Comments

If the file has modules in order number_string1, number_string2, number_string3, num_string4. I am getting 4th module as 1st in the list buti want all in same order as they appear
@RockStar, unfortunately, no trace is left for introspection of the order in which one module imported others -- you'd need to go deeper and analyze the module's Python source (or bytecode via module 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:-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.