How to find full module path of a class to import in other file

Posted by Pooya on Stack Overflow See other posts from Stack Overflow or by Pooya
Published on 2012-07-01T09:09:00Z Indexed on 2012/07/01 9:15 UTC
Read the original article Hit count: 248

Filed under:
|

I have method that returns module path of given class name

def findModulePath(path, className):
    attributes = []
    for root, dirs, files in os.walk(path):
        for source in (s for s in files if s.endswith(".py")):
            name = os.path.splitext(os.path.basename(source))[0]
            full_name = os.path.splitext(source)[0].replace(os.path.sep, '.')
            m = imp.load_module(full_name, *imp.find_module(name, [root]))
            try:
                attr = getattr(m, className)
                attributes.append(attr)

            except:
                pass
    if len(attributes) <= 0:
        raise Exception, "Class %s not found" % className

    for element in attributes:
        print "%s.%s" % (element.__module__, className)

but it does not return the full path of the module, For example I have a python file named "objectmodel" in objects package,and it contains a Model class, So I call findModulePath(MyProjectPath,"Model"). it prints objectmodel.Model but I need objects.objectmodel.Model

© Stack Overflow or respective owner

Related posts about python

Related posts about path