class "type" and metaclasses (was Re: Style for overwritten methods of abstract classes)

Stefan Schwarzer s.schwarzer at ndh.net
Sun Jan 6 11:05:15 EST 2002


Hello Alex

thank you for the long answer. Here's mine. :-)

Alex Martelli wrote:
> > So I can think of three different approaches:
> > 1. write the code as above
> > 2. merely describe the implementation/interfaces (e. g. in the class
> >    docstring or in a comment); write no code
> > 3. use code but let the abstract methods raise NotImplementedError
> >    instead of providing a default behaviour which might be useless
> > (4. Are there others?)
> 
> Yes, there are.  You could have a metaclass that does ensure the
> behavior you desire, and specify specialmethods that MAY or MUST
> be provided in class-attributes.
> 
> It's easier in 2.2, of course, where you can make your metaclass
> just by inheriting from type and tweaking it slightly, so, for
> example, here's a metaclass to implement "must-checking", only:

[Interesting code example of metaclass snipped]

To be honest, I haven't understood everything of this but it inspired
my curiosity regarding the "type" class. I didn't find anything about
it in the Python 2.2 docs (though I won't say it's not there ;-) ).
However, I discovered something via >>> help(type) (and then using
the HTTP "version" of pydoc).

The PEPs 252 and 253 seemed rather to be aimed at C programmers who
want to define their own types. The most useful document (for me) seems
to be the tutorial "Unifying types and classes in Python 2.2" at
http://www.python.org/2.2/descrintro.html . If I haven't overlooked it
that also doesn't mention the type class, does it?

There are some more questions open (for me):

- Where can I find more information on metaclass programming in Python?

- (How) are the built-in function type and the class named "type" (that
  didn't exist prior to Python 2.2?) related?

- Should I be very concerned with metaclass programming? I can't really
  estimate how useful they are. On the other hand, I suppose that would
  not have been added to Python if it weren't useful (contrasted to beeing
  merely "nice"). Are metaclasses rather for experts?

> But, to each its own.  Python gives you all the power you need to
> shoot yourself in the foot, in this and several other ways.  While
> still not the best language for "Bondage and Discipline Programming",
> Python does enjoy the advantage (?) that you may easily devise and
> implement your own cruel and unusual punishments for yourself
> along these lines.

No, I don't like B&D programming. If I would, I probably wouldn't use
Python but rather C++ or Java. ;-) My question aimed more at a simple
or elegant approach. (Please don't be upset if you consider your
suggestion simple and/or elegant. To be more specifically: the usage
of the so defined class may be simple but its implementation not so.
;-) ).

Stefan



More information about the Python-list mailing list