473,586 Members | 2,678 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

undefined variable ?

Hello
How can i check if variable named var1 exists ?

Thanx
Michal
Jul 18 '05 #1
5 6716
vertigo wrote:
Hello
How can i check if variable named var1 exists ?


if 'var1' in globals():
...
Jul 18 '05 #2
vertigo wrote:
How can i check if variable named var1 exists ?


It's frequently a better approach to assume that it does and catch an
exception if it doesn't.

try:
var1
except NameError:
var1 = "neW"

But why do you want to do this?
--
Michael Hoffman
Jul 18 '05 #3
Are exceptions cheap in Python then? Coming from Java, I know there's
all sorts of overhead involved in creating and throwing an exception
there...

On Sat, 16 Oct 2004 13:20:08 +0100, Michael Hoffman
<m.************ *************** ******@example. com> wrote:
vertigo wrote:
How can i check if variable named var1 exists ?


It's frequently a better approach to assume that it does and catch an
exception if it doesn't.

try:
var1
except NameError:
var1 = "neW"

But why do you want to do this?
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list

--
http://www.haslo.ch/
Jul 18 '05 #4
On Sat, Oct 16, 2004 at 11:43:08AM +0200, vertigo wrote:
Hello
How can i check if variable named var1 exists ?


While it's possible to do that, you'll do better in the long run by
learning to write programs in the Python style, which does not often
perform checks like "does the named variable exist". For instance,
instead of writing
def my_max(seq):
for i in seq:
if undefined("larg est") or i > largest: largest = i
return largest
you would write
def my_max(seq):
largest = None
for i in seq:
if largest is None or i > largest: largest = i
or
def my_max(seq):
largest = seq[0]
for i in seq:
if i > largest: largest = i

It's a little more common to check whether an object has a given
attribute:
def write_or_send(f , s):
# "look-before-you-leap" style
if hasattr(f, "write"): return f.write(s)
return f.send(s)

And checking whether a key is in a dictionary is frequent:
if "spam" not in pantry: pantry["spam"] = buy("spam")

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.6 (GNU/Linux)

iD8DBQFBcUOlJd0 1MZaTXX0RAnwqAJ 9BEiZyFXPdVD4F/Wnc3S2NsuYvGgCf bmq+
+mUQ3j5gjkCowI1 SShWXPto=
=5iRN
-----END PGP SIGNATURE-----

Jul 18 '05 #5
Are exceptions cheap in Python then? Coming from Java, I know there's
all sorts of overhead involved in creating and throwing an exception
there...


They are not free, but they aren't that bad either...
import time
def te(n): ... for i in xrange(n):
... try:
... j = 1
... except:
... pass
... def tf(n): ... for i in xrange(n):
... try:
... raise #generally improper use
... except:
... pass
... def tf2(n): ... for i in xrange(n):
... try:
... j = l
... except:
... pass
... def ne(n): ... for i in xrange(n):
... j = 1
... t = time.time();te( 1000000);time.t ime()-t 0.9210000038146 9727 t = time.time();tf( 1000000);time.t ime()-t 7.7030000686645 508 t = time.time();tf( 1000000);time.t ime()-t 27.0 t = time.time();ne( 1000000);time.t ime()-t 0.5789999961853 0273

The no-exception version runs in ~.58 seconds, with-exception handling
(none raised) runs in ~.92 seconds, the first exception raiser runs in
~7.7 seconds, and the name error on assignment runs in ~27 seconds.
As long as you aren't relying on exception handling as a major part of
your algorithms, and are actually using them as /error handling/, I
wouldn't worry too much; the rest of us don't (we prefer properly
running scripts).

- Josiah

Jul 18 '05 #6

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

Similar topics

3
8265
by: Dan Finn | last post by:
OpenBSD 3.2 Apache 1.3.26 PHP 4.3.4 PHP-Nuke 6.9 getting these in the apache error log: Sun Nov 16 20:20:16 2003] PHP Notice: Undefined variable: HTTP_USER_AGENT in /htdocs/nuke/html/mainfile.php on line 16 PHP Notice: import_request_variables(): No prefix specified - possible security hazard in
4
3700
by: Pizzor2000 | last post by:
When I run PHP scripts on my company's web server, I can attempt to read a variable that has not already been declared. When I try to access a variable before a value is assigned on my home computer (Windows with IIS), I get a warning about the variable being undefined. Is there a flag in php.ini that allows a script to check a variable...
7
2805
by: Coder Droid | last post by:
I decided to run some code with errors set to E_ALL, just to see what I would run across. It caught a few things, but 90% or better of the messages were of the 'undefined' kind: PHP Notice: Undefined variable PHP Notice: Undefined index PHP Notice: Undefined property I'd like to go back and fix what I can, but I'm wondering: how good...
0
1852
by: Dave | last post by:
Hi everyone, (I already posted this to the VS.NET IDE news group without any responses, so I'm attempting one more time in this group) The issue I'm having is occuring in the IDE of VS.NET 2003, although I'm not sure what is actually causing the problem. I can't summarize the issue, so please read on to find out more. I've created a...
10
5267
by: Sharon | last post by:
Hi! Does anyone know why the onclick in the following popup menu gives the error:"Val is undefined"? Does it have something to do with the fact that it is called within the variable tablePop? Because it IS displayed properly as part of the popup text, where it is called outside the single quotation marks (see ). It is only in the onclick that...
4
4149
by: Chris Beall | last post by:
If you want your code to be bulletproof, do you have to explicitly check for the existence of any possibly-undefined variable? Example: window.outerHeight is defined by some browsers, but not others. It would therefore seem prudent, before using this variable, to do something like: if (typeof (window.outerHeight) != "undefined") { do stuff...
49
14463
by: matty | last post by:
Hi, I recently got very confused (well that's my life) about the "undefined" value. I looked in the FAQ and didn't see anything about it. On http://www.webreference.com/programming/javascript/gr/column9/ they say: <snip> The undefined property A relatively recent addition to JavaScript is the undefined property.
17
3333
by: yb | last post by:
Hi, Looking for clarification of undefined variables vs. error in JavaScript code. e.g. <script> alert( z ); // this will be an error, i.e. an exception </script>
45
4814
by: VK | last post by:
(see the post by ASM in the original thread; can be seen at <http://groups.google.com/group/comp.lang.javascript/browse_frm/thread/3716384d8bfa1b0b> as an option) As that is not in relevance to "new Array() vs " question or to the array performance, I dared to move it to a new thread. Gecko takes undefined value strictly as per Book 4,...
2
3440
by: Bob Bruyn | last post by:
I've recently installed Apache 2 and php 5.2 on my WIndows XP machine. Everything is up and running. I'm passing some vars via the URL. It works fine online: http://www.torusdesign.nl/spry/test.php?folder=schilderijen/vrij_werk&navColor=SchilderijenNAV This is the code: <?php echo $folder; ?> <?php echo $navColor; ?>
0
7912
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
7839
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8202
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. ...
1
7959
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5710
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5390
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
3837
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...
0
3865
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2345
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

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.