Importing module with name given as a variable

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Sean Davis

    #1

    Importing module with name given as a variable

    What is the "best practice" for importing an arbitrary module given
    that the name is stored in a variable? The context is a simple web
    application with URL dispatching to a module and function. I know of
    __import__(), the imp module, and exec. For each of these, is there a
    way to make them work "just like" the normal import call?

    Thanks,
    Sean
  • Wojtek Walczak

    #2
    Re: Importing module with name given as a variable

    On Sat, 30 Aug 2008 11:02:03 -0700 (PDT), Sean Davis wrote:
    What is the "best practice" for importing an arbitrary module given
    that the name is stored in a variable? The context is a simple web
    application with URL dispatching to a module and function. I know of
    __import__(), the imp module, and exec. For each of these, is there a
    way to make them work "just like" the normal import call?
    It all depends on your needs. If you have to deal with user
    input to get the name of the module, better use __import__
    than exec. __import__ works just like the normal import call:

    import sys

    is equal to:

    sys = __import__('sys ')

    If you need, let's say, to search for a module that lies
    outside sys.module paths, then use imp's functions.

    HTH.

    --
    Regards,
    Wojtek Walczak,
    http://tosh.pl/gminick/

    Comment

    Working...