non-implicit globals -- missing feature
aleax at aleax.it
Tue Jun 17 11:07:30 CEST 2003
Helmut Jarausch wrote:
> 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?
> # 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:
x = 7
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.
You may easily get a list of all names that a function uses
and that are not local variables of that function, e.g.:
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...
More information about the Python-list