Hi,
I have a reference to certain objects. What is the most pythonic way to
test for valid reference:
if obj:
if None!=obs:
if obj is not None:
--
alfz1 9 2044
alf wrote:
Hi,
I have a reference to certain objects. What is the most pythonic way to
test for valid reference:
if obj:
if None!=obs:
if obj is not None:
If you're checking whether an object is None or not, the third is the
best way.
Some people might say you should use the first: this works sometimes,
but sometimes an object that is not None can be false, in which case
this test will fail. (I'll give you an example of one place where it
bit me: in ElementTree. An Element is false if there are no
subelements, thus to test whether a certain element exist, you can't
just say "if aaa.find('bbb') ", because a bbb tag exists, it is false
unless it has subelements of its own. You must instead say "if
aaa.find('bbb') is not None".)
The second test is slower than the first and adds nothing. Whether
something is None is an identity test; identity tests should use is.
Carl Banks
alf a écrit :
Hi,
I have a reference to certain objects. What is the most pythonic way to
test for valid reference:
if obj:
Don't do this:
for o in [0, '', [], {}, ()]:
print obj, bool(obj), obj is None
if None!=obs:
In python, assignement is a statement, not an expression, so there's no
way you could write 'if obj = None' by mistake (-syntax error). So
this style is unpythonic. Also, None is a singleton, and identity test
is way faster than equality test.
if obj is not None:
That's the good one.
I have a reference to certain objects. What is the most pythonic way to
test for valid reference:
if obj:
if None!=obs:
if obj is not None:
The third way is the most precise way. It is often used in combination
with default arguments.
def __init__(self, amount = None):
if amount is not None:
self.amount = amount
else:
self.amount = self.calc_amoun t()
However, the first way is shorter and more concise. It really depends
on what obj is supposed to be and where you get obj from. If it is a
database and obj is an instance:
obj = db.get("sometab le", id = 33)
(assuming db.get returns None if the object isn't found) Then "if
obj:" clearly is the right test. In general, I think "If obj:" is the
right answer, except when dealing with default arguments. And you must
be aware that some objects, like 0, [] or {} evaluate to False -- it
is possible that that could create some subtle bugs.
--
mvh Björn
alf wrote:
Hi,
I have a reference to certain objects. What is the most pythonic way to
test for valid reference:
if obj:
if None!=obs:
if obj is not None:
I like this way the most. I used timeit to benchmark this against the
first one, expecting it to be faster (the first is a general false
test, the last should just be comparing pointers) but it's slower.
Still I don't expect that to ever matter, so I use it wherever I wish
to test for None, it reads the best of all of them.
-Sandra
Bruno Desthuilliers wrote:
In python, assignement is a statement, not an expression, so there's no
way you could write 'if obj = None' by mistake (-syntax error). So
this style is unpythonic. Also, None is a singleton, and identity test
is way faster than equality test.
Playing Devil's advocate here: if you were to write "x!=None", then x's
__eq__ method is invoked, which might not account for the possibility
that the other operand is None.
However, if you write "None!=x", then None's __eq__ method is invoked,
which accounts for any given type.
Carl Banks
alf <ask@mewrites :
I have a reference to certain objects. What is the most pythonic way
to test for valid reference:
If you're intending to use None as a sentinel for an invalid reference,
then use
if obj is not None:
You could also make a unique sentinel:
Sentinel = object()
...
if obj is not Sentinel: ...
"if obj" isn't necessarily what you want; obj might be a valid but
empty container.
"if obj != None" is also wrong, for reasons someone else explained.
Carl Banks wrote:
Bruno Desthuilliers wrote:
>In python, assignement is a statement, not an expression, so there's no way you could write 'if obj = None' by mistake (-syntax error). So this style is unpythonic. Also, None is a singleton, and identity test is way faster than equality test.
Playing Devil's advocate here: if you were to write "x!=None", then x's
__eq__ method is invoked, which might not account for the possibility
that the other operand is None.
However, if you write "None!=x", then None's __eq__ method is invoked,
which accounts for any given type.
Well... Since we all know it should be an identity test anyway... <g>
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
At Monday 4/9/2006 17:02, alf wrote:
>I have a reference to certain objects. What is the most pythonic way to test for valid reference:
By "valid reference" you mean, you have initially:
obj = None
and you want to detect whether obj is bound to another, different,
object, right?
if obj:
This checks whether obj is considered True, not whether it is None.
e.g. obj=[] would not pass.
if None!=obs:
Would be OK, but the next one is better:
if obj is not None:
This is what you are looking for! :)
Gabriel Genellina
Softlab SRL
_______________ _______________ _______________ _____
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! http://www.yahoo.com.ar/respuestas
alf wrote:
Hi,
I have a reference to certain objects. What is the most pythonic way to
test for valid reference:
if obj:
if None!=obs:
if obj is not None:
thx for all answers - now "if obj is not None:" in an obvious choice ... This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: TechNovice |
last post by:
Hi:
I'm trying to find a way to test input values.
To test an integer I tried this code:
******Code******
int input_number;
cin>>input_number;
while(!input_number)
cout<<"invalid input"<<endl;
******End Code******
|
by: Konstantin Zakharenko |
last post by:
Hello,
Our QA team have running a lot of test scripts (for automated regression
testing), they run them on the different databases (Oracle/MS SQL).
Several of those tests are dependent on the current date/time. In order to
be
able to use them efficiently, we changed the current date/time on the QA
database server to a specific date/time before starting the scripts, so we
are sure the test scripts always run in the same environment.
|
by: Jonathan Allen |
last post by:
We have found that our method of testing does not match traditional
text-book methodologies. I decided to write a short white paper on it so
that I could get your opinions. Does anyone else use this method? If so,
what the heck is it called? Do you think it would work in other projects, or
did we just luck out?
Jonathan Allen
*****************
|
by: John Smith |
last post by:
Hey folks,
I know this is an old topic, but I can't find a definitive answer on google.
How do I tell if an int has been initialized or not? I had been testing it
like:
if(myInt == Convert.ToInt32(null)){
:
}
|
by: Ravi Chand via .NET 247 |
last post by:
(Type your message here)
Hi All,
One of our ASP.Net application was stress tested recently andunfortunately it is throwing up intermittent errors. Theapplication has been setup in a load balancing environment. Theaspx pages thorwing the errors work normally under stress freeconditions.
The 2 distinct errors being thrown are:
1) Specified Cast is not valid
System.InvalidCastException: Specified Cast is not valid
| |
by: clintonG |
last post by:
I'm using an .aspx tool I found at but as nice as the interface is I
think I need to consider using others. Some can generate C# I understand.
Your preferences please...
<%= Clinton Gallagher
http://forta.com/books/0672325667/
|
by: rlm |
last post by:
We are working on an app developed w/ VB.net in a situation where the
developer of a particular piece of suspect code has left the company.
The section of code involves connecting to a FTP server. The code tests
for a valid response from the server.
What criteria should be used to determine if we receive a valid
response in an FTP session?
For some reason I conjecture that a method exists in a .NET library for
|
by: Christoph Schneegans |
last post by:
Hi!
I would like to announce XHTML Proxy, a service that allows more accurate
testing of XHTML documents.
<http://hixie.ch/advocacy/xhtml> states that "Sending XHTML as text/html
Considered Harmful" since "authors write XHTML that makes assumptions that
are only valid for tag soup or HTML4 UAs" and might find that the "site
breaks horribly" when they decide to "send the same content as
application/xhtml+xml".
|
by: Andrew Wan |
last post by:
I have been developing web applications with ASP & Javascript for a long
time. I have been using Visual Studio 2003.NET. While VS2003 is okay for
intellisense of ASP & Javascript, it's still not that great.
One of the cons of ASP & Javascript is that they're both interpreted, which
means one has twice the amount of work to do interms of syntax checking &
semantic/runtime checking.
Another bad thing is that ASP & Javascript doesn't have...
|
by: Matthew Fitzgibbons |
last post by:
I'm by no means a testing expert, but I'll take a crack at it.
Casey McGinty wrote:
I've never run into this.
Rule of thumb: always separate software from hardware. Write mock
classes or functions that do your hardware/file access that always
return known data (but remember to test for alpha and beta errors--make
sure both valid and invalid data are handled correctly). That way you
can test the client code that is accessing the...
|
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 usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
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 most users, this new feature is actually very convenient. If you want to control the update process,...
|
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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 launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |