Modules with __getattr__ (Re: PEP 317: Eliminate Implicit Exception Instantiation)

Greg Ewing (using g2h5dqi002 at
Wed Jun 11 05:04:12 CEST 2003

Steven Taschuk wrote:
> That seems plausible -- though Guido recently reiterated on py-dev
> his dislike of the idea of class-like attribute access for
> modules.  In his words: "When you want a class, use one. :-)".

Under type/class unification, a module is already
(an instance of) a class; you just don't get any
choice about which class it's an instance of.

I've been toying with the idea of something like

   __moduleclass__ = MyModuleClass

in the body of a module, somewhat analogous to
__metaclass__ in a class. The effect of this would
be that the object created by importing the module
would be an instance of the specified class, instead
of types.ModuleType.

The tricky part is that the class needs to be known
before the module object is created, but it can only
be discovered after executing (at least some of) the
module's code, and the module object needs to exist
before doing that, in case it gets imported by
something that it imports.

This could be circumvented by initially creating the
module as an ordinary module, and then later changing
its class if there is a __moduleclass__ present in its
namespace. This would probably require that the
__moduleclass__ be a subclass of types.ModuleType to
ensure C layout compatibility, but that would be fine
for the uses I have in mind.

By the way, the main use case I have for this is
for implementing autoloading of classes, so that I
can have a top-level package which apparently contains
a bunch of classes, but they don't actually get created
until someone asks for them. A module class with a
__getattr__ would be ideal for this.

I can feel a PEP coming on...

Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand

More information about the Python-list mailing list