简体   繁体   中英

Why doesn't my code print `os.path`

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)`

__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')

@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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM