creating class objects inside methods

Stephen Hansen apt.shansen at
Sun Oct 4 22:31:28 CEST 2009

> Anyways, maybe I got off to a bad start, but I'm a bit leery of the
> language. In my estimation it's trying to be 'too clever by half', and
> this coming from a veteran bash/perl programmer. I mean, free form is
> one thing, but too much of a good thing can be harmful to your
> programming health. Maybe PyChecker or PyLint will help, I don't know.

There's nothing at all clever going on here, though. There just seems to be
a lack of understanding of how assignment and variables operate in Python.
Nothing is being changed "at a distance"; the lookup and binding semantics
of Python are actually really, really simple.

Everytime you reference a name, it is first looked up in the local scope: if
it's not found there, it's looked up in the global scope. That's it.

Everytime you assign a name, it is always assigned to the local scope.

Those are the basic rules, and that's really all you need to know for all
the basic doings. Anytime you try to get the value of "state", it looks in
two places -- local, then global. Anytime you try to assign the value of
"state", it assigns it to the local scope.

The global scope remains unchanged in the assignment; you're not altering
anything at a distance or going and messing with the class definition that
lives in the global scope of the module. You've just made a local variable
that shadows it.

Okay, things get slightly more complicated in two places-- if you use the
'global name' statement within a function, subsequent assignments to name
will assign to the global namespace instead of the local namespace. Also, if
you nest functions within each-other, there is a limited searching up that
nesting of local scopes to find names. There's no other nested / lexical
scoping in any other context in Python.

But, overall, things are simple. Just different. There's only two scopes or
namespaces: the current function body, and the global scope. Nothing's
clever going on. All assignment is local, lookups search first the local and
then the global namespace. In my experience, once you grasp that it's
trivial to never run into this sort of error ever again. I don't just mean
finding it when you do it-- but never even writing it anymore.

Just don't shadow global names in the local namespace. It's really not a big

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list