[Python-Dev] Re: would warnings be appropriate for probably-misused global statements?

Guido van Rossum guido@python.org
Wed, 06 Nov 2002 18:17:31 -0500

> > Yes.  This could even be made a syntax error, as with other contextual
> > statements:
> This somewhat contradicts Guido's judgement that this would not be
> easy to implement. Can you come up with a patch?

Alex suggested two different things to test for: global outside a
function, and global for a variable that is not actually set.

Global outside a function would seem easy to detect (at least as easy
as return outside a function), but you need to be careful: in a string
passed to the exec statement, one could have distinct locals and
globals, and then 'global x' outside a function would make sense.
Also, 'global x' makes sense inside a class statement.

Global for a variable that's not set should at best trigger a
warning.  To detect this, you'd have to analyze all the assignments in
a block.  That currently happens as part of the local variable
determination, and it may be possible to fold this in; I'm not clear
how easy it would be to get the error message refer to the correct
line number though.

But I'm not excited about this.  A similar amount of analysis can
discover assigning to a variable that's not used.  Isn't that more
useful?  Using a name that's not defined anywhere.  Etc.  There are
tons of these things.  PyChecker watches for all of them.  I'd prefer
to make a project out of integrating PyChecker functionality into
Python, eventually, rather than attacking random things one at a time
-- the more of these we do in an ad-hoc fashion, the harder it will be
to do in a more systematic way.

--Guido van Rossum (home page: http://www.python.org/~guido/)