You are here: Home > Dive Into Python > An Object-Oriented Framework > More on modules | << >> | ||||
Dive Into PythonPython for experienced programmers |
Modules, like everything else in Python, are objects. Once imported, you can always get a reference to a module through the global dictionary sys.modules.
>>> import sys >>> print '\n'.join(sys.modules.keys()) win32api os.path os exceptions __main__ ntpath nt sys __builtin__ site signal UserDict stat
>>> import fileinfo >>> print '\n'.join(sys.modules.keys()) win32api os.path os fileinfo exceptions __main__ ntpath nt sys __builtin__ site signal UserDict stat >>> fileinfo <module 'fileinfo' from 'fileinfo.pyc'> >>> sys.modules["fileinfo"] <module 'fileinfo' from 'fileinfo.pyc'>
>>> from fileinfo import MP3FileInfo >>> MP3FileInfo.__module__ 'fileinfo' >>> sys.modules[MP3FileInfo.__module__] <module 'fileinfo' from 'fileinfo.pyc'>
Every Python class has a built-in class attribute __module__, which is the name of the module in which the class is defined. | |
Combining this with the sys.modules dictionary, you can get a reference to the module in which a class is defined. |
def getFileInfoClass(filename, module=sys.modules[FileInfo.__module__]): "get file info class from filename extension" subclass = "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:] return hasattr(module, subclass) and getattr(module, subclass) or FileInfo
This is a function with two arguments; filename is required, but module is optional and defaults to the module which contains the FileInfo class. This looks inefficient, because you might expect Python to evaluate the sys.modules expression every time the function is called. In fact, Python only evaluates default expressions once, the first time the module is imported. As we’ll see later, we never call this function with a module argument, so module serves as a function-level constant. | |
We’ll plough through this line later, after we dive into the os module. For now, take it on faith that subclass ends up as the name of a class, like MP3FileInfo. | |
You already know about getattr, which gets a reference to an object by name. hasattr is a complementary function that checks whether an object has a particular attribute; in this case, whether a module has a particular class (although it works for any object and any attribute, just like getattr). In English, this line of code says “if this module has the class named by subclass then return it, otherwise return the base class FileInfo”. |
<< for loops |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | |
The os module >> |