Python Gotcha's?

Dave Angel d at davea.name
Thu Apr 5 21:38:37 EDT 2012


On 04/05/2012 08:02 PM, Cameron Simpson wrote:
> On 05Apr2012 19:13, Alain Ketterlin <alain at dpt-info.u-strasbg.fr> wrote:
> | Miki Tebeka <miki.tebeka at gmail.com> writes:
> | > (Note that I want over http://wiki.python.org/moin/PythonWarts already).
> | 
> | The "local variable and scoping" is, imho, something to be really
> | careful about. Here is an example:
> | 
> | class A(object):
> |     def __init__(self):
> |         self.x = 0
> |     def r(self):
> |         return x # forgot self
> | 
> | a = A()
> | x = 1
> | print a.r() # prints 1
> | 
> | I know there is "no remedy". It's just really tricky.
>
> Whoa!
>
> I presume this jost happens with globals and not with one function
> calling another... (I guess I should test that instead of asking such a
> dumb question).

It doesn't generally happen "with one function calling another."  What
it does apply to is to "variables" of nested scope.  If the function
doesn't have a defining line for x, then the runtime looks one level
out.  in this case, that's to globals. But in more complex programs, for
example with nested functions, it might be to other places.

-- 

DaveA




More information about the Python-list mailing list