Module magic methods

Neel Krishnaswami neelk at brick.cswv.com
Wed Jun 16 04:19:22 CEST 1999


In article <m3g13wt71h.fsf at atrus.jesus.cam.ac.uk>,
Michael Hudson  <mwh21 at cam.ac.uk> wrote:
>
>FWIW, I've often thought it would be funky to be able to define
>__add__ or __call__ etc methods to modules. Pointless, I'd have to
>admit, but still funky.

Not so pointless, imo, because a module is just a singleton class 
with a light dusting of nonstandard syntax and semantics. I've 
been bitten now and again by the differences (don't ask), and I
compiled a list of the differences. Some are superficial, and some
are significant:

o Classes are defined by the block a "class" statement contains; a
  module is defined by the contents of its file (sort of).
 
o Instances of classes are created by the __init__ method of the
  class (mostly), and a module instance is created with the "import"
  statement.

o Type-checking is performed on a call to a method of a class to
  guarantee that the first argument is the same class as the class the
  method belongs to (sigh), whereas no such type checking is performed
  on functions inside a module.

o Assigning to a instance attribute of the same name as a class
  variable will just shadow the class attribute for that instance. 
  For the module, no such shadowing happens. That is,

  >>> class Foo:
          q = 'foo'

  >>> x = Foo()
  >>> x.q = 'bar'
  >>> print x.q
  bar
  >>> print Foo.q
  foo

  >>> import math
  >>> print math.pi
  3.14159265359
  >>> math.pi = 3
  >>> print math.pi 
  3
  >>> del math; import math 
  >>> print math.pi
  3

Right now, since classes and modules are built-in types, so we don't 
have access to what makes them different. So you can't have a module
intializer that you can pass information to, for example. But in the
promised land of Python 2.0, when types and classes are unified, it
may be possible to do things like this:

class WhyWhyWhy(Module, Class):
    [...]

In addition to just being gross, notice how we've snuck a metaclass
into the equation. This would just be too cool, wouldn't it? :) 


Neel




More information about the Python-list mailing list