[Python-3000] Interest in PEP for callbacks on module import

Christian Heimes lists at cheimes.de
Sat Dec 8 22:32:32 CET 2007


Nick Coghlan wrote:
> With the new abstract base classes in Py3k, I can see it being 
> worthwhile to have a standard mechanism to allow callbacks to be 
> registered for execution when particular modules are first imported.
> 
> For example, to handle the commented out case above:
> 
>    @imp.imported('decimal')
>    def register(decimal):
>        Inexact.register(decimal.Decimal)

Your proposed hook is a post import hook. Could we use a pre import hook
that is called before the module is loaded? I can think of several use
cases:

* modify the search path sys.path dynamically
* issue deprecation warnings
* modify the name of the module which is going to be imported
* return a different module

def preImportHook(name: str) -> (None, str, ModuleType instance):
    """The pre import hook is run before the module is loaded
    and inserted into sys modules

    Return values::
     * None
       No special treatment
     * string: new_name
       The module "new_name" is loaded instead of the module "name"
     * module object
       The module object is inserted into sys.modules and returned by
       the import statement.
     * raise Exception
       The import is stopped and a chained ImportError is raised
    """

The pre import hook could be useful for
http://www.python.org/dev/peps/pep-0364/.

The pre import hook can probably be implemented in pure Python with a
meta path hook as described in http://www.python.org/dev/peps/pep-0302/.
I see the pre import hook as a lightweight meta path hook with an easy
to use interface.

Christian


More information about the Python-3000 mailing list