Newbie: is a variable defined?

Anton Vredegoor anton at vredegoor.doge.nl
Sat Dec 21 08:49:31 EST 2002


On Fri, 20 Dec 2002 10:26:25 -0900, Christopher Swingley
<cswingle at iarc.uaf.edu> wrote:

>Short version: I'm wondering how you test variables to see if they've 
>been defined or not.

Short answer: You don't :-)

>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.

One option would be to always initialize the "user name portion of the
email address" with a default value that is appropriate. In this case
I assume that an empty string would be okay but let's write our code
so that it doesn't break if I change my mind later.

In Python, empty strings, empty lists or tuples, the integer or
floating point value of zero, etc. are all evaluated as being false
when used in an if clause, so the code could look like this:

If efrom:
	#do something

>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?

"If len(efrom)" comes close, but "if efrom:" is better because efrom
could be something that doesn't have a length. It's possible that
later on efrom could be changed into something else like a number or a
class variable without a __len__() method defined. Code that doesn't
make these kind of assumptions won't break if they change. This is one
of the finer points of Python that's hard to grasp and can evoke
feelings of insecurity and unsafety in newbies. In reality however
this way of programming is safer because the added transparency
enables one to detect errors earlier, be it by eyeballing the
sourcecode or by using pychecker.

One other thing that comes to mind is that if there's a list of
efrom's that is looked up in the database one could just do:

for x in [y in efromlist if y]: #or some other isValid(y) function
	#look up x

So one could structure the script so that the SQL-database is only
checked for valid addresses.

BTW, I trust you're not spamming anyone :-), that would be very
unpythonic because we're nice people here,

I'm a lumberjack and I'm okay,
I sleep all night and I work all day!

Regards,

	Anton.



More information about the Python-list mailing list