special method in module

Fredrik Lundh fredrik at pythonware.com
Wed Nov 16 13:03:55 CET 2005


Jan Procházka wrote:

> can have modules special methods?

no, but you can replace the module object with something that can have
special methods:

$ more module.py
import sys

class Module:
    def __getitem__(self, value):
        return value

sys.modules[__name__] = Module()

$ python
>>> import module
>>> module[10]
10

as with any other introspection hack, you should only use this if you have
very good reasons.

(saving some typing in import statements is not a good reason; creating a
module that's a transparent proxy to some external system might be.  but
in such cases, you should stick to attribute hooks/descriptors, and make
sure that code that uses your proxy looks like code that uses an ordinary
module.  Python always works better if you use it to write Python code...)

</F> 






More information about the Python-list mailing list