user505160
user505160

Reputation: 1216

Loading modules at runtime from functions

I would like to load modules at runtime.

If I do it like this it works:

a = __import__('datetime',globals(),locals(),[],-1)

for e in a.__dict__:
    if not e.startswith("__"):
        globals()[e] = a.__dict__[e]

But if I try to do this it doesn't work:

def module_loader(modname,g,l):
    a = __import__(modname,g(),l(),[],-1)

    for e in a.__dict__:
        if not e.startswith("__"):
            g()[e] = a.__dict__[e]


module_loader('datetime',globals,locals)

Any help?

Upvotes: 0

Views: 203

Answers (2)

rajasaur
rajasaur

Reputation: 5470

Your snippet above works for me if I call it as

module_loader('datetime', globals, locals)

Upvotes: 1

Pushpak Dagade
Pushpak Dagade

Reputation: 6460

def module_loader(modname,g,l):
    a = __import__(modname,g(),l(),[],-1)

    for e in a.__dict__:
        if not e.startswith("__"):
            g()[e] = a.__dict__[e]

module_loader('datetime', globals, locals)

Upvotes: 0

Related Questions