Testing for a Variable

Alex Martelli aleaxit at yahoo.com
Fri May 4 06:23:36 EDT 2001


"Brian Quinlan" <BrianQ at ActiveState.com> wrote in message
news:mailman.988938007.12258.python-list at python.org...
> Steve wrote:
> > Probably not a good idea, in case var holds something like
> > "system('rm *')".
> > Since you only need to be sure it can be referenced, simply
> > use a reference,
> > as in:
> >
> > try:
> >     var
> > except NameError:
> >     print "You lose"
> >
> > > # Do something
> > > except NameError:
> > > # Do something else
> > >
> > no-need-to-evaluate-what-can-simply-be-referred-to-ly y'rs -- Steve
>
> The question is, of course, can you simply refer to it? You can't pass
> around undefined variables but you can pass strings. And if the variable
is
> defined by your own application, hopefully it won't have unsafe code it
in.

One way to check whether a string X is the name of a variable
is vars().has_key(X).  In 2.2, syntax "X in vars()" should be
even neater for the same semantics.  However, I suspect this
doesn't play well with nested scopes -- variables that ARE
defined in a nested scope seems to be present in vars() and
locals() only if they're actually USED somewhere in the current
function's scope, if I have understood things correctly.

But I guess if you're "passing around" a variable name it's
presumably not meant to apply across functions anyway, is it?
In other words, not a _local_ variable and I would guess not
one from a nested scope either.  In this case, i.e. if global
variables are your real interest, then they're attributes of
the module object and hasattr() may be simplest (although
globals().has_key() will also work fine, if the SAME module
object is shared by all the places in which you're "passing
around" the variable-name string).

It all does sound pretty peculiar to me, I will confess, so
maybe I just haven't understood exactly what application
level purpose you intend to satisfy through this means...?


Alex






More information about the Python-list mailing list