Nested class structures

Alex Martelli aleaxit at yahoo.com
Sat Sep 11 13:34:00 EDT 2004


Diez B. Roggisch <deetsNOSPAM at web.de> wrote:
   ...
> Thats a nice one. I always forget about the possibility to execute actual
> code while a class is encountered by the interpreter. As always, I'm

Right, that's all you CAN execute at that time, actually -- a class body
is nothing but a generic suite of statements which execute in their own
scope.

> impressed on the variety of things doable in python - even if they don't
> appeal to me as exactly useful (in this special case I mean.)

Right about the usefulness, unless further clarified by the OP.  But,
sure!


> > No way!  Classes as well as functions are perfectly fine objects.
> > Python has no 'declarations'.
> 
> The reason I said that was because of the way the debugger steps through the
> code: If it comes to a def, it doesn't execute the body - naturally. But it

Ah, right, 'def' itself is executed as soon as it's met, but it
"stashes" the body away for later, of course -- and it binds the name. 

I.e.,
def name(...): function_body
is something like:

body = compile(function_body)
name = new.function('name', body, ...

for an appropriate value of ...;-).  Just like 'class', more precisely,
class name(bases): classbody
is like the sequence:

classdict = {}
exec class_body in classdict
name = appropriate_metaclass('name', bases, classdict)

where appropriate_metaclass is usually type (except for classic classes
or when you're using a custom metaclass).


> collects of course the function as callable. That I viewed that as sort of
> declaration - but you are of course right that there is no such thing as an
> actual declaration in python.

Right, and that's important because sometimes it's nice to put class and
def in conditionals, loops, etc -- knowing they're normal executable
statements lets you do that with tranquility.  E.g.:

if we_are_debugging:
  def f():
      body with much debugging printout
else:
  def f():
      lean and mean body

You don't need different and special #if/#else, normal runtime if/else
suffice, exactly because def is a normal executable statement...


Alex



More information about the Python-list mailing list