473,563 Members | 2,884 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2651
At some point, Bart Nessux <ba*********@ho tmail.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=No ne):
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)phy sics(dot)mcmast er(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 <opsbxubr1g1v4i jd@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_reportin g(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 <opsbxubr1g1v4i jd@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_reportin g(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.p acific.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_reportin g(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.current frame().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_reportin g(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.current frame().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 <opsb9nh9xd1v4i jd@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_reportin g(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
2635
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 twice and check that they match. Problem is script doesn't valide past username input and I dont know why!! If you don't enter a password it doesn't...
3
15816
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() <> "" Then 'this is the line that hangs debugging using VID 'code if array is populated
14
12321
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++ ) { if( !isDigit(foo) ) { return false; } }
2
3701
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 */ } else { /* exit with error message */
8
3150
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 data to it, then moves on to the next rep: ---------- conTARGETVisits = FTPLocation & "RepCallPlan" & Format(MyRepCode, "00")
7
18643
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 try...except structure: index = -3
1
13813
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 more list and dictionaries variables.SO every where I have to check whether the dict or list is empty. Thanks PSB
3
1308
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 simple: If list_of_files != "" : # this can be if list_of_files != : get the files elas:
5
3620
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 System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles DetailsView1.ItemInserting Dim h As String
0
7664
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7885
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7948
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6250
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5213
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3642
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2082
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1198
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
923
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.