Get named module's file location

Chris Angelico rosuav at gmail.com
Fri Dec 23 16:21:56 EST 2011


I'm guessing you meant for this to be on-list, and am hoping you don't
mind that I'm replying on-list.

On Sat, Dec 24, 2011 at 8:16 AM, Gnarlodious <gnarlodious at gmail.com> wrote:
> Chris Angelico wrote:
>> [(m, os.path.getmtime(m)) for m in (imp.find_module(module)[1] for
>> module in modules)]
>>
>> Yeah, a little hard to read. Tell me, does this formulation execute
>> imp.find_module(module) once or twice for each modname?

What this does is save a temporary list, more or less. (It's actually
a generator expression, not a list comprehension, but that's
immaterial.)

temporary = [imp.find_module(module)[1] for module in modules]
[(m, os.path.getmtime(m)) for m in temporary]

It iterates over modules, calling find_module for each, and saving the
results to a new list. Then separately iterates over the new list,
pairing each with the getmtime.

Since I used parentheses instead of square brackets in the original
expression, Python won't actually build the full list. Other than
that, it's equivalent to the two-statement version, and you can try
those two in IDLE to see what they do.

ChrisA



More information about the Python-list mailing list