Check if variable is defined
tim.one at home.com
Fri May 18 09:34:06 CEST 2001
[Fredrik, on testing whether a vrbl has been bound]
> that's extremely bad style in Python, but you probably knew that.
> If that were true, it would declare a lot of interesting applications
> for Python in particular and script languages in general as `bad
> style' a priori.
For Python in particular, no: such apps are fine but that programming style
is unnecessary and indeed a bad style in Python.
> In these applications you define little languages for users which are
> not really programmers, but for whom you want to provide a way to hack
> in some simple commands for a dedicated task. Instead of writing a
> parser you define these commands as Python functions at let the basic
> syntax be Python --- why not, it is as good or even better as any
> ad-hoc invented one.
> After execfile()-ing their command file it *is* often necessary to
> test if certain variables where set or not --- of course depending on
> how you defined your little language.
But there's no need to pollute *your* program's vrbls with theirs. What if
they happen to use a variable of the same name as a variable you're using in
your interpreter? Chaos.
Use the exec statement, and pass it an explicit dict for evaluation context.
Then the user-program's bindings are in a well-controlled place, and testing
for boundedness is an ordinary .has_key() operation on that dict. Indeed,
Guido has said that he expects to deprecate the use of exec (and execfile)
*without* the use of explicit non-global()/local() dicts, and in part because
of all the trouble people get themselves into by letting the dynamic
execution gimmicks pollute the namespace of the invoking code. That's as
dangerous as using "from XYZ import *" at random points in your code when you
have no idea what XYZ exports.
> P.S.: I feel like starting a flame war today which is why I would like
> to maintain that little languages are easier to do in Tcl ;-)
I thought everything was easier in Tcl -- don't be so timid <wink>.
More information about the Python-list