FAQ

Henry Baumgartl wrote:

Hello all,

Having recently embarked on my journey into Python land, I would like to
know if there is an elegant solution to the following problem:

I would like to be able to compound variables that will then form the name
of the particular module to be loaded into the active script.
__import__

cheers,

f

Search Discussions

  • Henry Baumgartl at Mar 6, 2002 at 4:04 pm
    Hello all,

    Having recently embarked on my journey into Python land, I would like to
    know if there is an elegant solution to the following problem:

    I would like to be able to compound variables that will then form the name
    of the particular module to be loaded into the active script.

    Long lists of -if- and -elif- statements don't really do the trick, as one
    still has to hardcode all possible options and defeating the dynamic nature
    of the application.

    A solution I came up with was to write a new module every time the process
    starts, and loading this to get to the dynamically selected sub-modules.
    Unfortunately, as the name of the 'new' module needs to be hardcoded for
    this scheme to work, only one user can safely use the application at any one
    time, which is not good enough.

    Any suggestions to resolve my dilemma will be greatly appreciated.

    Best Regards,
    Henry Baumgartl
  • Skip Montanaro at Mar 6, 2002 at 4:18 pm
    Henry> I would like to be able to compound variables that will then form
    Henry> the name of the particular module to be loaded into the active
    Henry> script.

    Take a look at the docs for the exec statement and the __import__ builtin
    function. Briefly:

    mname = raw_input("enter a module name: ")
    exec "import %s"%mname in globals()

    or

    mname = raw_input("enter a module name: ")
    m = __import__(mname, globals())
    print m.__doc__

    --
    Skip Montanaro (skip at pobox.com - http://www.mojam.com/)

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouppython-list @
categoriespython
postedMar 6, '02 at 3:54p
activeMar 6, '02 at 4:18p
posts3
users3
websitepython.org

People

Translate

site design / logo © 2022 Grokbase