To describe my questions concisely, please have a look at examples below:
Module
oshave a functiongetcwd()which returns current working directory. But there are no details aboutos.getcwd()in/usr/lib/python2.7/os.pyfile. Where is the implementation of the function?os.pathis also a module in python , but in/usr/lib/python2.7directory, there is no file namedos.path. So when youimport os.pathin your python script, which file is imported?
Thank all your helps...
4 Answers 4
1 . The getcwd() functions is implemented in C look here.
2 . os.path is defined in the module os by dynamically detecting the os type and importing the correspondent library and set in it using : sys.modules['os.path'] = path
Comments
Modules do not have to be python scripts. Using the C-API you can write modules in C or C++. You can compile them as dynamic libraries, so that the interpreter can load them dynamically, or you can recompile the interpreter and link the modules into it.
1 Comment
.class files. I guess IronPython does something similar.If you're on a POSIX system (Linux, Mac OS X), these lines in os.py bring in those bits:
from posix import *
import posixpath as path
And on Windows:
from nt import *
import ntpath as path
(Plus a couple more options for less popular systems)
Note that using from x import * is usually frowned on. This is kind of a special case.
Comments
The interactive python shell can be used to check where a module is loaded from, and to see if a method is built-in or python:
>>> import os
>>> os
<module 'os' from '/usr/lib/python2.6/os.pyc'>
>>> os.path
<module 'posixpath' from '/usr/lib/python2.6/posixpath.pyc'>
>>> os.getcwd
<built-in function getcwd>
>>> os.path.join
<function join at 0x87d1b1c>
>>>
os.path is loaded from posixpath.pyc,
os.getcwd is built-in, os.path.join is a python method.