473,396 Members | 1,898 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

checking whether a var is empty or not

Are these equivelent? Is one approach prefered
over the other

#check to see if var contains something... if so
proceed.
if var is not None:
continue

#check to see if var is empty... if so prompt user
again.
if not var:
print "Please specify the amount."
...
Jul 18 '05 #1
9 2636
At some point, Bart Nessux <ba*********@hotmail.com> wrote:
Are these equivelent? Is one approach prefered over the other

#check to see if var contains something... if so proceed.
if var is not None:
continue

#check to see if var is empty... if so prompt user again.
if not var:
print "Please specify the amount."
...


They're not equivalent: if var is None, the first doesn't trigger, but
the second does.

Do you mean:

if var is None:
# do something
if not var:
# do something

The first if only triggers if var is the singleton None.
The second if will trigger if var is False, 0, 0.0, 0j, '', [], (), None,
or anything else that has a length of 0 or var.__nonzero__() returns
False. In this case, you're checking if var is false in a boolean
logic context.

If you're checking arguments to a function to see if a non-default
argument has been passed, you probably want the first, like this:

def function(var=None):
if var is None:
# do something to get a default argument

But if you want a flag that's true or false, you want the second:
def function(var):
if var:
# yes, do something
else:
# no, do something else

--
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
Jul 18 '05 #2
Bart Nessux wrote:
Are these equivelent? Is one approach prefered over the other

#check to see if var contains something... if so proceed.
if var is not None:
continue

#check to see if var is empty... if so prompt user again.
if not var:
print "Please specify the amount."
...

They're not quite equivalent. The second form ('if not var') will
resolve to be true if var is any value that resolves to false -- this
could be None, 0, [], {}, '', or some user-defined objects. The first
form will only be true if var is None.

This could be significant if, for instance, 0 is a valid value. You
might want to initialize var to None, conditionally assign an integer to
it, and then later see if an integer (including 0) was actually
assigned. In that case, you'd need to use the first form.

Jeff Shannon
Technician/Programmer
Credit International

Jul 18 '05 #3


This smells like PHP to me...

if var is not None:
if var has not been assigned, it raises an exception.
if var has been assigned, it contains a value which can be None or
someting else.

This is different from PHP where you can't know if a variable exists or
not, because a non-existent variable will contain null if you check it,
and putting null in a variable is like deleting it, but noone knows
because there's no way of checking if a variable really exists, etc.

Are these equivelent? Is one approach prefered over the other

#check to see if var contains something... if so proceed.
if var is not None:
continue

#check to see if var is empty... if so prompt user again.
if not var:
print "Please specify the amount."
...


Jul 18 '05 #4
In article <opsbxubr1g1v4ijd@musicbox>, Pierre-Frédéric Caillaud wrote:

This smells like PHP to me...

if var is not None:
if var has not been assigned, it raises an exception.
if var has been assigned, it contains a value which can be None or
someting else.

This is different from PHP where you can't know if a variable exists or
not, because a non-existent variable will contain null if you check it,
and putting null in a variable is like deleting it, but noone knows
because there's no way of checking if a variable really exists, etc.


No, in PHP, you can find out if a variable exists using isset(). And trying
to dereference an uninitialized variable will generate a warning if you have
error reporting turned up all the way (error_reporting(E_ALL)).

--
.:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.

"When the country is confused and in chaos, information scientists appear."
Librarian's Lao Tzu: http://www.geocities.com/onelibrarian.geo/lao_tzu.html
Jul 18 '05 #5
Dave Benjamin wrote:
In article <opsbxubr1g1v4ijd@musicbox>, Pierre-Frédéric Caillaud wrote:
This smells like PHP to me...

if var is not None:
if var has not been assigned, it raises an exception.
if var has been assigned, it contains a value which can be None or
someting else.

This is different from PHP where you can't know if a variable exists or
not, because a non-existent variable will contain null if you check it,
and putting null in a variable is like deleting it, but noone knows
because there's no way of checking if a variable really exists, etc.

No, in PHP, you can find out if a variable exists using isset(). And trying
to dereference an uninitialized variable will generate a warning if you have
error reporting turned up all the way (error_reporting(E_ALL)).

def isset(var): .... return var in globals()
.... print isset('var') 0 var = 43
print isset('var')

1

Not that I can see any good use for this :-).

- Dave

--
http://www.object-craft.com.au
Jul 18 '05 #6
In article <ap*******************@nasal.pacific.net.au>, Dave Cole wrote:
Dave Benjamin wrote:

No, in PHP, you can find out if a variable exists using isset(). And trying
to dereference an uninitialized variable will generate a warning if you have
error reporting turned up all the way (error_reporting(E_ALL)).

def isset(var): ... return var in globals()
... print isset('var') 0 var = 43
print isset('var') 1

Not that I can see any good use for this :-).


Not that there's *any* reason to do anything like this, *ever* ;) but...
import inspect
def isset(v): .... return v in globals() or v in inspect.currentframe().f_back.f_locals
.... isset('a') False a = 5
isset('a') True def f(): .... b = 6
.... print isset('b')
.... print isset('c')
.... f() True
False c = 42
f()

True
True

Verdict: Just catch the NameError, already! =)

--
.:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.

"When the country is confused and in chaos, information scientists appear."
Librarian's Lao Tzu: http://www.geocities.com/onelibrarian.geo/lao_tzu.html
Jul 18 '05 #7
No, in PHP, you can find out if a variable exists using isset(). And
trying
to dereference an uninitialized variable will generate a warning if you
have
error reporting turned up all the way (error_reporting(E_ALL)).


WRONG !!!!!

Example in this stupid language :

<?php

echo "<p>one : ";
var_dump(isset( $a ));

$a = 1;
echo "<p>two : ";
var_dump(isset( $a ));

$a = null;
echo "<p>three : ";
var_dump(isset( $a ));

?>

Output :
one : bool(false)

two : bool(true)

three : bool(false)
Get it ?

Jul 18 '05 #8

import inspect
def isset(v):
return v in globals() or v in inspect.currentframe().f_back.f_locals

Why would you want that ?

Use this PHP emulator :

from (all installed modules...) import *

If you want to emulate PHP, you should only use global variables, and
don't forget to copy those into all the modules you import (and of course,
update globals with all variables coming from all modules).
Jul 18 '05 #9
In article <opsb9nh9xd1v4ijd@musicbox>, Pierre-Frédéric Caillaud wrote:
No, in PHP, you can find out if a variable exists using isset(). And
trying
to dereference an uninitialized variable will generate a warning if you
have
error reporting turned up all the way (error_reporting(E_ALL)).


WRONG !!!!!
Example in this stupid language :

<?php

echo "<p>one : ";
var_dump(isset( $a ));

$a = 1;
echo "<p>two : ";
var_dump(isset( $a ));

$a = null;
echo "<p>three : ";
var_dump(isset( $a ));

?>

Output :

one : bool(false)
two : bool(true)
three : bool(false)

Get it ?


I stand corrected. That is rather stupid.

Well, I try to use nulls sparingly and always initialize my variables, which
may explain why in the five or so years I've been using PHP, I've never run
into this problem. Likewise, I don't think I've ever had to use the
corresponding idiom in Python:

try:
a
except NameError:
# ...

At the very least, I'll be testing for a's existence in some namespace, so
I'll be looking for an AttributeError.

--
.:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.

"When the country is confused and in chaos, information scientists appear."
Librarian's Lao Tzu: http://www.geocities.com/onelibrarian.geo/lao_tzu.html
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Philip D Heady | last post by:
Hi, I'm validating a simple form for input via post ($PHP_SELF). Near the end I check for username and password. I'm using simple if, elseif, else statements. I require them to enter password...
3
by: David P. Jessup | last post by:
Good day folks. Within an ASP I'm working on I need to check whether an array is empty or not. Code: Dim somearray() 'other code: array might have been populated, maybe not if somearray()...
14
by: Christopher Benson-Manica | last post by:
I'm trying to check whether a string is all digits. This part is easy: function allDigits( str ) { var foo=str.split( '' ); // better than charAt()? for( var idx=0; idx < foo.length; idx++ ) {...
2
by: Marlene Stebbins | last post by:
I am entering numbers into my program from the command line. I want to check whether they are > INT_MAX. Sounds simple, but I've discovered that if(x <= INT_MAX) { /* use x in some calculation...
8
by: J-P-W | last post by:
Hi, anyone got any thoughts on this problem? I have sales reps. that remotely send their data to an ftp server. The office downloads all files, the code creates an empty file, then downloads the...
7
by: Rehceb Rotkiv | last post by:
I want to check whether, for example, the element myList exists. So far I did it like this: index = -3 if len(myList) >= abs(index): print myList Another idea I had was to (ab-?)use the...
1
by: psbasha | last post by:
Hi, Whether we can check the empty list or dict by i"f "conditon or catch this exception by "try" and "catch" blocks. Which will be the best practctice?. In my work I have to play with...
3
by: Nader | last post by:
Hello, I read some files name from a directory and then I put these name in a list. I will check whether it is empty or not, and I would do it with an exception. With if statement it is very...
5
by: bob | last post by:
Hi, i want to check whether the textbox of the detailsview is not left empty, in insert mode. I did this: Protected Sub DetailsView1_ItemInserting(ByVal sender As Object, ByVal e As...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.