Tracing variable scope (local vs. global)

Lie Ryan lie.1296 at gmail.com
Tue Dec 1 17:34:41 EST 2009


On 12/2/2009 9:02 AM, Manuel Graune wrote:
>
> Hello,
>
> consider the following piece of code:
>
> a=1
> b=2
>
> def foo(c):
>      b=3
>      return a + b + c
>
> In this case, when calling "foo", "a" will take the global value,
> "b" will take the local value and "c" will take the value assigned
> when calling the function.
>
> Since I consider this behaviour a possible source of bugs due to
> personal sloppiness (e. g. forgetting to put "a=4" inside the
> function-body):
>
> Is there any way to automatically check that all variables in a
> function are either local or passed in as arguments?

If you really mean what you're saying, you won't be able to use builtin 
functions.

Anyway... the answer to your problem is a strong naming convention and 
to not store variables in the global namespace; put everything in a 
class and use a main() function so your initialization code doesn't 
clutter up the global namespace. As such, there shouldn't be a 
lowercased name in the global namespace (class use CamelCase and 
constants UPPERCASED); and all lowercased names are local (or builtins, 
use pylint to check for the case of shadowing builtins).



More information about the Python-list mailing list