find out whether a module exists (without importing it)

Discussion in 'Python' started by Gelonida N, Aug 6, 2012.

  1. Gelonida N

    Gelonida N Guest

    Is this possible.

    let's say I'd like to know whether I could import the module
    'mypackage.mymodule', meaning,
    whther this module is located somewhere in sys.path

    i tried to use

    imp.find_module(), but
    it didn't find any module name containing a '.'

    Am I doing anything wrong?

    Is there another existing implementation, that helps.

    I could do this manually, but this is something I'd just like to do if
    necessary.
     
    Gelonida N, Aug 6, 2012
    #1
    1. Advertisements

  2. Gelonida N

    Miki Tebeka Guest

    imp.find_module(), but
    The docs (http://docs.python.org/library/imp.html#imp.find_module) clearly say:

    "This function does not handle hierarchical module names (names containing dots). In order to find P.M, that is, submodule M of package P, use find_module() and load_module() to find and load package P, and then use find_module() with the path argument set to P.__path__. When P itself has a dotted name, apply this recipe recursively."

    See https://gist.github.com/3278829 for possible implementation.
     
    Miki Tebeka, Aug 6, 2012
    #2
    1. Advertisements

  3. Gelonida N

    Miki Tebeka Guest

    imp.find_module(), but
    The docs (http://docs.python.org/library/imp.html#imp.find_module) clearly say:

    "This function does not handle hierarchical module names (names containing dots). In order to find P.M, that is, submodule M of package P, use find_module() and load_module() to find and load package P, and then use find_module() with the path argument set to P.__path__. When P itself has a dotted name, apply this recipe recursively."

    See https://gist.github.com/3278829 for possible implementation.
     
    Miki Tebeka, Aug 6, 2012
    #3
  4. Gelonida N

    Gelonida N Guest

    Thanks,
    Well this explains.
    find_module() and load_module() to find and load package P, and then use
    find_module() with the path argument set to P.__path__. When P itself
    has a dotted name, apply this recipe recursively."

    Using imp and then iterating (as you suggested) is probably the fastest
    solution. This is what I will do.

    Thanks again.
     
    Gelonida N, Aug 6, 2012
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.