Metaclasses & docstrings in 2.2

Jeremy Bowers jerf at jerf.org
Tue Jul 23 00:00:59 EDT 2002


Python session you can copy & paste to follow along:

-----

class M1:
	"M1's docstring."
	def __init__(cls, name, bases, dict):
		pass

class A:
	"A's docstring."
	pass

A.__doc__

-----

The last line will print "M1's docstring."

I'm new to metaclass stuff (though loving it!), and I wanted to check to
make sure I understand this, so please correct the following statements as
you see fit:

1. In theory, A.__doc__ *should* equal "A's docstring", because A's
docstring is more specific and should override the metaclass's docstring.

2. This happens in practice because the metaclass is executed after the
class statement for A is executed, and the setting of the docstring ends
up affecting A.

(If 1 is false, and theory and practice match up, then I'm not convinced
"metaclass" is the best word possible, though I don't have a better
suggestion. "Metaclass" to me would imply something that *generates*
classes, not *modifies* classes after the fact. This is an observation,
not a challenge; this usage is probably too entrenched to change now.)

And a note to anyone who hits this problem themselves, the solution is
either leave the docstring off of the metaclass (obvious), or add
	cls.__doc__ = dict["__doc__"]

though the latter might kill the pickler; I didn't test it.



(Oh, and this stuff rocks. A three line metaclass, and two lines
activating it on a couple of base classes, is saving me oodles of typing
and goodness only knows how many bugs based on forgetting those lines in
some obscure subclass. I had a hard time understanding the metaclasses
until I found a need for them, but now it's crystal clear. Thanks, Python
team, this f'in ROCKS!)



More information about the Python-list mailing list