Reputation: 1068
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
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