kimes wrote:

> But the only os.path doesn't have their own file..
> ye I know is has actually depending on os like in my case posixpath..
> What I'd love to know is..
> when I call import os.path..
> how happened under the hood?

At first os - module, or package, it doesn't matter here - is imported.
In its code, it detects the proper path module and imports it. The module
cache is then manipulated and the name 'path' is bound to posixpath, too:

sys.modules["os.path"] = posixpath
path = posixpath

The second stage of the import then reduces to just a lookup in the cache
instead of a search for the inexistent .../os/ in the filesystem.

Both the module attribute and the cache update are necessary when you want
to pull off similar tricks. Here is an example of the odd behaviour that
results from them being out of sync:

>>> import os
>>> os.path = 42
>>> from os import path # binds the path attribute of module os
>>> path
>>> import os.path
>>> os.path
>>> old_globals = set(globals().keys())
>>> from os.path import * # looks up os.path module as found in the cache
>>> set(globals().keys()) - old_globals
set(['pardir', 'sameopenfile', 'exists', 'sep', 'splitext', 'basename',
'walk', 'expandvars', 'old_globals', 'expanduser', 'getmtime', 'defpath',
'dirname', 'isfile', 'supports_unicode_filenames', 'pathsep', 'getsize',
'samestat', 'split', 'devnull', 'islink', 'curdir', 'samefile', 'realpath',
'commonprefix', 'abspath', 'normcase', 'getatime', 'isdir', 'join',
'altsep', 'getctime', 'isabs', 'normpath', 'ismount', 'splitdrive',



Reply via email to