开发者

python loop through imports & check for variable

开发者 https://www.devze.com 2023-03-04 20:08 出处:网络
开发者_Go百科I\'ve successfully imported a bunch of modules in a folder using from assets import *

开发者_Go百科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'


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__
0

精彩评论

暂无评论...
验证码 换一张
取 消