non-implicit globals -- missing feature

Helmut Jarausch jarausch at skynet.be
Tue Jun 17 16:22:13 CEST 2003


Alex Martelli wrote:
> Helmut Jarausch wrote:
> 
> 
>>Hi,
>>
>>I'm missing a feature (in many programming languages including
>>Python) that does not use global variables unless requested.
>>
>>Is there any means in Python to catch errors like this following one?
>>
>>x=1
>>
>># many many lines here
>>
>>def mysub()
>>   # x=7   #forgot this assignment
>>   # ....
>>   anothersub(x)  # this uses the global x unfortunately
>>                  # how can I get an exception here ?
>>
>>So I would prefer if there were an option / pragma
>>which say  # __no_implicit_globals__
>>
>>Is there any way to get this behaviour?
> 
> 
> Unfortunately, there isn't.  But are you really sure you'd like
> it if it was there?  Such an option would inevitably flag:
> 
> def myothersub():
>   x = 7
>   anothersub(x)
> 
> as an error, because name 'anothersub' is global too.  There
> is no strong distinction between names that are currently bound
> to callable objects and names that are bound to objects that
> are not callable, after all -- names are just names.

Ofcourse one wouldn't forbid all global names but you would be
forced to "declare" them. If I remember right, Modula requires
an 'import <Name>' statement to access non-local names.
Ofcourse 'import' is used differently in Python. And Python's
'global' keyword doesn't work either, since it has other
implications. So one would probably need something like
(with better keywords, ofcourse)

option no_implicit_globals
import_name  anothersub, ....

I still think this automatic usage of global names together with a
copy on write semantics is error-prone.

> 
> You may easily get a list of all names that a function uses
> and that are not local variables of that function, e.g.:
> 
> def nonlocals(f):
>     c = f.func_code
>     return [n for n in c.co_names if n not in c.co_varnames]
> 
> this would report ['anothersub', 'x'] in your example case,
> but just ['anothersub'] in the myothersub case.  There is no
> reasonable way, that I can see, to automate the vetting of
> these lists; but if you want to program arbitrary rules such
> as 'and report an error if some of the names are module
> attributes that are not callable', you could do so...
> 

Many thanks for your comment and especially this hint,
Helmut.


-- 
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany





More information about the Python-list mailing list