Possible to import a module whose name is contained in a variable?

Discussion in 'Python' started by Steven Reddie, Mar 7, 2005.

  1. Hi,

    I want to do something like the following, which doesn't work:

    modulename = 'module'
    import modulename

    The error is that there is no module named 'modulename'. Is there a
    way to get that variable expanded?

    Regards,

    Steven
     
    Steven Reddie, Mar 7, 2005
    #1
    1. Advertising

  2. Re: Possible to import a module whose name is contained in avariable?

    On 6 Mar 2005 21:34:08 -0800, Steven Reddie <> wrote:
    > Hi,
    >
    > I want to do something like the following, which doesn't work:
    >
    > modulename = 'module'
    > import modulename
    >
    > The error is that there is no module named 'modulename'. Is there a
    > way to get that variable expanded?
    >


    modulename = 'module'
    module = __import__(modulename)


    Hye-Shik
     
    Hye-Shik Chang, Mar 7, 2005
    #2
    1. Advertising

  3. Claudio Grondi wrote:
    > "Steven Reddie" <> schrieb im Newsbeitrag
    > news:...
    >>
    >>I want to do something like the following, which doesn't work:
    >>
    >> modulename = 'module'
    >> import modulename
    >>
    >>The error is that there is no module named 'modulename'. Is there a
    >>way to get that variable expanded?

    >
    > modulename = 'module'
    > cmd = 'import '+modulename
    > exec(cmd)
    >
    > Check also the thread:
    > How do I import everything in a subdir?
    > in THIS newsgroup.


    And note that it tells you to use __import__, not exec. =)

    STeVe
     
    Steven Bethard, Mar 7, 2005
    #3
  4. "Steven Reddie" <> schrieb im Newsbeitrag
    news:...
    > Hi,
    >
    > I want to do something like the following, which doesn't work:
    >
    > modulename = 'module'
    > import modulename
    >
    > The error is that there is no module named 'modulename'. Is there a
    > way to get that variable expanded?
    >
    > Regards,
    >
    > Steven


    modulename = 'module'
    cmd = 'import '+modulename
    exec(cmd)

    Check also the thread:
    How do I import everything in a subdir?
    in THIS newsgroup.

    Claudio
    P.S.
    > MODULES = [ 'module1', 'module2' ]
    >
    > def libinfo():
    > for m in MODULES:
    > __import__('libinfo.'+m)
    > m.libinfo()
    > CFLAGS+=m.CFLAGS


    indentation error?
     
    Claudio Grondi, Mar 7, 2005
    #4
  5. Re: Possible to import a module whose name is contained in avariable?

    On Monday 07 March 2005 11:52, Claudio Grondi wrote:
    > I try to avoid using any of the
    > __xxxx__() functions if possible
    > (considering this a good
    > programming style).


    This is never good style, at least in the case of exec. exec is evil.

    What works (beware that the below code is nevertheless untested and might
    contain little warts) and is the "usual" and clean way to go:

    ### libinfo/__init__.py

    # Empty.

    ### libinfo/Module1.py

    def libinfo():
    return "I am module1."

    CFLAGS = ["-DMODULE1"]

    ### libinfo/Module2.py

    def libinfo():
    return "I am module2."

    CFLAGS = ["-DMODULE2"]

    ### Importer.py

    modules = {}
    CFLAGS = []

    def load_modules(to_load=["module1","module2"]):
    global modules, CFLAGS

    for mod in to_load:
    try:
    modules[mod] = getattr(__import__("libinfo.%s" % mod),mod)
    except ImportError:
    print "Could not load %s." % mod
    continue
    print "Module: %s (%r)." % (mod,modules[mod])
    print "Modules libinfo: %r." % modules[mod].libinfo()
    CFLAGS += modules[mod].CFLAGS

    print "Total CFLAGS: %s." % CFLAGS

    if __name__ == "__main__":
    load_modules()
    print "Module container: %s." % modules

    ### End Importer.py

    HTH!

    --
    --- Heiko.

    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.4.0 (GNU/Linux)

    iD8DBQBCLCgXf0bpgh6uVAMRAhCUAJ95kbz6bMWAV7j42hxrh1nYEvj4lgCfZoD3
    p0E0cdgp4io2eyGfL6u2lho=
    =wYq0
    -----END PGP SIGNATURE-----
     
    Heiko Wundram, Mar 7, 2005
    #5
  6. Claudio Grondi wrote:
    > STeVe,
    >
    > may I ask you for more details on this?
    > Any disadvantages while using exec()
    > in this context?
    >
    > I try to avoid using any of the
    > __xxxx__() functions if possible
    > (considering this a good
    > programming style).


    Avoiding exec (which is a statement, not a function) is much more
    important. Since it executes arbitrary code, you can get unpredictable
    results from it.

    >>> z = "sys; print 'w00t'"
    >>> exec "import " + z

    w00t

    Consider the case where z = "shutil; shutil.rmtree('/')"
    --
    Michael Hoffman
     
    Michael Hoffman, Mar 7, 2005
    #6
  7. STeVe,

    may I ask you for more details on this?
    Any disadvantages while using exec()
    in this context?

    I try to avoid using any of the
    __xxxx__() functions if possible
    (considering this a good
    programming style).

    Claudio

    "Steven Bethard" <> schrieb im Newsbeitrag
    news:...
    > Claudio Grondi wrote:
    > > "Steven Reddie" <> schrieb im Newsbeitrag
    > > news:...
    > >>
    > >>I want to do something like the following, which doesn't work:
    > >>
    > >> modulename = 'module'
    > >> import modulename
    > >>
    > >>The error is that there is no module named 'modulename'. Is there a
    > >>way to get that variable expanded?

    > >
    > > modulename = 'module'
    > > cmd = 'import '+modulename
    > > exec(cmd)
    > >
    > > Check also the thread:
    > > How do I import everything in a subdir?
    > > in THIS newsgroup.

    >
    > And note that it tells you to use __import__, not exec. =)
    >
    > STeVe
     
    Claudio Grondi, Mar 7, 2005
    #7
  8. Steven Reddie

    Ed Leafe Guest

    Re: Possible to import a module whose name is contained in avariable?

    On Mar 7, 2005, at 5:23 AM, Michael Hoffman wrote:

    > Avoiding exec (which is a statement, not a function) is much more
    > important. Since it executes arbitrary code, you can get unpredictable
    > results from it.


    Is there any way to use __import__ to replace the following:

    exec("from %s import *" % modulename)

    ___/
    /
    __/
    /
    ____/
    Ed Leafe
    http://leafe.com/
    http://dabodev.com/
    Come to PyCon!!!! http://www.python.org/pycon/2005/
     
    Ed Leafe, Mar 7, 2005
    #8
  9. Steven Reddie

    Gerrit Holl Guest

    Re: Possible to import a module whose name is contained in avariable?

    Ed Leafe wrote:
    > On Mar 7, 2005, at 5:23 AM, Michael Hoffman wrote:
    > >Avoiding exec (which is a statement, not a function) is much more
    > >important. Since it executes arbitrary code, you can get unpredictable
    > >results from it.

    >
    > Is there any way to use __import__ to replace the following:
    >
    > exec("from %s import *" % modulename)


    No.

    Gerrit.

    --
    Weather in Twenthe, Netherlands 07/03 13:25:
    4.0°C Few clouds mostly cloudy wind 5.4 m/s NW (57 m above NAP)
    --
    In the councils of government, we must guard against the acquisition of
    unwarranted influence, whether sought or unsought, by the
    military-industrial complex. The potential for the disastrous rise of
    misplaced power exists and will persist.
    -Dwight David Eisenhower, January 17, 1961
     
    Gerrit Holl, Mar 7, 2005
    #9
  10. Steven Reddie

    Peter Hansen Guest

    Gerrit Holl wrote:
    > Ed Leafe wrote:
    >
    >>On Mar 7, 2005, at 5:23 AM, Michael Hoffman wrote:
    >>
    >>>Avoiding exec (which is a statement, not a function) is much more
    >>>important. Since it executes arbitrary code, you can get unpredictable
    >>>results from it.

    >>
    >> Is there any way to use __import__ to replace the following:
    >>
    >>exec("from %s import *" % modulename)


    > No.


    Between the following two recipes, it seems unlikely that a simple
    "No" is really correct:

    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/223972

    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307772

    A variation on some of the code therein should certainly be
    able to do the equivalent of "from xx import *". (The addition
    of support for __all__ is at least required for full emulation.)

    -Peter
     
    Peter Hansen, Mar 7, 2005
    #10
  11. Re: Possible to import a module whose name is contained in a variable?

    Ed Leafe wrote:
    >
    > Is there any way to use __import__ to replace the following:
    >
    > exec("from %s import *" % modulename)


    I shouldn't do this but:

    module = __import__(modulename)
    try:
    for key in module.__all__:
    globals()[key] = module[key]
    except AttributeError:
    globals().update(module.__dict__)

    But really, you shouldn't be using from x import * as it
    has unpredictable results as well.

    http://www.python.org/doc/faq/progr...e-best-practices-for-using-import-in-a-module
    --
    Michael Hoffman
     
    Michael Hoffman, Mar 7, 2005
    #11
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page