Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Version of `imp.find_module` that works on dotted modules

Tags:

python

import

Is there an existing implementation of imp.find_module that works on dotted module names? It doesn't need to be bulletproof, it's okay if it won't work for some cases. But the more cases it works for, the better.

And please, don't try to implement this function in an answer. I've already implemented my version of it, I'm asking if there's an existing implementation because if there is one, it's probably much more tested than my version.

like image 680
Ram Rachum Avatar asked Apr 26 '11 19:04

Ram Rachum


2 Answers

importlib might be what you're after. In particular the function import_module. The docs say:

importlib.import_module(name, package=None)

Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod)

like image 115
Carlos Valiente Avatar answered Sep 19 '22 20:09

Carlos Valiente


For others viewing this question and looking for a method, here's what I'm using.

import imp

def find_dotted_module(name, path=None):
    res = None
    for x in name.split('.'):
        res = imp.find_module(x, path)
        path = [module[1]]
    return res
like image 20
Michael Waterfall Avatar answered Sep 23 '22 20:09

Michael Waterfall