Newbie: is a variable defined?
Nicodemus
nicodemus at globalite.com.br
Fri Dec 20 15:34:50 EST 2002
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