Confused with classmethods

jfj jfj at
Sat Mar 12 01:40:54 CET 2005

Diez B. Roggisch wrote:

>>Moreover the documentation 
>>sais that if the first argument is an instance, its class will be
>>used for the classmethod.  OTOH, "class scope" is not a real thing in
>>python.  It is just some code which is executed and then we get its
>>locals and use it on Class(localsDict, BasesTuple, ClassName) to make
>>a new class, it seems.  So we can create a classmethod in any scope
>>and then just attach it to a class's dictionary.
> I'd still call the code executed inside a class statement block a "scope" -
> for example in a def-statement the scope is the current frame of execution,
> so 
> def foo():
>    bar = "baz"

Absolutely.  In fact here is another interesting case which can lead to
nice recipies:

class B:
     print "Making class B!"
     if blah:
         def f(self): print self
         def f(self): raise StopIteration
     print "My locals are:",locals(),"and I will make a class from them"

> makes the bar part of the frames local variables. Scopes just exchange or
> stack the  dicts for name lookup.

Well, actually, to put things right, in python there are only *two*
real scopes: global scope and local scope.

I remember that when I was a newbie I was confused by this.
The thing is that there is no nesting of scopes in reality.

Just to help other newbies avoid the confusion, I believe it would
be better to say, from the start, that:

- There definitelly is no nesting of scopes for if/for/while/try

- There is no nesting of scopes when nested functions reference
stuff from the enclosing function.  It looks like there is but
there isn't because then we should be able to say:

	exec "some code" in locals(), cellvars(), globals()

which we can't and proves that referencing variables from the enclosing
function is indeed a questionable feature.  It all happens because the
parser detects that there are variables with that name in the enclosing
functions and creates special cellvars...

- No nesting of scopes for classes because we *have* to use 'self'
(which is a good thing IMHO).


More information about the Python-list mailing list