f



'is not' or '!='

A newbie question to you; what is the difference between statements 
like:
  if x is not None:
and
 if x != None:

Without any context, which one should be preferred?
IMHO, the latter is more readable.
0
ElChino
8/18/2014 8:35:01 PM
comp.lang.python 77058 articles. 4 followers. Post Follow

43 Replies
2447 Views

Similar Articles

[PageSpeed] 58

On 2014-08-18 21:35, ElChino wrote:
> A newbie question to you; what is the difference between statements
> like:
>    if x is not None:
> and
>   if x != None:
>
> Without any context, which one should be preferred?
> IMHO, the latter is more readable.
>
"x == y" tells you whether x and y refer to objects that are equal.

"x is y" tells you whether x and y actually refer to the same object.

In the case of singletons like None (there's only one None object),
it's better to use "is".

0
MRAB
8/18/2014 8:53:28 PM
"ElChino" <elchino@cnn.cn>:

> A newbie question to you; what is the difference between statements
> like:
>  if x is not None:
> and
> if x != None:

Do the following: take two $10 bills. Hold one bill in the left hand,
hold the other bill in the right hand.

Now, the bill in the left hand "is not" the bill in the right hand.
However, the bill in the left hand "==" the bill in the right hand.

> Without any context, which one should be preferred?
> IMHO, the latter is more readable.

In almost all cases, both tests would result in the same behavior.
However, the "is not" test is conceptually the correct one since you
want to know if x is the one and only None object. You don't want to be
fooled by an imposter object that simply looks like the None object.
Frankly, I don't know of any other object that is "==" to the None
object except None itself, but such objects could possible exist.


Marko
0
Marko
8/18/2014 8:53:49 PM
"Marko Rauhamaa" <marko@pacujo.net> wrote:
 
> In almost all cases, both tests would result in the same behavior.
> However, the "is not" test is conceptually the correct one since you
> want to know if x is the one and only None object. You don't want to be
> fooled by an imposter object that simply looks like the None object.

Thanks for this excellent answer. "Terve, terve".
0
ElChino
8/18/2014 8:58:34 PM
On 08/18/2014 01:58 PM, ElChino wrote:
> "Marko Rauhamaa" <marko@pacujo.net> wrote:
>
>> In almost all cases, both tests would result in the same behavior.
>> However, the "is not" test is conceptually the correct one since you
>> want to know if x is the one and only None object. You don't want to be
>> fooled by an imposter object that simply looks like the None object.
>
> Thanks for this excellent answer. "Terve, terve".

I don't know what "terve, terve" means, but the "in almost all cases" is only true when talking about singletons such as 
None.

If you are not dealing with singletons (which is most cases), such as numbers, strings, lists, and most other arbitrary 
objects, you will need to use "!=" or anytime the two objects you are comparing are not the exact same object, you can 
easily get the wrong answer.

--
~Ethan~
0
Ethan
8/18/2014 9:42:24 PM
--e89a8f646fcf349b150500ee8fee
Content-Type: text/plain; charset=UTF-8

On Mon, Aug 18, 2014 at 2:42 PM, Ethan Furman <ethan@stoneleaf.us> wrote:

> If you are not dealing with singletons (which is most cases), such as
> numbers, strings, lists, and most other arbitrary objects, you will need to
> use "!=" or anytime the two objects you are comparing are not the exact
> same object, you can easily get the wrong answer.


For example, in CPython 3.4.1:
>>> (254 + 3) is 257
False
>>> (254 + 3) == 257
True
>>> ('asd' + '@sd') is 'asd@sd'
False
>>> ('asd' + '@sd') == 'asd@sd'
True

However, when testing these cases, you need to be careful due to
optimizations like smaller integer interning and string interning:

>>> (254 + 2) == 256
True
>>> (254 + 2) is 256
True
>>> ('asd' + 'sd') == 'asdsd'
True
>>> ('asd' + 'sd') is 'asdsd'
True

In each of these cases, the behavior may be different in other
implementations or versions of Python.

Chris

--e89a8f646fcf349b150500ee8fee
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable

<div dir=3D"ltr"><div class=3D"gmail_extra"><br><div class=3D"gmail_quote">=
On Mon, Aug 18, 2014 at 2:42 PM, Ethan Furman <span dir=3D"ltr">&lt;<a href=
=3D"mailto:ethan@stoneleaf.us" target=3D"_blank">ethan@stoneleaf.us</a>&gt;=
</span> wrote:<br>

<blockquote class=3D"gmail_quote" style=3D"margin:0px 0px 0px 0.8ex;border-=
left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;p=
adding-left:1ex">If you are not dealing with singletons (which is most case=
s), such as numbers, strings, lists, and most other arbitrary objects, you =
will need to use &quot;!=3D&quot; or anytime the two objects you are compar=
ing are not the exact same object, you can easily get the wrong answer.</bl=
ockquote>

</div><br>For example, in CPython 3.4.1:</div><div class=3D"gmail_extra"><d=
iv class=3D"gmail_extra">&gt;&gt;&gt; (254 + 3) is 257</div><div class=3D"g=
mail_extra">False</div><div class=3D"gmail_extra">&gt;&gt;&gt; (254 + 3) =
=3D=3D 257</div>

<div class=3D"gmail_extra">True</div><div class=3D"gmail_extra"><div class=
=3D"gmail_extra">&gt;&gt;&gt; (&#39;asd&#39; + &#39;@sd&#39;) is &#39;asd@s=
d&#39;</div><div class=3D"gmail_extra">False</div><div class=3D"gmail_extra=
">&gt;&gt;&gt; (&#39;asd&#39; + &#39;@sd&#39;) =3D=3D &#39;asd@sd&#39;</div=
>

<div class=3D"gmail_extra">True</div><div class=3D"gmail_extra"><br></div><=
div class=3D"gmail_extra">However, when testing these cases, you need to be=
 careful due to optimizations like smaller integer interning and string int=
erning:</div>

<div class=3D"gmail_extra"><br></div><div class=3D"gmail_extra"><div class=
=3D"gmail_extra">&gt;&gt;&gt; (254 + 2) =3D=3D 256</div><div class=3D"gmail=
_extra">True</div><div class=3D"gmail_extra">&gt;&gt;&gt; (254 + 2) is 256<=
/div><div class=3D"gmail_extra">

True</div></div><div class=3D"gmail_extra"><div class=3D"gmail_extra">&gt;&=
gt;&gt; (&#39;asd&#39; + &#39;sd&#39;) =3D=3D &#39;asdsd&#39;</div><div cla=
ss=3D"gmail_extra">True</div><div class=3D"gmail_extra">&gt;&gt;&gt; (&#39;=
asd&#39; + &#39;sd&#39;) is &#39;asdsd&#39;</div>

<div class=3D"gmail_extra">True</div><div class=3D"gmail_extra"><br></div><=
div class=3D"gmail_extra">In each of these cases, the behavior may be diffe=
rent in other implementations or versions of Python.</div></div></div><br c=
lear=3D"all">

<div>Chris</div>
</div></div>

--e89a8f646fcf349b150500ee8fee--
0
Chris
8/18/2014 10:04:28 PM
On 08/18/2014 03:04 PM, Chris Kaynor wrote:
> On Mon, Aug 18, 2014 at 2:42 PM, Ethan Furman wrote:
>>
>> If you are not dealing with singletons (which is most cases), such as numbers, strings, lists, and most other
>> arbitrary objects, you will need to use "!=" or anytime the two objects you are comparing are not the exact same
>> object, you can easily get the wrong answer.
>
> For example, in CPython 3.4.1:
>>>> (254 + 3) is 257
> False
>>>> (254 + 3) == 257
> True
>>>> ('asd' + '@sd') is 'asd@sd'
> False
>>>> ('asd' + '@sd') == 'asd@sd'
> True
>
> However, when testing these cases, you need to be careful due to optimizations like smaller integer interning and string
> interning:
>
>>>> (254 + 2) == 256
> True
>>>> (254 + 2) is 256
> True
>>>> ('asd' + 'sd') == 'asdsd'
> True
>>>> ('asd' + 'sd') is 'asdsd'
> True
>
> In each of these cases, the behavior may be different in other implementations or versions of Python.

But the point to remember is that, for equal objects, '==' will work, 'is' may or may not.

--
~Ethan~
0
Ethan
8/18/2014 10:19:39 PM
Ian Kelly <ian.g.kelly@gmail.com>:

> When I need to do this, I use:
>
>     SENTINEL = object()
>
> It's still a singleton, and why should a sentinel be mutable?

Private enums are often nicer in that they provide str() and repr().


Marko
0
Marko
8/19/2014 1:01:01 AM
On Tuesday, August 19, 2014 2:05:01 AM UTC+5:30, ElChino wrote:
> A newbie question to you; what is the difference between statements=20
> like:
>   if x is not None:
> and
>  if x !=3D None:

> Without any context, which one should be preferred?
> IMHO, the latter is more readable.

Here is Terry Reedy, a python-dev, from Mar 2, on this list on 'is'

| The 'is' operator has three uses, two intended and one not. In
| production code, 'is' tests that an object *is* a particular singular
| object, such as None or a sentinel instance of class object=B2. In test
| code, 'is' can also be used to test details of a particular
| implementation, such as pre-allocation of small ints. New python
| programmers also use it to confuse themselves.=20

which I would summarize by "if you are a beginner you dont want to
deal with is"=B9

As for Marko's dollar bill example:=20
I find it very plausible and still more misleading because:

1. We write computer programs because we want to understand/manipulate
something outside the computer -- 'reality'
2. The computer program never deals with that reality directly but at one
or more removes -- it handles models

eg. You go to a real-estate agent to buy an apartment and see two
plaster of paris models is his office.  Different cases may emerge:

a. The models are for two different projects -- one on the North and
one on the East side of town
b. They are two facades of the same project

OTOH the fact that there are two distinct plaster of paris objects in
the agent's office is true but mostly irrelevant.
ie if the agent says "These two ARE the same" he means they are different v=
iews=20
of the same building.
IOW python's use of the word 'is' is misleading and unfortunate=20

=B9 "... is None" is an exception -- unfortunate in my view.
Treat the 'is None' as atomic write it but and dont look inside!

=B2 Same as case 3
0
Rustom
8/19/2014 2:29:11 AM
On Mon, 18 Aug 2014 19:29:11 -0700, Rustom Mody wrote:

> On Tuesday, August 19, 2014 2:05:01 AM UTC+5:30, ElChino wrote:
>> A newbie question to you; what is the difference between statements
>> like:
>>   if x is not None:
>> and
>>  if x != None:
> 
>> Without any context, which one should be preferred? IMHO, the latter is
>> more readable.
> 
> Here is Terry Reedy, a python-dev, from Mar 2, on this list on 'is'
> 
> | The 'is' operator has three uses, two intended and one not. In 
> | production code, 'is' tests that an object *is* a particular singular
> | object, such as None or a sentinel instance of class object². In test
> | code, 'is' can also be used to test details of a particular 
> | implementation, such as pre-allocation of small ints. New python
> | programmers also use it to confuse themselves.

Hah :-)

You'll notice that use-case #2, testing implementation details, is just a 
special case of #1, testing that a value is a specific instance.


> which I would summarize by "if you are a beginner you dont want to deal
> with is"¹

In general, correct. Actually, even experts should hardly ever need to 
use `is`. And as you point out, "is None" is an exception.


> As for Marko's dollar bill example:
> I find it very plausible and still more misleading because:
[...snip example of plaster-of-paris models...]
> OTOH the fact that there are two distinct plaster of paris objects in
> the agent's office is true but mostly irrelevant. ie if the agent says
> "These two ARE the same" he means they are different views of the same
> building.
> IOW python's use of the word 'is' is misleading and unfortunate

The English word "is" is the third-person singular simple present 
indicative form of "be", quoting Wiktionary:

http://en.wiktionary.org/wiki/is#English

The word "be" (is, was, been, will be, has been, etc.) has many different 
meanings and usage, including:

- mathematical equality, "two times three is six";

- metaphorical equivalence, "he is a dumb ox";

- linking the subject to a count or measurement, "this building is 
  300 years old";

- to connect a noun to an adjective, "my shirt is wrinkled";

- to connect the subject noun to a noun or noun phrase, "she is
  a petty dictator";

- to indicate that the subject and object are the same, "Elizabeth 
  Windsor[1] is the Queen of England";

and quite a few more.

http://en.wiktionary.org/wiki/be#English


There is no requirement that the word "is" can only be used in a 
programming language if it reflects all of these meanings. After all, we 
don't expect that the jargon terms "function", "object", "class", 
"method", "procedure" as used by programming languages have *precisely* 
the same meanings as used in plain English.

A programming language is entitled to choose the meaning of its keywords, 
hopefully they would be familiar meanings not radically dissimilar from 
the normal plain English meaning (or whatever language the word is taken 
from). Hypertalk, and its descendants, use "is" as a synonym for 
equality, so that "x is 2" and "x = 2" mean exactly the same thing. 
Python, on the other hand, gives "is" a specific meaning: are the two 
operands the same instance? Although all men and women are equal, only 
one such person is Elizabeth II Queen of England.




[1] It isn't clear or obvious what the Queen[2] would use as a surname on 
the unlikely event she needed one. Even the official website of the UK 
royal family is unclear as to what Elizabeth II would use as a surname 
since her marriage. Prior to her marriage, she used "Elizabeth Windsor" 
on those rare occasions that "Princess Elizabeth" or "Queen Elizabeth II" 
was not sufficient. Her children, should they need a surname, use  
Mountbatten-Windsor. Prince William and Harry used the surname 
"Wales" (for their father's title, Prince of Wales) upon joining the 
military. The whole thing is oh so very complicated.

http://www.royal.gov.uk/ThecurrentRoyalFamily/TheRoyalFamilyname/Overview.aspx

Why do I know so much about the British royal family???


[2] Of the UK, Australia, and a few other places, but not Denmark, or any 
other place with a Queen.



-- 
Steven
0
Steven
8/19/2014 8:36:26 AM
On Tue, Aug 19, 2014 at 6:36 PM, Steven D'Aprano <steve@pearwood.info> wrote:
> Why do I know so much about the British royal family???
>
>
> [2] Of the UK, Australia, and a few other places, but not Denmark, or any
> other place with a Queen.

Possibly because British royalty is very well-defined, and can be used
to explain other, even fictional, royalty. We can examine Arendelle
and notice that, even though most Queens Consort would be addressed
equivalently to a Queen Regnant, their Queen Consort is addressed
equivalently to a princess. (She's addressed as Highness as she
embarks on her last sea voyage.)

Why do I know so much about the Arendelle royal family? Hmm.

ChrisA
0
Chris
8/19/2014 8:47:43 AM
On Mon, 18 Aug 2014 23:53:49 +0300, Marko Rauhamaa wrote:

> "ElChino" <elchino@cnn.cn>:
> 
>> A newbie question to you; what is the difference between statements
>> like:
>>  if x is not None:
>> and if x != None:
> 
> Do the following: take two $10 bills. Hold one bill in the left hand,
> hold the other bill in the right hand.
> 
> Now, the bill in the left hand "is not" the bill in the right hand.
> However, the bill in the left hand "==" the bill in the right hand.
> 
>> Without any context, which one should be preferred?
>> IMHO, the latter is more readable.
> 
> In almost all cases, both tests would result in the same behavior.
> However, the "is not" test is conceptually the correct one since you
> want to know if x is the one and only None object. You don't want to be
> fooled by an imposter object that simply looks like the None object.
> Frankly, I don't know of any other object that is "==" to the None
> object except None itself, but such objects could possible exist.
> 
> 
> Marko

Depending on context you may 'Want' 0 to be equal to none
however as far as python is concerned it is not.




-- 
"Why must you tell me all your secrets when it's hard enough to love
you knowing nothing?"
		-- Lloyd Cole and the Commotions
0
alister
8/19/2014 9:35:10 AM
Am 19.08.2014 00:04 schrieb Chris Kaynor:

> In each of these cases, the behavior may be different in other
> implementations or versions of Python.

And, the most important thing, in each of these cases, using "is" is 
semantically wrong, so no matter how different versions behave.

If you ask the wrong question, you might get a wrong answer.


Thomas
0
Thomas
8/19/2014 9:49:45 AM
Am 18.08.2014 22:53 schrieb Marko Rauhamaa:

> Frankly, I don't know of any other object that is "==" to the None
> object except None itself, but such objects could possible exist.

class ImitatingNone(object):
     def __eq__(self, other):
         return True # is equal to everything else
         return other is None # is equal only to None
         return not(other) # is equal to everything which is falsey


Pick one.

Thomas
0
Thomas
8/19/2014 9:53:04 AM
On 2014-08-19 08:36, Steven D'Aprano wrote:
> The English word "is" is the third-person singular simple present 
> indicative form of "be",

Am I the only one who feels the urge to write

  if i am some_other_object: ...
  if we are some_other_object: ...
  if u are some_other_object: ... # though txtspk bothers me

instead of using "is" for reasons of grammatical correctness?  I've
changed variable-names to avoid this on occasion. :-)

-tkc





0
Tim
8/19/2014 10:36:16 AM
2014-08-19 0:04 GMT+02:00 Chris Kaynor <ckaynor@zindagigames.com>:
>
> On Mon, Aug 18, 2014 at 2:42 PM, Ethan Furman <ethan@stoneleaf.us> wrote:
>>
>> If you are not dealing with singletons (which is most cases), such as
>> numbers, strings, lists, and most other arbitrary objects, you will need to
>> use "!=" or anytime the two objects you are comparing are not the exact same
>> object, you can easily get the wrong answer.
>
>
> For example, in CPython 3.4.1:
>>>> (254 + 3) is 257
> False
>>>> (254 + 3) == 257
> True
>>>> ('asd' + '@sd') is 'asd@sd'
> False
>>>> ('asd' + '@sd') == 'asd@sd'
> True

Now you have managed to confuse this newbie: What would a valid
"is-example" look like?


Regards,

Martin S
0
Martin
8/19/2014 12:42:34 PM
On Tue, Aug 19, 2014 at 7:42 AM, Martin S <shieldfire@gmail.com> wrote:
>> For example, in CPython 3.4.1:
>>>>> (254 + 3) is 257
>> False
>>>>> (254 + 3) == 257
>> True
>>>>> ('asd' + '@sd') is 'asd@sd'
>> False
>>>>> ('asd' + '@sd') == 'asd@sd'
>> True
>
> Now you have managed to confuse this newbie: What would a valid
> "is-example" look like?

Perhaps adding to the confusion:

>>> (4 + 3) is 7
True

The use of "is" or "is not" is the right thing to do when the object
of the comparison is known to be a singleton. That is true for None.
(I suspect it's true for True and False as well, though for historical
and idiomatic reasons "x is True" is never used.) It would also be
true if you created a sentinel object like this:

SENTINEL = []

then used it to represent "no valid value" in situations where you
can't otherwise assume some value like None is outside the domain of
values:

if mything is not SENTINEL:
    # do whatever is necessary to initialize mything
    ...

The case of "(4 + 3) is 7" simply exposes an optimization in the
implementation of integers in CPython (the small integer cache), and
*must not be relied on*.

Note that

SENTINEL = ()

would be a mistake if () is in the domain of your data, since the
empty tuple is itself a singleton. That is a CPython implementation
detail you shouldn't rely on:

>>> x = ()
>>>
>>> y = (1,2,3)
>>>
>>> z = y[0:0]
>>> z
()
>>> x
()
>>> x == z
True
>>> x is z
True

That's why the first definition of SENTINEL uses the empty list. I can
guarantee that there is no other object in the system which "is" that
particular object.

(Strings which look like identifiers are also "interned" so there is
only one copy in memory. I suspect that's why Chris's string example
included an "@" - to defeat that optimization.)

The CPython runtime is under no obligation to retain these
optimizations. Relying on them is a bug. OTOH, CPython guarantees
there is only one None object in the system.

Skip
0
Skip
8/19/2014 1:12:35 PM
On Tue, Aug 19, 2014 at 7:12 AM, Skip Montanaro <skip@pobox.com> wrote:
> The use of "is" or "is not" is the right thing to do when the object
> of the comparison is known to be a singleton. That is true for None.
> (I suspect it's true for True and False as well, though for historical
> and idiomatic reasons "x is True" is never used.) It would also be
> true if you created a sentinel object like this:
>
> SENTINEL = []

When I need to do this, I use:

    SENTINEL = object()

It's still a singleton, and why should a sentinel be mutable?
0
Ian
8/19/2014 4:42:49 PM
Skip Montanaro <skip@pobox.com>:

> The use of "is" or "is not" is the right thing to do when the object
> of the comparison is known to be a singleton.

Object identity stirs a lot of passions on this forum. I'm guessing the
reason is that it is not defined very clearly (<URL:
https://docs.python.org/3/library/functions.html#id>):

   id(object)

       Return the “identity” of an object. This is an integer which is
       guaranteed to be unique and constant for this object during its
       lifetime. Two objects with non-overlapping lifetimes may have the
       same id() value.

       CPython implementation detail: This is the address of the object
       in memory.


The "is" relation can be defined trivially through the id() function:

   X is Y iff id(X) == id(Y)

What remains is the characterization of the (total) id() function. For
example, we can stipulate that:

   X = Y
   assert(id(X) == id(Y))
   # assignment preserves identity

(assuming X and Y are not modified in other threads or signal handlers).

We know further that:

   i = id(X)
   time.sleep(T)
   assert(i == id(X))
   # the identity does not change over time

   def f(x, y):
       return id(x) == id(y)
   assert(f(X, X))
   # parameter passing preserves the identity

   def f(x):
       return x
   assert(id(f(X) == id(X)))
   # the return statement preserves the identity

   assert(id((X0, X1, ..., X)[k]) == id(Xk))
   # tuple composition and projection preserve the identity

   i = id(X)
   X.Y
   assert(i == id(X))
   # reference does not change the identity

and so on. The nice thing about these kinds of formal definitions is
that they make no metaphysical reference to "objects" or "lifetime" (or
the CPython implementation). They can also be converted into
implementation conformance statements and test cases.

A much tougher task is to define when id(X) != id(Y). After all, all of
the above would be satisfied by this implementation of id():

   def id(x):
       return 0

The nonidentity will probably have to be defined separately for each
builtin datatype. For example, for integers and strings we know only
that:

   assert(X == Y or id(X) != id(Y))
   # inequality implies nonidentity


Marko
0
Marko
8/19/2014 5:29:52 PM
On 2014-08-19 20:29, Marko Rauhamaa wrote:
> The "is" relation can be defined trivially through the id()
> function:
> 
>    X is Y iff id(X) == id(Y)
> 
> What remains is the characterization of the (total) id() function.
> For example, we can stipulate that:
> 
>    X = Y
>    assert(id(X) == id(Y))

Note that a lifetime can be less than a statement:

$ python
Python 2.7.3 (default, Mar 13 2014, 11:03:55) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> id([1,2,3]) == id([4,5,6])
True


-tkc


0
Tim
8/19/2014 5:34:00 PM
Tim Chase <python.list@tim.thechases.com>:

> Note that a lifetime can be less than a statement:
>
>>>> id([1,2,3]) == id([4,5,6])
> True

Duly noted.


Marko
0
Marko
8/19/2014 6:18:07 PM
Marko Rauhamaa wrote:

> Skip Montanaro <skip@pobox.com>:
> 
>> The use of "is" or "is not" is the right thing to do when the object
>> of the comparison is known to be a singleton.
> 
> Object identity stirs a lot of passions on this forum. I'm guessing the
> reason is that it is not defined very clearly (<URL:
> https://docs.python.org/3/library/functions.html#id>):

Identity is defined very clearly. As you just quoted:

>    id(object)
> 
>        Return the “identity” of an object. This is an integer which is
>        guaranteed to be unique and constant for this object during its
>        lifetime. Two objects with non-overlapping lifetimes may have the
>        same id() value.

Python identity is represented by an integer, and it is guaranteed to be
unique and constant for the lifetime of the object. It may or may not be
reused once the object no longer exists. That's all you need to know about
identity; that's *all there is to know* about identity in Python.

[Actually, to be pedantic, one also needs to state that the objects have to
be part of a single Python process. Object X in one process, and object Y
in another process, may have the same id() but still be considered
distinct.]


>        CPython implementation detail: This is the address of the object
>        in memory.

I really wish CPython didn't do that, or at least not admit to it. It does
nothing but confuse people.


> The "is" relation can be defined trivially through the id() function:
> 
>    X is Y iff id(X) == id(Y)

Except that id() is a built-in function and can be shadowed or
monkey-patched, while the `is` operator is a keyword and cannot be. But
apart from that minor point, I agree.

 
> What remains is the characterization of the (total) id() function. For
> example, we can stipulate that:
> 
>    X = Y
>    assert(id(X) == id(Y))
>    # assignment preserves identity

That's not a property of identity. That's a property of *assignment*. So you
cannot use that fact to define identity in Python, since there could be
another language with the *exact* same definition of identity but that does
copy-on-assignment instead.


> (assuming X and Y are not modified in other threads or signal handlers).
> 
> We know further that:
> 
>    i = id(X)
>    time.sleep(T)
>    assert(i == id(X))
>    # the identity does not change over time

That would be the part of the definition that says the identity is constant.

 
>    def f(x, y):
>        return id(x) == id(y)
>    assert(f(X, X))
>    # parameter passing preserves the identity

Again, that's not a property of identity. There could be a language just
like Python in all respects, including identity, except that parameters are
passed by value.


[snip more examples of things which tell us nothing about identity]


> The nice thing about these kinds of formal definitions is 
> that they make no metaphysical reference to "objects" or "lifetime" (or
> the CPython implementation).

They are not metaphysical. They are concrete. You cannot understand the
semantics of identity in Python without understanding Python's execution
model. Python's execution model contains objects (which are not
metaphysical woo, but a concrete computer science data structure), and
identity in Python is defined in terms of objects. Not values, or names, or
namespaces, but objects.


> They can also be converted into
> implementation conformance statements and test cases.

True, but in most of the examples you show, they will be tests of some other
aspect of Python, e.g. that assignment (name binding) preserves identity.
They don't help us understand identity, because there are other models for
assignment, and there are an infinite number of things which could also be
preserved by assignment but aren't identity.

E.g. "the number of zero bits in the object struct".


> A much tougher task is to define when id(X) != id(Y). After all, all of
> the above would be satisfied by this implementation of id():
> 
>    def id(x):
>        return 0

That fails the definition given, that identities are *unique*.

Defining non-identity for objects that exist simultaneously is simple:

id(X) != id(Y) iff not (X is Y)

We don't have good notation for discussing objects which exist at different
times, but we can fake it with the rule:

"if either X or Y or both raise NameError, then we deem `X is Y` to be
false"

 
> The nonidentity will probably have to be defined separately for each
> builtin datatype. 

That is incorrect. See below.

> For example, for integers and strings we know only  
> that:
> 
>    assert(X == Y or id(X) != id(Y))
>    # inequality implies nonidentity

That tells us something about string equality. It tells us nothing about
identity.

Python's concept of identity applies equally to all types. Read the
definition again: it refers to objects, but without caring about the type
of objects. Let's just consider two types:

str:
    assert (X == Y or id(X) != id(Y)) always passes

float:
    assert (X == Y or id(X) != id(Y)) sometimes fails

Proof of the second case:

py> X = Y = float('nan')
py> assert (X == Y or id(X) != id(Y))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

This demonstrates that the condition

    (X == Y or id(X) != id(Y))

fails to tell us anything useful about identity, since it is sometimes true
and sometimes false.

You cannot understand identity from first principles, precisely because it
is not a metaphysical concept in Python. In Python it is defined by and in
terms of the concrete programming model of the language.



-- 
Steven

0
Steven
8/19/2014 6:26:50 PM
On Tue, Aug 19, 2014 at 11:42 AM, Ian Kelly <ian.g.kelly@gmail.com> wrote:
> When I need to do this, I use:
>
>     SENTINEL = object()
>
> It's still a singleton, and why should a sentinel be mutable?

Old habits die hard, I guess. I've been using Python since long before
object() existed. :-)

Skip
0
Skip
8/19/2014 6:44:31 PM
Steven D'Aprano <steve+comp.lang.python@pearwood.info>:

> Python identity is represented by an integer, and it is guaranteed to
> be unique and constant for the lifetime of the object. It may or may
> not be reused once the object no longer exists. That's all you need to
> know about identity; that's *all there is to know* about identity in
> Python.
>
> [...]
>
> They are not metaphysical. They are concrete. You cannot understand the
> semantics of identity in Python without understanding Python's execution
> model.

That's circular reasoning. When you are defining Python's execution
model, you can't refer back to Python's execution model.

For a good example of what I'm after, take a look how Java specifies its
crucial happens-before relation:

   <URL:
   http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.5>


Marko
0
Marko
8/19/2014 6:52:15 PM
On 19/08/2014 19:26, Steven D'Aprano wrote:
> Marko Rauhamaa wrote:
>
>>         CPython implementation detail: This is the address of the object
>>         in memory.
>
> I really wish CPython didn't do that, or at least not admit to it. It does
> nothing but confuse people.
>

I agree and would happily support your issue on the bug tracker to get 
it deleted from the docs :)

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

0
Mark
8/19/2014 7:05:04 PM
Marko Rauhamaa <marko@pacujo.net>:

> That's circular reasoning. When you are defining Python's execution
> model, you can't refer back to Python's execution model.
>
> For a good example of what I'm after, take a look how Java specifies its
> crucial happens-before relation:
>
>    <URL:
>    http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.5>

However, Java does *not* do a particularly good job defining object
identity (<URL:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.21.3>):

   At run time, the result of == is true if the operand values are both
   null or both refer to the same object or array; otherwise, the result
   is false.

   The result of != is false if the operand values are both null or both
   refer to the same object or array; otherwise, the result is true.

For a more worthy attempt, we'll have to take a look at Scheme (<URL:
http://www.scheme.com/tspl2d/objects.html>):

   * Two objects of different types (booleans, the empty list, pairs,
     numbers, characters, strings, vectors, symbols, and procedures) are
     distinct. The Revised4 Report (but not the ANSI/IEEE standard)
     permits one exception to this rule: the empty list and the boolean
     #f may be identical.

   * Two objects of the same type with different contents or values are
     distinct.

   * The boolean object #t is identical to itself wherever it appears,
     and #f is identical to itself wherever it appears, but #t and #f
     are distinct.

   * The empty list () is identical to itself wherever it appears.

   * Two symbols (created by read or by string->symbol) are identical if
     and only if they have the same name (by string=?).

   * A quoted pair, vector, or string is identical to itself, as is a
     pair, vector, or string created by an application of cons, vector,
     string, etc. Two pairs, vectors, or strings created by different
     applications of cons, vector, string, etc., are distinct. One
     consequence is that cons, for example, may be used to create a
     unique object distinct from all other objects.

   * Two procedures that may behave differently are distinct. A
     procedure created by an evaluation of a lambda expression is
     identical to itself. Two procedures created by the same lambda
     expression at different times, or by similar lambda expressions,
     may or may not be identical.


Marko
0
Marko
8/19/2014 9:00:22 PM
On Tue, Aug 19, 2014 at 3:00 PM, Marko Rauhamaa <marko@pacujo.net> wrote:
> For a more worthy attempt, we'll have to take a look at Scheme (<URL:
> http://www.scheme.com/tspl2d/objects.html>):

Those are invariants, not a definition.  The actual definition is
found in the paragraph above:

"In most Scheme systems, two objects are considered identical if they
are represented internally by the same pointer value and distinct (not
identical) if they are represented internally by different pointer
values, although other criteria, such as time-stamping, are possible."

In other words, object identity in Scheme is also established by an
integer that may or may not correspond to a memory address. How is
this any different from Python's definition?
0
Ian
8/19/2014 10:21:41 PM
On 8/19/2014 3:05 PM, Mark Lawrence wrote:
> On 19/08/2014 19:26, Steven D'Aprano wrote:
>> Marko Rauhamaa wrote:
>>
>>>         CPython implementation detail: This is the address of the object
>>>         in memory.
>>
>> I really wish CPython didn't do that, or at least not admit to it. It
>> does
>> nothing but confuse people.
>>
>
> I agree and would happily support your issue on the bug tracker to get
> it deleted from the docs :)

It was added to the docs because people noticed that CPython ids looked 
like addresses and assumed incorrectly that this is a language property. 
  In other words, the point is not to say that CPython uses addresses - 
people already know or discover that, but to say that the addresses are 
*only* implementation detail.

That said, I agree that it unfortunately *does* unnecessarily inform 
people who do not know that and probably confuses some who do not 
understand why they are being told something they don't need to know. We 
could discuss alternatives here.

-- 
Terry Jan Reedy

0
Terry
8/19/2014 10:23:37 PM
Ian Kelly <ian.g.kelly@gmail.com>:

> On Tue, Aug 19, 2014 at 3:00 PM, Marko Rauhamaa <marko@pacujo.net> wrote:
>> For a more worthy attempt, we'll have to take a look at Scheme (<URL:
>> http://www.scheme.com/tspl2d/objects.html>):
>
> Those are invariants, not a definition.  The actual definition is
> found in the paragraph above:
>
> "In most Scheme systems, two objects are considered identical if they
> are represented internally by the same pointer value and distinct (not
> identical) if they are represented internally by different pointer
> values, although other criteria, such as time-stamping, are possible."
>
> In other words, object identity in Scheme is also established by an
> integer that may or may not correspond to a memory address. How is
> this any different from Python's definition?

"In most Scheme systems" is similar to the CPython sidenote. The
"invariants" might not form a complete axiom system but are a step in
that direction.

When Peano Arithmetic posits (<URL:
http://en.wikipedia.org/wiki/Peano_axioms#Addition>):
   
   a + 0 = a
   a + b' = (a + b)'

we usually take that to be the definition of addition in the system.

The true Scheme standard appeals to the "invariants" (<URL:
http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.ht
ml#%_sec_6.1>):

    The eqv? procedure defines a useful equivalence relation on objects.
    Briefly, it returns #t if obj1 and obj2 should normally be regarded
    as the same object. This relation is left slightly open to
    interpretation, but the following partial specification of eqv?
    holds for all implementations of Scheme.

    The eqv? procedure returns #t if:

       obj1 and obj2 are both #t or both #f.

       obj1 and obj2 are both symbols and

       (string=? (symbol->string obj1)
                 (symbol->string obj2))
                   ===>  #t

    [...]


Marko
0
Marko
8/19/2014 11:02:33 PM
Tim Chase <python.list@tim.thechases.com> writes:

> Am I the only one who feels the urge to write
>
>   if i am some_other_object: ...
>   if we are some_other_object: ...
>   if u are some_other_object: ... # though txtspk bothers me

How often do you need to refer to an object with personal pronouns? I
think for me the answer is “never”. Why not name the specific role the
object is playing, rather than the indirectness of personal pronouns?

So, in short: you may not be the only one, but I find it difficult to
imagine why anyone would be motivated to do that.

-- 
 \      “When I was born I was so surprised I couldn't talk for a year |
  `\                                        and a half.” —Gracie Allen |
_o__)                                                                  |
Ben Finney

0
Ben
8/19/2014 11:24:00 PM
On Wednesday, August 20, 2014 4:54:00 AM UTC+5:30, Ben Finney wrote:
> Tim Chase writes:

> > Am I the only one who feels the urge to write
> >   if i am some_other_object: ...
> >   if we are some_other_object: ...
> >   if u are some_other_object: ... # though txtspk bothers me

> How often do you need to refer to an object with personal pronouns? I
> think for me the answer is "never". Why not name the specific role the
> object is playing, rather than the indirectness of personal pronouns?

> So, in short: you may not be the only one, but I find it difficult to
> imagine why anyone would be motivated to do that.

If you've taught beginners its not so surprising -- 
Ive heard all kinds of
- I go here
- I try this again
- I come back

where that 'I' is some procedure/program-counter-ish notion
and the listener is supposed to figure out what exactly the speaker is
(currently) identifying with :-)

Ive never heard 'we-s' and 'u-s' though

I also (once!) had a student who started every single variable/function/filename
with his name!!
0
Rustom
8/20/2014 4:01:49 AM
On Tue, 19 Aug 2014 21:01:49 -0700, Rustom Mody wrote:

> I also (once!) had a student who started every single
> variable/function/filename with his name!!

I recall somebody on the Python tutor mailing list doing that. They did 
so because their course instructor made it a requirement and failed 
anyone who didn't.

No reason was given, according to the student, but I imagine that the 
instructor was trying to teach them "best practice" *cough* for multi-
user projects, so you can identify who first created each function or 
variable.


from guidosys import guidoversion; guidoprint(guidoversion)-ly yr's,

-- 
Steven
0
Steven
8/20/2014 4:59:13 AM
On Wednesday, August 20, 2014 10:29:13 AM UTC+5:30, Steven D'Aprano wrote:
> On Tue, 19 Aug 2014 21:01:49 -0700, Rustom Mody wrote:

> > I also (once!) had a student who started every single
> > variable/function/filename with his name!!

> I recall somebody on the Python tutor mailing list doing that. They did 
> so because their course instructor made it a requirement and failed 
> anyone who didn't.

> No reason was given, according to the student, but I imagine that the 
> instructor was trying to teach them "best practice" *cough* for multi-
> user projects, so you can identify who first created each function or 
> variable.

It is interesting (and insidious) how technology shapes our thinking
patterns.  Before git, such tracking could be a headache.  Things like
git blame give an automated list 'blaming' each line on its
perpetrator.

Likewise when teaching (with) C it was immoral behaviour to not match
malloc and free, file-open and close.
Today the first is impossible and the second is unnecessary and wasteful
0
Rustom
8/20/2014 5:25:47 AM
Rustom Mody wrote:

> It is interesting (and insidious) how technology shapes our thinking
> patterns.  Before git, 

Pardon me, but git did not invent revision control. There are dozens of
revision control software applications, including:

Mercurial: released April 2005
Git: released April 2005
GNU Bazaar: released March 2005
Subversion: 2000
Clearcase: 1992
CVS: 1990

Even venerable old cvs tracked authors.


> such tracking could be a headache.  Things like 
> git blame give an automated list 'blaming' each line on its
> perpetrator.
> 
> Likewise when teaching (with) C it was immoral behaviour to not match
> malloc and free, file-open and close.
> Today the first is impossible and the second is unnecessary and wasteful

If you're talking about Python, in the second case you're mistaken. Although
it is not *compulsory* to close files in Python, since the garbage
collector will eventually do so for you, it is considered good practice to
do so. Generally it is considered best to use a `with open(...) as f`
block, and Python will automatically close the file as soon as the block is
left, but manually calling f.close() is still an option.


-- 
Steven

0
Steven
8/20/2014 11:05:42 AM
On Wed, Aug 20, 2014 at 9:05 PM, Steven D'Aprano
<steve+comp.lang.python@pearwood.info> wrote:
> Rustom Mody wrote:
>
>> It is interesting (and insidious) how technology shapes our thinking
>> patterns.  Before git,
>
> Pardon me, but git did not invent revision control. There are dozens of
> revision control software applications, including:
>
> Mercurial: released April 2005
> Git: released April 2005
> GNU Bazaar: released March 2005
> Subversion: 2000
> Clearcase: 1992
> CVS: 1990
>
> Even venerable old cvs tracked authors.

That's true, but how easy is it to annotate a file with each line's
author (or, at least, to figure out who wrote some particular line of
code)? It's easy enough with 'git blame' or 'hg blame', and it
wouldn't surprise me if bzr had a similar feature; but that's all the
current generation of version control systems. I don't think cvs or
svn offered that kind of feature. Sure it's possible in theory - the
information is all there - but if you can't pull it up when you want
it, it's not that helpful.

Personally, I like to just edit the line of code (add a character or
something), save the file, then pull up gitk and look at "Unstaged
Changes", from which I can right-click and say "Show origin of this
line". Much faster than a full 'git blame'.

ChrisA
0
Chris
8/20/2014 11:17:10 AM
On 2014-08-20 21:17, Chris Angelico wrote:
> That's true, but how easy is it to annotate a file with each line's
> author (or, at least, to figure out who wrote some particular line
> of code)? It's easy enough with 'git blame' or 'hg blame', and it
> wouldn't surprise me if bzr had a similar feature; but that's all
> the current generation of version control systems. I don't think
> cvs or svn offered that kind of feature.

Just for the record, at least SVN has "svn blame" which will annotate
with the committer's name/id.  I use it all the time at $DAYJOB.  I've
managed to avoid CVS, so I can't speak to that.

-tkc


0
Tim
8/20/2014 11:26:43 AM
On Wed, Aug 20, 2014 at 9:26 PM, Tim Chase
<python.list@tim.thechases.com> wrote:
> On 2014-08-20 21:17, Chris Angelico wrote:
>> That's true, but how easy is it to annotate a file with each line's
>> author (or, at least, to figure out who wrote some particular line
>> of code)? It's easy enough with 'git blame' or 'hg blame', and it
>> wouldn't surprise me if bzr had a similar feature; but that's all
>> the current generation of version control systems. I don't think
>> cvs or svn offered that kind of feature.
>
> Just for the record, at least SVN has "svn blame" which will annotate
> with the committer's name/id.  I use it all the time at $DAYJOB.  I've
> managed to avoid CVS, so I can't speak to that.
>

Ah, was not aware of that. But my usage of svn has been pretty minimal
(just basic cloning of a repo and such; I think I started svn'ing one
project at one point, got to maybe four revisions, and then the
project stagnated for long enough that I met git), and my cvs even
less so (I cloned exactly one repo, then ran into difficulties, asked
on the mailing list about compiling the version from cvs, and after a
few exchanges, someone said "Wait... when you say cvs, do you
literally mean cvs? We moved to git a little while ago, that's now out
of date" and I moved to git forthwith), so I have no experience with
even slightly advanced tools.

ChrisA
0
Chris
8/20/2014 11:33:50 AM
On 2014-08-20 12:26, Tim Chase wrote:
> On 2014-08-20 21:17, Chris Angelico wrote:
>> That's true, but how easy is it to annotate a file with each line's
>> author (or, at least, to figure out who wrote some particular line
>> of code)? It's easy enough with 'git blame' or 'hg blame', and it
>> wouldn't surprise me if bzr had a similar feature; but that's all
>> the current generation of version control systems. I don't think
>> cvs or svn offered that kind of feature.
>
> Just for the record, at least SVN has "svn blame" which will annotate
> with the committer's name/id.  I use it all the time at $DAYJOB.  I've
> managed to avoid CVS, so I can't speak to that.

cvs annotate

http://compbio.soe.ucsc.edu/cvsdoc/cvs-manual/cvs_74.html

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

0
Robert
8/20/2014 11:40:03 AM
On Wednesday, August 20, 2014 4:35:42 PM UTC+5:30, Steven D'Aprano wrote:
> Rustom Mody wrote:

> > It is interesting (and insidious) how technology shapes our thinking
> > patterns.  Before git, 

> Pardon me, but git did not invent revision control. There are dozens of
> revision control software applications, including:

> Mercurial: released April 2005
> Git: released April 2005
> GNU Bazaar: released March 2005
> Subversion: 2000
> Clearcase: 1992
> CVS: 1990

> Even venerable old cvs tracked authors.

Ok I was mistaken -- only remembering from rcs where one had to put
a 'cookie' containing rcs-variables that would be substituted.

Which variables you put would decide which pieces of info were
available; the info was in-band, if at all.  Nowadays its all there, its
out-of-band and the natural usage therefore is different.
0
Rustom
8/20/2014 12:01:12 PM
On Wednesday, August 20, 2014 2:30:22 AM UTC+5:30, Marko Rauhamaa wrote:

> For a more worthy attempt, we'll have to take a look at Scheme (<URL:
> http://www.scheme.com/tspl2d/objects.html>):

Since you brought up scheme, here is a discussion going on right now
on the Haskell list:

http://www.haskell.org/pipermail/haskell-cafe/2014-August/115659.html
[The lingo is of course different]

In summary it runs thus:
OP asks for 'is' (Haskell has no equivalent of 'is')

Almost all the answers explain why its a bad idea
0
Rustom
8/21/2014 5:03:35 AM
Rustom Mody <rustompmody@gmail.com>:

> OP asks for 'is' (Haskell has no equivalent of 'is')
>
> Almost all the answers explain why its a bad idea

Well, I don't think it is a bad idea in and of itself, but if you don't
have it, you don't have to define it.

Object identity does make you look under the skin. In Python, it is
necessary even without id() or *is* since you have to understand why

   >>> a = []
   >>> b = a
   >>> b.append(0)
   >>> a
   [0]

Exposing object identity is a consequence of allowing mutable objects.


Marko
0
Marko
8/21/2014 5:56:08 AM
Am 20.08.2014 13:17 schrieb Chris Angelico:

> That's true, but how easy is it to annotate a file with each line's
> author (or, at least, to figure out who wrote some particular line of
> code)? It's easy enough with 'git blame' or 'hg blame', and it
> wouldn't surprise me if bzr had a similar feature; but that's all the
> current generation of version control systems. I don't think cvs or
> svn offered that kind of feature.

$ LANG=C svn help blame
blame (praise, annotate, ann): Output the content of specified files or
URLs with revision and author information in-line.
usage: blame TARGET[@REV]...

$ cvs help
Unknown command: `help'

CVS commands are:
         add          Add a new file/directory to the repository
         admin        Administration front end for rcs
         annotate     Show last revision where each line was modified
[...]

IMHO annotate does the same what blame does on other VCS.


Thomas
0
Thomas
8/21/2014 6:31:06 PM
On Mon, Aug 18, 2014 at 1:35 PM, ElChino <elchino@cnn.cn> wrote:
> A newbie question to you; what is the difference between statements like:
>  if x is not None:
> and
> if x != None:
>
> Without any context, which one should be preferred?
> IMHO, the latter is more readable.

You've got some good answers.

I'd like to point out that this might make a good entry in a Python FAQ list...
0
Dan
8/21/2014 7:24:12 PM
"Dan Stromberg" <drsalists@gmail.com> wrote:

> You've got some good answers.

I've counted around 210 messages in this thread!!

> I'd like to point out that this might make a good entry in a Python FAQ list...

Ok.
0
ElChino
8/21/2014 7:42:14 PM
Reply:

Similar Artilces:

'^=' and '~='?
Hello, What is the difference between '^=' and '~='? Thanks, Duckhye ...

'''''''''''''The Running Update/Append Queries Using VBA code Ordeal''''''''''''''
Hello fellow programmers, I am trying to run an append/update query from code, a command button on a form initiates the queries. the format i am using is; _____________________________________________________ SELECT "criteria" FROM "criteria" WHERE "criteria" UPDATE/APPEND "field selections" RecordSource "qryExample" = above text strings" _______________________________________________________________________ When i am running a SELECT query in this manner it works fine with no problems, and accepts the values of specified linked for...

'''''''''''''The Running Update/Append Queries Using VBA code Ordeal'''''''''''''' #2
Hi, Thanks for ur help there HJ. I know how to do the tasks you specified there. I would like for the update query to use field values from some of the fields on the form (frmInvoices) such as InvoiceNumber, DateFrom, DateTo. My problem is that an append/update query can't find the values in the open Form (frmInvoices) when I specify them as; [Forms]![frmInvoices]![InvoiceNumber] a select query has no problem finding the field values on a form. please help. Aaron Hi Aaron, Could you post the entire code that you are having trouble with? Now it is not possible to see what goes wron...

if str_mo not in ('','.') and str_da not in ('','.') and str_yy not in ('','.') Any shorter ?
Hi, there. =20 I'm just curious if it ever dawned on anybody how to abbreviate this line : if str_mo not in ('','.') and str_da not in ('','.') and str_yy not in ('','.')=20 =20 Igor Kurbeko Clinical Programmer Analyst 678 336 4328 ikurbeko@atherogenics.com =20 no brain no pain =20 how about: if not (str_mo in ('','.') or str_da in ('','.') or str_yy in ('','.')) OR if not (missing(str_mo) or missing(str_da) or missing(str_yy)) Eric On 22 Oct 03 21:13:37 GMT, ikurbeko@ATHER...

A function with 'and' , 'not' , 'null' , 'car' and 'cdr'
What's this ? (defun enigma (x) (and (not (null x)) (or (null (car x)) (enigma (cdr x))))) "I suppose I should learn Lisp, but it seems so foreign." - Paul Graham, Nov 1983 On Wed, Oct 07 2015, CAI GENGYANG wrote: > What's this ? > > > (defun enigma (x) > (and (not (null x)) > (or (null (car x)) > (enigma (cdr x))))) Bad taste? It returns T if the list X contains nil as an element. It would be clearer to write (some #'null x). Helmut CAI GENGYANG ...

which is more 'pythonic' / 'better' ?
hi, there are 2 versions of a simple code. which is preferred? === if len(line) >= (n+1): text = line[n] else: text = 'nothing' === === try: text = line[n] except IndexError: text = 'nothing' === which is the one you would use? thanks, gabor gabor wrote: > hi, > > there are 2 versions of a simple code. > which is preferred? > > > === > if len(line) >= (n+1): > text = line[n] > else: > text = 'nothing' > === > > > === > try: > text = line[n] > except IndexError: > text = '...

Re: if str_mo not in ('','.') and str_da not in ('','.') and str_yy not in ('','.') Any shorter ?
OR you could use ARRAY data new; set old; array igor $ (*) str_mo str_da str_yr; do over igor; if igor ~in (' ','.') then do; end; run; Prasad Ravi Igor Kurbeko <ikurbeko@ATHEROGENIC To: SAS-L@LISTSERV.UGA.EDU S.COM> cc: Sent by: "SAS(r) Subject: if str_mo not in ('','.') and str_da not in ('','.') and str_yy ...

error: expected '=', ',', ';', 'asm' or '__attrib
Hi I'm trying to compile an ADC Driver & come acrosss the following error. I've no experience writing drivers before, and hence have no clue how to fix it. Hope someone out there has encountered the problem & suggesst a fix for the same. The Error is I get is : qadc.c: At top level: qadc.c:97: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'qadc_read' make: *** [qadc.o] Error 1 [root@localhost qadc]# ########################################################################### ADC Driver Code ##...

error: expected '=', ',', ';', 'asm' or '__attrib
Hi I'm trying to compile an ADC Driver & come acrosss the following error. I've no experience writing drivers before, and hence have no clue how to fix it. Hope someone out there has encountered the problem & suggesst a fix for the same. The Error is I get is : qadc.c: At top level: qadc.c:97: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'qadc_read' make: *** [qadc.o] Error 1 [root@localhost qadc]# ########################################################################### ADC Driver Code ####################...

replacement for '{' and '}' ?
I am still playing around with what kind of syntax I would like to mark up my documents. Are there equivalent long substitutes for { and } when they are not used to describe arguments to functions? Something like \begin{group} and \end{group}. In other words, if I could force myself to write, say, \begin{group} \it ... \end{group} instead of {\it ... }, then I believe I could identify from the markup context what is an argument that belongs to a just invoked macro and what is text. {Of course, in this context, \textit{...} would be better.} No more ambiguity whether a in \myfunction{a} i...

logical to 'on' / 'off'
Hi, is there a function implemented doing this conversion? my Problem is, that I want to use the following code: set(handles.edit_curr_trq_sl,'Enable',get(hObject,'Value')) where get(hObject,'Value') gives the state of a checkbox thank you! function [str]=tf2oo(logic) switch logic case 0 str='off'; case 1 str='on'; end%switch end%function tf2oo() while i do not know a built in function, I use my own:) meisterbartsch wrote: > > > function [str]=tf2oo(logic) > switch logic > case 0 > str='off'; &g...

Replacing ',' with '.'
Hello, I have a huge amount of numbers in a .txt file. The numbers are in the form 2,43252e+1. I need to replace the , with . How should I do this? I'd prefer some import method that does this during the import procedure. -Janne Hi, I guess you import the data as text and convert it then to numbers. Try 'strrep' before you convert the text to numbers. Tobias Jake the Snake schrieb: > Hello, > > I have a huge amount of numbers in a .txt file. The numbers are in the form 2,43252e+1. I need to replace the , with . How should I do this? I'd prefer some import method...

replacing '/' with '\\'
I have a MKS ksh shell script running on a Windows box. In some scripts I have to convert a UNIX filename into a DOS filename, that is replace the '/' with '\\'. For example, replace /opt/siips/archive/text.dat with \\opt\\siips\\archive\\text.dat. I've tried using sed like $FILE='echo $FILE|sed "s/\//\\\/g"' which got me \opt\siips\archive\text.dat. It's close but I still need the second \. Does anyone have any suggestion? Or tell me where I've gone wrong? Thanks -- Steffen On 9 Dec 2004 20:14:21 -0800, sajohn52@yahoo.com <sajohn52@yahoo....

Re: '^=' and '~='?
Duckhye, According to the doc ( http://xrl.us/befwjx ) they, and one other set of characters, and the mnemonic 'NE' all represent 'NOT EQUAL'. Art ------- On Wed, 11 Feb 2009 16:52:40 -0600, Duck-Hye Yang <dyang@CHAPINHALL.ORG> wrote: >Hello, >What is the difference between '^=' and '~='? > >Thanks, >Duckhye ...

Web resources about - 'is not' or '!=' - comp.lang.python

Resources last updated: 2/7/2016 9:01:55 AM