Confused about python modules and functions in it
To describe my questions concisely, please have a look at examples below:
Module
os
have a functiongetcwd开发者_开发技巧()
which returns current working directory. But there are no details aboutos.getcwd()
in/usr/lib/python2.7/os.py
file. Where is the implementation of the function?os.path
is also a module in python , but in/usr/lib/python2.7
directory, there is no file namedos.path
. So when youimport os.path
in your python script, which file is imported?
Thank all your helps...
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
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.
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.
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.
精彩评论