Ngoc N. Tran
Ngoc N. Tran

Reputation: 1068

Extended import with a function in Python

It's my CS homework - Exercise 12-6 in Wesley Chun's "Core Python Programming." The objective is to imitate extended import with a function like when import ... as was not implemented. These are my attempts, both of which yield errors:

def importAs(name):
    eval('import '+name)
    ret = eval(name)
    eval('del '+name)
    return ret

foo = importAs('os')

This yields a SyntaxError: invalid syntax at import os in File "<string>", line 1, while:

def importAs(name):
    import name
    ret = name
    del name
    return ret

foo = importAs(os)

yields a NameError: name 'os' is not defined at foo = importAs(os).

Can anybody explains the reason and a solution please?

EDIT: please keep it 2.x only :)

Upvotes: 0

Views: 79

Answers (1)

m.wasowski
m.wasowski

Reputation: 6387

eval can evaluate only expression. And import is a statement, so it won't work.

You should use importlib module for your task.

Also take a look at eval to import a module

Upvotes: 1

Related Questions