Chad
Chad

Reputation: 11

python loop through imports & check for variable

I've successfully imported a bunch of modules in a folder using

from assets import *

Now i want to loop through those imported modules and check for a specific variable or function. I tried to use dir() function to get a list of imported modules and look through them, but because i'm looping through an array of strings, instead of an array of modules technically, i can't lookup the module var.

for aModule in dir(assets):
    if word in aModule.alt:
        print "found it!"

if word in aModule.alt:

AttributeError: 'str' object has no attribute 'alt'

Upvotes: 1

Views: 3631

Answers (1)

Mu Mind
Mu Mind

Reputation: 11214

I think what you're doing could be done much more simply:

import assets
for aModule in vars(assets).values():
    if hasattr(aModule, 'alt') and word in aModule.alt:
        print "found it!"
        print aModule.__name__

Upvotes: 3

Related Questions