tags:

views:

98

answers:

2

for code:

def a(x):
    if x=='s':
        __import__('os')# i think __import__==import
        print os.path
a('s')

why,thanks


my Questions is from next code: and it doesn't use like 'a=__import__('os')',it only use '__import__('some')',why

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 it do this
    return sys.modules[name]
+10  A: 

__import__ returns a module. It doesn't actually add anything to the current namespace.

You probably want to just use import os:

def a(x):
    if x=='s':
        import os
        print os.path
a('s')

Alternatively, if you want to import the module as a string, you can explicitly assign it:

def a(x):
    if x=='s':
        os = __import__('os')
        print os.path
a('s')
HS
hi @statictype.org,I have updated the examples, please help me to have a look
zjm1126
+3  A: 

@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 what print os.path will 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'] or print os.getcwd()...?

Edit: to answer the OP's follow-on question:

__import__(name)#why it do this
return sys.modules[name]

__import__ does install what's importing in sys.modules; this is better than

return __import__(name)

if name contains one or more .s (dots): in that case, __import__ returns the top-level module, but sys.modules has the real thing. For example:

return __import__('foo.bar')

is equivalent to

__import__('foo.bar')
return sys.modules['foo']

not as one might think to

__import__('foo.bar')
return sys.modules['foo.bar']
Alex Martelli
hi alex,I have updated the examples, please help me to have a look
zjm1126
so ,'__import__' must be the different name ,because '__import__' Can not distinguish 'a.txt' , 'a.py' or 'a.rar',yes?,thanks
zjm1126
`__import__` imports a Python module, so a `.py` (or a `.pyd` [[on Win; `.so` on Linux]], or a `.pyc` directly, if existing and updated), **never** a `.txt` or `.rar`.
Alex Martelli