For the code:
def a(x):
if x=='s':
__import__('os') #I think __import__ == import
print os.path
Why doesn’t print a('os') print os.path?
My next question is: Why does the following code use __import__('some') instead of something like, a = __import__('os') ?
def import_module(name, package=None):
if name.startswith('.'):
if not package:
raise TypeError("relative imports require the 'package' argument")
level = 0
for character in name:
if character != '.':
break
level += 1
name = _resolve_name(name[level:], package, level)
__import__(name) #Why does it do this
return sys.modules[name] #Instead of `return __import__(name)`
@statictype.org’s answer is correct (
__import__does not bind any name in local namespace), but why ever do you want to print<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.pyc'>or something equally weird depending on your platform?! That’s whatprint os.pathwill do once you’ve fixed your bug — what are you trying to accomplish by that?!You sure you don’t want something completely different such as
print os.environ['PATH']orprint os.getcwd()…?Edit: to answer the OP’s follow-on question:
__import__does install what’s importing insys.modules; this is better thanif
namecontains one or more.s (dots): in that case,__import__returns the top-level module, butsys.moduleshas the real thing. For example:is equivalent to
not as one might think to