Neat Trick for Loading Modules with unknown Name

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Randall Smith

    Neat Trick for Loading Modules with unknown Name

    I've found an easy and clean way to load and use modules that are loaded
    after a program has started when the name of the module can not be
    pre-determined.

    modname = 'usermodname'
    # load the module
    exec('import ' + modname)
    # alias the module
    usersmod = eval(modname)

    Not you can use the module like this: usermod.def
    Where def is some function, class, etc. defined in the module.

    Very simple. I stumbled on this for a while and even read some long,
    complex solutions involving using __import__, etc. Just thought I'd share.

    Randall
  • Ixokai

    #2
    Re: Neat Trick for Loading Modules with unknown Name

    *blink*

    Long, complex?
    [color=blue][color=green][color=darkred]
    >>> modname = 'email'
    >>> mod = __import__(emai l)
    >>> mod[/color][/color][/color]
    <module 'email' from 'Z:\python23\li b\email\__init_ _.py'>

    ?

    --Stephen
    "Randall Smith" <randall@tnr.cc > wrote in message
    news:I6t7c.8065 5$u_5.47815@fe2 .texas.rr.com.. .[color=blue]
    > I've found an easy and clean way to load and use modules that are loaded
    > after a program has started when the name of the module can not be
    > pre-determined.
    >
    > modname = 'usermodname'
    > # load the module
    > exec('import ' + modname)
    > # alias the module
    > usersmod = eval(modname)
    >
    > Not you can use the module like this: usermod.def
    > Where def is some function, class, etc. defined in the module.
    >
    > Very simple. I stumbled on this for a while and even read some long,
    > complex solutions involving using __import__, etc. Just thought I'd[/color]
    share.[color=blue]
    >
    > Randall[/color]


    Comment

    Working...