Newbie: is a variable defined?
Lemniscate
d_blade8 at hotmail.com
Fri Dec 20 18:04:00 EST 2002
Oh, the reason I like dir() better than locals is that locals() is a
dictionary and I didn't see the need in accessing all the values (its
slightly more efficient, on huge lists of local items, that have
large/long values, on slow computers, etc.l alternatively, you could
query locals().keys() or use something like
locals().has_key(Your_Variable) ). I just wanted to give you some
options. Good luck.
Chris
Nicodemus <nicodemus at globalite.com.br> wrote in message news:<mailman.1040413473.24131.python-list at python.org>...
> Christopher Swingley wrote:
>
> >Greetings,
> >
> >
> >Longer version: What I'm trying to do is parse a file that may or may
> >not contain an email address. If it does, I use regular expressions to
> >extract the username portion of the email address and place this in a
> >variable named 'efrom'. Later, I want to search a SQL database, and if
> >'efrom' has been defined it will perform one SELECT and if it's not
> >it'll do something else.
> >
> >I could set up a seperate flag 'efrom_defined = 0', update it when efrom
> >gets a value, and then test this flag. Or I could use a 'try: except
> >NameError:' block. Or I could do 'efrom = ""' at the beginning of the
> >program and then test 'if len(efrom):'
> >
> >How would you do this?
> >
>
> Hail!
>
> You can do what you want by checking if the variable has an entry in the
> locals dir:
>
> >>> 'efrom' in locals()
> 0
> >>> efrom = 10
> >>> 'efrom' in locals()
> 1
>
> But I would recommend against that.
>
> The standard way is to initialize all the variables with None, and then
> check later if they were
> initialized with something else.
>
> >>> efrom = None
> >>> efrom = 'xx at xx.com'
> # later...
> >>> if efrom is not None:
> ... # use 'efrom' variable here
>
>
>
> Farewell,
> Nicodemus.
More information about the Python-list
mailing list