Login | Register For Free | Help
Search for: (Advanced)

Mailing List Archive: Python: Python

Python Basic Doubt

 

 

First page Previous page 1 2 Next page Last page  View All Python python RSS feed   Index | Next | Previous | View Threaded


i.am.songoku at gmail

Aug 10, 2013, 8:33 AM

Post #1 of 31 (63 views)
Permalink
Python Basic Doubt

Hi Fellow Python Friends,

I am new to Python and recently subscribed to the mailing list.I have a
doubt regarding the basics of Python. Please help me in understanding the
below concept.

So doubt is on variables and their contained value.

Why does in the below example from Interpreter exploration value of c take
pre existing memory location.

>>> a=10
>>> id(a)
21665504
>>> b=a
>>> id(b)
21665504
>>> c=10
>>> id(c)
21665504

I am actually assigning new value to c. But from the value of id() all
three variables take same location. With variables a and b it is ok. But
why c taking the same location?

Regards,
Krishnan


roy at panix

Aug 10, 2013, 9:35 AM

Post #2 of 31 (61 views)
Permalink
Re: Python Basic Doubt [In reply to]

In article <mailman.428.1376151419.1251.python-list [at] python>,
Krishnan Shankar <i.am.songoku [at] gmail> wrote:

> Hi Fellow Python Friends,
>
> I am new to Python and recently subscribed to the mailing list.I have a
> doubt regarding the basics of Python. Please help me in understanding the
> below concept.
>
> So doubt is on variables and their contained value.
>
> Why does in the below example from Interpreter exploration value of c take
> pre existing memory location.
>
> >>> a=10
> >>> id(a)
> 21665504
> >>> b=a
> >>> id(b)
> 21665504
> >>> c=10
> >>> id(c)
> 21665504

Python doesn't really expose anything about memory locations. The fact
that id() returns something which looks like it might be a memory
location is purely a detail of the particular implementation you're
using.

The next thing to understand is that python doesn't have variables. It
has objects and names which are bound to those objects. So, what's
happening in your example is:

1) a = 10

You're creating an integer object with the value 10, and binding the
name "a" to that object.

2) b = a

You're binding another name, "b" to the same object that "a" is bound to.

3) c = 10

This is the tricky one. You're using 10 again as a literal, and the
interpreter is reusing the same existing (interned) integer object, and
binding yet another name, "c" to it. This part is implementation
dependent. Nothing says Python must intern integer literals, it's
entirely free to create a new integer object every time you utter 10 in
your source code.
--
http://mail.python.org/mailman/listinfo/python-list


python.list at tim

Aug 10, 2013, 9:40 AM

Post #3 of 31 (61 views)
Permalink
Re: Python Basic Doubt [In reply to]

On 2013-08-10 21:03, Krishnan Shankar wrote:
> >>> a=10
> >>> id(a)
> 21665504
> >>> b=a
> >>> id(b)
> 21665504
> >>> c=10
> >>> id(c)
> 21665504
>
> I am actually assigning new value to c. But from the value of id()
> all three variables take same location. With variables a and b it
> is ok. But why c taking the same location?

As an internal optimization, CPython caches small integer values

>>> a = 256
>>> b = 256
>>> a is b
True
>>> a = 257
>>> b = 257
>>> a is b
False

Because it's an internal implementation detail, you shouldn't count
on this behavior (Jython or Cython or IronPython may differ; or
future versions of Python may cache a different range of numbers).

Generally, if you are using the "is" operator to compare against
anything other than None, you're doing it wrong. There are exceptions
to this, but it takes knowing the particulars.

-tkc



--
http://mail.python.org/mailman/listinfo/python-list


rosuav at gmail

Aug 10, 2013, 9:42 AM

Post #4 of 31 (61 views)
Permalink
Re: Python Basic Doubt [In reply to]

On Sat, Aug 10, 2013 at 4:33 PM, Krishnan Shankar
<i.am.songoku [at] gmail> wrote:
> Hi Fellow Python Friends,
>
> I am new to Python and recently subscribed to the mailing list.I have a
> doubt regarding the basics of Python. Please help me in understanding the
> below concept.
>
> So doubt is on variables and their contained value.

Tangential to this: Python doesn't have "variables" that "contain"
anything, but rather has names that are bound to (point to, if you
like) objects. You're mostly right, this is just a terminology point.

> Why does in the below example from Interpreter exploration value of c take
> pre existing memory location.
>
>>>> a=10
>>>> id(a)
> 21665504
>>>> b=a
>>>> id(b)
> 21665504
>>>> c=10
>>>> id(c)
> 21665504
>
> I am actually assigning new value to c. But from the value of id() all three
> variables take same location. With variables a and b it is ok. But why c
> taking the same location?

CPython caches a number of integer objects for efficiency. Whenever
you ask for the integer 10, you'll get the _same_ integer 10. But if
you try the same exercise with a much higher number, or with a
different value, you should get a unique id.

With immutable literals, the interpreter's allowed to reuse them. You
don't normally care about the id() of an integer, and nor should you.
Same goes for strings; the interpreter's allowed to intern them if it
chooses. Generally, don't assume that they're different, don't assume
they're the same either.

ChrisA
--
http://mail.python.org/mailman/listinfo/python-list


tjreedy at udel

Aug 10, 2013, 10:44 AM

Post #5 of 31 (55 views)
Permalink
Re: Python Basic Doubt [In reply to]

On 8/10/2013 11:33 AM, Krishnan Shankar wrote:
> Hi Fellow Python Friends,
>
> I am new to Python and recently subscribed to the mailing list.I have a
> doubt regarding the basics of Python. Please help me in understanding
> the below concept.
>
> So doubt is on variables and their contained value.

It would be better English to say that you have a 'question' or even
'confusion', rather than a 'doubt'. From your subject line, I got the
impression that you doubted that you should learn or use Python. That
clearly is not what you meant.

--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


jarabal at gmail

Aug 10, 2013, 11:00 AM

Post #6 of 31 (56 views)
Permalink
Re: Python Basic Doubt [In reply to]

Hello,

El 10/08/2013 18:40, Tim Chase escribió:
> Generally, if you are using the "is" operator to compare against
> anything other than None, you're doing it wrong. There are exceptions
> to this, but it takes knowing the particulars.

Now I have one doubt, I use 'is' to compare basic types in python 3, for example .-

v = []
if type(v) is list:
print('Is list...')

Because I think it is more clear and faster than .-
type(v) == [].__class__ ... or ... isinstance(v, list)

Is this correct?
Thanks.
--
Xavi
--
http://mail.python.org/mailman/listinfo/python-list


steve+comp.lang.python at pearwood

Aug 10, 2013, 12:32 PM

Post #7 of 31 (52 views)
Permalink
Re: Python Basic Doubt [In reply to]

On Sat, 10 Aug 2013 20:00:58 +0200, Xavi wrote:

> Now I have one doubt, I use 'is' to compare basic types in python 3, for
> example .-
>
> v = []
> if type(v) is list:
> print('Is list...')

No, do not do this. This is unnecessarily restrictive.

> Because I think it is more clear and faster than .-

Clear? Maybe. Clear, but does the wrong thing. Using type rejects
subclasses, which is normally a bad idea. Using isinstance accepts
subclasses, which is what we nearly always should do.

As for being faster -- who cares? The difference between calling type and
calling isinstance is about 0.02 microseconds on my slow computer. You
should not try to optimize things which are so unimportant.

The first rule of optimization: Don't do it.
For experts only: Don't do it yet.

Until you have profiled your application, and discovered calling
isinstance is the bottleneck making your application too slow, you are
wasting your time trying to guess what will make it go faster.



> type(v) == [].__class__

You should not do that either. Names starting and ending with double-
underscore are reserved for Python. They are not quite private
implementation details, but you almost never need to use them directly.

Why keep a dog and then bark yourself? Python will check __class__ for
you, when and if needed. That is not your job. It is very rare to need to
use __dunder__ attributes by hand.

> ... or ... isinstance(v, list)

That's the right solution, 99.9% of the time.

Actually, 99% of the time you should not call isinstance at all, but just
catch any errors that occur; or better still, only catch them if you can
do something about it. Otherwise, just allow the exception to propagate
to the caller, who may catch it. Calling isinstance should be rare;
calling type to check for an exact class even rarer.


--
Steven
--
http://mail.python.org/mailman/listinfo/python-list


tjreedy at udel

Aug 10, 2013, 12:46 PM

Post #8 of 31 (51 views)
Permalink
Re: Python Basic Doubt [In reply to]

On 8/10/2013 2:00 PM, Xavi wrote:
> Hello,
>
> El 10/08/2013 18:40, Tim Chase escribió:
>> Generally, if you are using the "is" operator to compare against
>> anything other than None, you're doing it wrong. There are exceptions
>> to this, but it takes knowing the particulars.
>
> Now I have one doubt, I use 'is' to compare basic types in python 3, for
> example .-
>
> v = []
> if type(v) is list:
> print('Is list...')
>
> Because I think it is more clear and faster than .-
> type(v) == [].__class__ ... or ... isinstance(v, list)
>
> Is this correct?

It depends on the context. If one is writing a test for a function that
is defined as returning a list, such as the builtin function *sorted*,
then 'is list' would be correct.

When one knows the type, as in your toy snippet, 'is list' is nonsensical.

In a more typical situation, as when testing the argument to a function
in the body of a function, then 'isinstance(arg, list)' is almost
certainly more correct (but often still not best) as the function should
usually accept at least any list subclass instance.

def popslice(lis, start, stop=None, step=0):
if not isinstance(lis, list):
raise TypeError("Can only popslice a list")
if stop is None: # here is where is *should* be used
start, stop = 0, start
ret = lis[start:stop:step]
del lis[start:stop:step]
return ret

lis = list(range(10))
print(popslice(lis, 2, 9, 2), lis)
>>>
[2, 4, 6, 8] [0, 1, 3, 5, 7, 9]

However, why exclude a mutable sequence that support slices but is not
specifically a list?

def popslice(seq, start, stop=None, step=0):
if stop is None: # here is where is *should* be used
start, stop = 0, start
ret = seq[start:stop:step]
del seq[start:stop:step]
return ret

Bad inputs will raise TypeErrors.
TypeError: 'int' object is not subscriptable
TypeError: 'tuple' object doesn't support item deletion
It this is not good enough, wrap the body in
try:
...
except TypeError as e:
raise TypeError("your custom message here")

--
Terry Jan Reedy


--
http://mail.python.org/mailman/listinfo/python-list


roy at panix

Aug 10, 2013, 1:42 PM

Post #9 of 31 (52 views)
Permalink
Re: Python Basic Doubt [In reply to]

In article <mailman.439.1376166663.1251.python-list [at] python>,
Dennis Lee Bieber <wlfraed [at] ix> wrote:

> Because id(n) is not giving you the address of the NAME. It is giving
> you the address of the "10"

Actually, it is giving you the id of the int(10) object. Maybe it's an
address, maybe it's not. Only your implementation knows for sure.
--
http://mail.python.org/mailman/listinfo/python-list


rosuav at gmail

Aug 10, 2013, 2:37 PM

Post #10 of 31 (48 views)
Permalink
Re: Python Basic Doubt [In reply to]

On Sat, Aug 10, 2013 at 7:00 PM, Xavi <jarabal [at] gmail> wrote:
> Now I have one doubt, I use 'is' to compare basic types in python 3, for
> example .-
>
> v = []
> if type(v) is list:
> print('Is list...')
>
> Because I think it is more clear and faster than .-
> type(v) == [].__class__ ... or ... isinstance(v, list)
>
> Is this correct?
> Thanks.

This really should be a separate thread, rather than a follow-up to
the previous one, since it's quite unrelated. But anyway.

The isinstance check is the better one, because it will also accept a
subclass of list, which the others won't.

ChrisA
--
http://mail.python.org/mailman/listinfo/python-list


gary.herron at islandtraining

Aug 10, 2013, 2:48 PM

Post #11 of 31 (48 views)
Permalink
Re: Python Basic Doubt [In reply to]

On 08/10/2013 11:00 AM, Xavi wrote:
> Hello,
>
> El 10/08/2013 18:40, Tim Chase escribió:
>> Generally, if you are using the "is" operator to compare against
>> anything other than None, you're doing it wrong. There are exceptions
>> to this, but it takes knowing the particulars.
>
> Now I have one doubt, I use 'is' to compare basic types in python 3,
> for example .-
>
> v = []
> if type(v) is list:
> print('Is list...')
>
> Because I think it is more clear and faster than .-
> type(v) == [].__class__ ... or ... isinstance(v, list)
>
> Is this correct?
> Thanks.

No! Don't do that! If you want to compare values use the "==" operator.

This is an oversimplification, but generally useful for all beginner
(and most advanced) programmers:
Don't use "is" for comparisons. Use "==".
It 20 years of programming Python, I've *needed* to use "is" ... only
once or twice.

Beyond that, there is a small batch of comparisons where "is" is
slightly more Pythonic, but not really necessary. And beyond that,
there are several instances where the difference between "is" and "==""
are important.

Mostly, using "is" is inappropriate and will get you into compassions
that depend on implementation details. For instance don't use "is"
until you understand this:

q:~> python3
Python 3.3.1 (default, Apr 17 2013, 22:32:14)
[GCC 4.7.3] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> 101 is 1+100
True

>>> 1001 is 1+1000
False

Gary Herron

--
http://mail.python.org/mailman/listinfo/python-list


rosuav at gmail

Aug 10, 2013, 3:09 PM

Post #12 of 31 (49 views)
Permalink
Re: Python Basic Doubt [In reply to]

On Sat, Aug 10, 2013 at 10:48 PM, Gary Herron
<gary.herron [at] islandtraining> wrote:
> This is an oversimplification, but generally useful for all beginner (and
> most advanced) programmers:
> Don't use "is" for comparisons. Use "==".
> It 20 years of programming Python, I've *needed* to use "is" ... only once
> or twice.

Hrm, I wouldn't make it that hard a rule. Both comparisons have their
place. As has been mentioned earlier in this thread, checking if
something is None is spelled "if something is None". Checking if it
equals zero is spelled "if it == 0", which is a quite different check.
The other common check that uses 'is' is with an argument default
where absolutely anything could be passed:

_notpassed = object()
def frob(appendage, device=_notpassed):
"""Use some appendage to frob some device, or None to frob nothing.
Omit device to frob whatever is currently held in that appendage"""
if device is _notpassed:
device = ... # whatever you need
if device is not None:
# frob the device

But granted, equality comparisons are a LOT more common than identity
comparisons.

ChrisA
--
http://mail.python.org/mailman/listinfo/python-list


gary.herron at islandtraining

Aug 10, 2013, 5:42 PM

Post #13 of 31 (45 views)
Permalink
Re: Python Basic Doubt [In reply to]

On 08/10/2013 03:09 PM, Chris Angelico wrote:
> On Sat, Aug 10, 2013 at 10:48 PM, Gary Herron
> <gary.herron [at] islandtraining> wrote:
>> This is an oversimplification, but generally useful for all beginner (and
>> most advanced) programmers:
>> Don't use "is" for comparisons. Use "==".
>> It 20 years of programming Python, I've *needed* to use "is" ... only once
>> or twice.
> Hrm, I wouldn't make it that hard a rule. Both comparisons have their
> place. As has been mentioned earlier in this thread, checking if
> something is None is spelled "if something is None". Checking if it
> equals zero is spelled "if it == 0", which is a quite different check.
> The other common check that uses 'is' is with an argument default
> where absolutely anything could be passed:
>
> _notpassed = object()
> def frob(appendage, device=_notpassed):
> """Use some appendage to frob some device, or None to frob nothing.
> Omit device to frob whatever is currently held in that appendage"""
> if device is _notpassed:
> device = ... # whatever you need
> if device is not None:
> # frob the device
>
> But granted, equality comparisons are a LOT more common than identity
> comparisons.
>
> ChrisA

Everything you say is true, and even reasonable for those who know
what's up.

But for each of your examples, using "==" is equivalent to using "is".
Each of
if something == None
if device == _not passed
if device != None
would all work as expected. In none of those cases is "is" actually
needed.

Given that, and the implementation dependent oddities, I still believe
that it is *highly* misleading to teach a beginner about "is".

Here's a challenge: What is the simplest non-contrived example where an
"is" comparison is *required*. Where substitution of an "==" comparison
would cause the program to fail or be significantly less efficient?
(I'm not including the nearly immeasurably small timing difference
between v==None and v is None.)

Gary Herron
--
http://mail.python.org/mailman/listinfo/python-list


rosuav at gmail

Aug 10, 2013, 6:00 PM

Post #14 of 31 (46 views)
Permalink
Re: Python Basic Doubt [In reply to]

On Sun, Aug 11, 2013 at 1:42 AM, Gary Herron
<gary.herron [at] islandtraining> wrote:
> On 08/10/2013 03:09 PM, Chris Angelico wrote:
>> _notpassed = object()
>> def frob(appendage, device=_notpassed):
>> """Use some appendage to frob some device, or None to frob nothing.
>> Omit device to frob whatever is currently held in that appendage"""
>> if device is _notpassed:
>> device = ... # whatever you need
>> if device is not None:
>> # frob the device
>>
>> But granted, equality comparisons are a LOT more common than identity
>> comparisons.
>>
>> ChrisA
>
>
> Everything you say is true, and even reasonable for those who know what's
> up.
>
> But for each of your examples, using "==" is equivalent to using "is". Each
> of
> if something == None
> if device == _not passed
> if device != None
> would all work as expected. In none of those cases is "is" actually needed.

Wrong. If you do equality comparisons, it's entirely possible for
something to be passed in that compares equal to the RHS without
actually being it, so "is" is precisely what's wanted. (Plus, why go
through a potentially expensive comparison check when you can simply
check object identity - which could be, for instance, an address
check? But performance is a distant second to correctness here.)

> Given that, and the implementation dependent oddities, I still believe that
> it is *highly* misleading to teach a beginner about "is".
>
> Here's a challenge: What is the simplest non-contrived example where an
> "is" comparison is *required*. Where substitution of an "==" comparison
> would cause the program to fail or be significantly less efficient? (I'm
> not including the nearly immeasurably small timing difference between
> v==None and v is None.)

All it takes is a slightly odd or buggy __eq__ implementation and the
== versions will misbehave. To check if an argument is something, you
use "is", not ==.

ChrisA
--
http://mail.python.org/mailman/listinfo/python-list


tjreedy at udel

Aug 10, 2013, 6:25 PM

Post #15 of 31 (43 views)
Permalink
Re: Python Basic Doubt [In reply to]

On 8/10/2013 8:42 PM, Gary Herron wrote:

> But for each of your examples, using "==" is equivalent to using "is".
> Each of
> if something == None
> if device == _not passed
> if device != None
> would all work as expected. In none of those cases is "is" actually
> needed.

class EqualAll:
def __eq__(self, other): return True

ea = EqualAll()
print(ea == None)
print(ea == float('nan'))
>>>
True
True

--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


rosuav at gmail

Aug 10, 2013, 6:32 PM

Post #16 of 31 (43 views)
Permalink
Re: Python Basic Doubt [In reply to]

On Sun, Aug 11, 2013 at 2:25 AM, Terry Reedy <tjreedy [at] udel> wrote:
> On 8/10/2013 8:42 PM, Gary Herron wrote:
>
>> But for each of your examples, using "==" is equivalent to using "is".
>> Each of
>> if something == None
>> if device == _not passed
>> if device != None
>> would all work as expected. In none of those cases is "is" actually
>> needed.
>
>
> class EqualAll:
> def __eq__(self, other): return True

That's a contrived example, of course, but it's easy to have a bug in
__eq__ that results in the same behaviour. I can't imagine any code
that would actually WANT that, unless you're trying to represent
Animal Farm.

class EqualAll:
def __eq__(self, other):
if (isinstance(other, pig): return 3 # Some are more equal than others
return True

ChrisA
--
http://mail.python.org/mailman/listinfo/python-list


i.am.songoku at gmail

Aug 10, 2013, 8:09 PM

Post #17 of 31 (44 views)
Permalink
Re: Python Basic Doubt [In reply to]

Thanks Tim,

This takes me to one more question.

'is' operator is used to compare objects and it should not be used to
compare data.

So can it be compared with 'False'.

i.e. Is this code possible

if a is False:
print 'Yes'
if b is False:
print 'No'

Because i recommended this should not be done. But my colleagues say it is
correct.

Regards,
Krishnan


On Sat, Aug 10, 2013 at 10:10 PM, Tim Chase
<python.list [at] tim>wrote:

> On 2013-08-10 21:03, Krishnan Shankar wrote:
> > >>> a=10
> > >>> id(a)
> > 21665504
> > >>> b=a
> > >>> id(b)
> > 21665504
> > >>> c=10
> > >>> id(c)
> > 21665504
> >
> > I am actually assigning new value to c. But from the value of id()
> > all three variables take same location. With variables a and b it
> > is ok. But why c taking the same location?
>
> As an internal optimization, CPython caches small integer values
>
> >>> a = 256
> >>> b = 256
> >>> a is b
> True
> >>> a = 257
> >>> b = 257
> >>> a is b
> False
>
> Because it's an internal implementation detail, you shouldn't count
> on this behavior (Jython or Cython or IronPython may differ; or
> future versions of Python may cache a different range of numbers).
>
> Generally, if you are using the "is" operator to compare against
> anything other than None, you're doing it wrong. There are exceptions
> to this, but it takes knowing the particulars.
>
> -tkc
>
>
>
>


rosuav at gmail

Aug 10, 2013, 8:20 PM

Post #18 of 31 (43 views)
Permalink
Re: Python Basic Doubt [In reply to]

On Sun, Aug 11, 2013 at 4:09 AM, Krishnan Shankar
<i.am.songoku [at] gmail> wrote:
> i.e. Is this code possible
>
> if a is False:
> print 'Yes'
> if b is False:
> print 'No'

You would use that if you want to check if a/b is the exact bool value
False. Normally you would simply spell it thus:

if not a:
print 'Yes'
if not b:
print 'No'

which will accept any value and interpret it as either empty (false)
or non-empty (true).

Using the equality operator here adds another level of potential confusion:

>>> 0 == False
True
>>> [] == False
False
>>> 0.0 == False
True
>>> () == False
False

whereas if you use the normal boolean conversion, those ARE all false:

>>> bool(0)
False
>>> bool([])
False
>>> bool(0.0)
False
>>> bool(())
False

ChrisA
--
http://mail.python.org/mailman/listinfo/python-list


gary.herron at islandtraining

Aug 10, 2013, 8:21 PM

Post #19 of 31 (38 views)
Permalink
Re: Python Basic Doubt [In reply to]

On 08/10/2013 06:00 PM, Chris Angelico wrote:
> On Sun, Aug 11, 2013 at 1:42 AM, Gary Herron
> <gary.herron [at] islandtraining> wrote:
>> On 08/10/2013 03:09 PM, Chris Angelico wrote:
>>> _notpassed = object()
>>> def frob(appendage, device=_notpassed):
>>> """Use some appendage to frob some device, or None to frob nothing.
>>> Omit device to frob whatever is currently held in that appendage"""
>>> if device is _notpassed:
>>> device = ... # whatever you need
>>> if device is not None:
>>> # frob the device
>>>
>>> But granted, equality comparisons are a LOT more common than identity
>>> comparisons.
>>>
>>> ChrisA
>>
>> Everything you say is true, and even reasonable for those who know what's
>> up.
>>
>> But for each of your examples, using "==" is equivalent to using "is". Each
>> of
>> if something == None
>> if device == _not passed
>> if device != None
>> would all work as expected. In none of those cases is "is" actually needed.
> Wrong. If you do equality comparisons, it's entirely possible for
> something to be passed in that compares equal to the RHS without
> actually being it, so "is" is precisely what's wanted. (Plus, why go
> through a potentially expensive comparison check when you can simply
> check object identity - which could be, for instance, an address
> check? But performance is a distant second to correctness here.)


You're missing my point.

Our knee-jerk reaction to beginners using "is" should be:
Don't do that! You almost certainly want "==". Consider "is" an
advanced topic.

Then you can spend as much time as you want trying to coach them into an
understanding of the precise details. But until they have that
understanding, they are well served by a rule-of-thumb that says:
Use "==" not "is" for comparisons.

>
>> Given that, and the implementation dependent oddities, I still believe that
>> it is *highly* misleading to teach a beginner about "is".
>>
>> Here's a challenge: What is the simplest non-contrived example where an
>> "is" comparison is *required*. Where substitution of an "==" comparison
>> would cause the program to fail or be significantly less efficient? (I'm
>> not including the nearly immeasurably small timing difference between
>> v==None and v is None.)
> All it takes is a slightly odd or buggy __eq__ implementation and the
> == versions will misbehave. To check if an argument is something, you
> use "is", not ==.

No, sorry, but any use of the word "is" in an English sentence is way
too ambiguous to specify a correct translation into code. To check "if
a calculation of some value is a million", you'd write
value == 1000000
not
value is 1000000
even though there are plenty of other examples where "is" would be correct.


>
> ChrisA

--
http://mail.python.org/mailman/listinfo/python-list


gary.herron at islandtraining

Aug 10, 2013, 8:30 PM

Post #20 of 31 (39 views)
Permalink
Re: Python Basic Doubt [In reply to]

On 08/10/2013 08:09 PM, Krishnan Shankar wrote:
> Thanks Tim,
>
> This takes me to one more question.
>
> 'is' operator is used to compare objects and it should not be used to
> compare data.
>
> So can it be compared with 'False'.
>
> i.e. Is this code possible
>
> if a is False:
> print 'Yes'
> if b is False:
> print 'No'

Depends on what you want. If you want to differentiate between a value
of False, and other false-like values 0, (), [], {} and so on, then you
need to be explicit with
if a is False:

Normally, that's not what you want, so you use
if not a:
to catch any of those false-like values.


>
> Because i recommended this should not be done. But my colleagues say
> it is correct.
>
> Regards,
> Krishnan
>
>
> On Sat, Aug 10, 2013 at 10:10 PM, Tim Chase
> <python.list [at] tim <mailto:python.list [at] tim>>
> wrote:
>
> On 2013-08-10 21:03, Krishnan Shankar wrote:
> > >>> a=10
> > >>> id(a)
> > 21665504
> > >>> b=a
> > >>> id(b)
> > 21665504
> > >>> c=10
> > >>> id(c)
> > 21665504
> >
> > I am actually assigning new value to c. But from the value of id()
> > all three variables take same location. With variables a and b it
> > is ok. But why c taking the same location?
>
> As an internal optimization, CPython caches small integer values
>
> >>> a = 256
> >>> b = 256
> >>> a is b
> True
> >>> a = 257
> >>> b = 257
> >>> a is b
> False
>
> Because it's an internal implementation detail, you shouldn't count
> on this behavior (Jython or Cython or IronPython may differ; or
> future versions of Python may cache a different range of numbers).
>
> Generally, if you are using the "is" operator to compare against
> anything other than None, you're doing it wrong. There are exceptions
> to this, but it takes knowing the particulars.
>
> -tkc
>
>
>
>
>
>


torriem at gmail

Aug 10, 2013, 8:35 PM

Post #21 of 31 (39 views)
Permalink
Re: Python Basic Doubt [In reply to]

On 08/10/2013 09:09 PM, Krishnan Shankar wrote:

> i.e. Is this code possible
>
> if a is False:
> print 'Yes'
> if b is False:
> print 'No'
>
> Because i recommended this should not be done. But my colleagues say it is
> correct.

You are probably correct in your believe that this idiom should be
avoided. As Chris says, it's much more pythonic to just use if not a.

There is one case where the recommended idiom is to use the 'is'
operator. That's when you want an empty list as a default parameter to a
function. Since lists are mutable, often times using [] as a default
parameter is the wrong thing to do. This is the recommended idiom:

def my_func(mylist = None):
if mylist is None:
mylist = []

--
http://mail.python.org/mailman/listinfo/python-list


rosuav at gmail

Aug 10, 2013, 8:43 PM

Post #22 of 31 (38 views)
Permalink
Re: Python Basic Doubt [In reply to]

On Sun, Aug 11, 2013 at 4:21 AM, Gary Herron
<gary.herron [at] islandtraining> wrote:
> On 08/10/2013 06:00 PM, Chris Angelico wrote:
>> Wrong. If you do equality comparisons, it's entirely possible for
>> something to be passed in that compares equal to the RHS without
>> actually being it, so "is" is precisely what's wanted. (Plus, why go
>> through a potentially expensive comparison check when you can simply
>> check object identity - which could be, for instance, an address
>> check? But performance is a distant second to correctness here.)
>
> You're missing my point.
>
> Our knee-jerk reaction to beginners using "is" should be:
> Don't do that! You almost certainly want "==". Consider "is" an
> advanced topic.
>
> Then you can spend as much time as you want trying to coach them into an
> understanding of the precise details. But until they have that
> understanding, they are well served by a rule-of-thumb that says:
> Use "==" not "is" for comparisons.

No, I'm not missing your point; I'm disagreeing with it. I think that
'is' should be taught, that it is every bit as important as '==';
you're walking down the path of "GOTO considered harmful", of decrying
some particular language feature because it can be misused.

>> All it takes is a slightly odd or buggy __eq__ implementation and the
>> == versions will misbehave. To check if an argument is something, you
>> use "is", not ==.
>
> No, sorry, but any use of the word "is" in an English sentence is way too
> ambiguous to specify a correct translation into code. To check "if a
> calculation of some value is a million", you'd write
> value == 1000000
> not
> value is 1000000
> even though there are plenty of other examples where "is" would be correct.

Granted, English is a poor litmus test for code. But in this
particular example, we're talking about immutable types (simple
integers), where value and identity are practically the same. A Python
implementation would be perfectly justified in interning *every*
integer, in which case the 'is' would work perfectly here. The
distinction between the two is important when the objects are mutable
(so they have an identity that's distinct from their current values).

ChrisA
--
http://mail.python.org/mailman/listinfo/python-list


joshua at landau

Aug 10, 2013, 9:04 PM

Post #23 of 31 (39 views)
Permalink
Re: Python Basic Doubt [In reply to]

On 11 August 2013 04:43, Chris Angelico <rosuav [at] gmail> wrote:
> On Sun, Aug 11, 2013 at 4:21 AM, Gary Herron
> <gary.herron [at] islandtraining> wrote:
>> On 08/10/2013 06:00 PM, Chris Angelico wrote:
>>> All it takes is a slightly odd or buggy __eq__ implementation and the
>>> == versions will misbehave. To check if an argument is something, you
>>> use "is", not ==.
>>
>> No, sorry, but any use of the word "is" in an English sentence is way too
>> ambiguous to specify a correct translation into code. To check "if a
>> calculation of some value is a million", you'd write
>> value == 1000000
>> not
>> value is 1000000
>> even though there are plenty of other examples where "is" would be correct.
>
> Granted, English is a poor litmus test for code. But in this
> particular example, we're talking about immutable types (simple
> integers), where value and identity are practically the same. A Python
> implementation would be perfectly justified in interning *every*
> integer, in which case the 'is' would work perfectly here. The
> distinction between the two is important when the objects are mutable
> (so they have an identity that's distinct from their current values).

I don't follow this argument. Tuples are immutable yet you're crazy if
you check their equality with "is". In Python identity and equality
are very distinct.

I follow (and agree) with the other arguments: "is" is useful and
should be used. It's just this part in particular sounds off.
--
http://mail.python.org/mailman/listinfo/python-list


gary.herron at islandtraining

Aug 10, 2013, 9:29 PM

Post #24 of 31 (38 views)
Permalink
Re: Python Basic Doubt [In reply to]

On 08/10/2013 08:43 PM, Chris Angelico wrote:
> On Sun, Aug 11, 2013 at 4:21 AM, Gary Herron
> <gary.herron [at] islandtraining> wrote:
>> On 08/10/2013 06:00 PM, Chris Angelico wrote:
>>> Wrong. If you do equality comparisons, it's entirely possible for
>>> something to be passed in that compares equal to the RHS without
>>> actually being it, so "is" is precisely what's wanted. (Plus, why go
>>> through a potentially expensive comparison check when you can simply
>>> check object identity - which could be, for instance, an address
>>> check? But performance is a distant second to correctness here.)
>> You're missing my point.
>>
>> Our knee-jerk reaction to beginners using "is" should be:
>> Don't do that! You almost certainly want "==". Consider "is" an
>> advanced topic.
>>
>> Then you can spend as much time as you want trying to coach them into an
>> understanding of the precise details. But until they have that
>> understanding, they are well served by a rule-of-thumb that says:
>> Use "==" not "is" for comparisons.
> No, I'm not missing your point; I'm disagreeing with it. I think that
> 'is' should be taught, that it is every bit as important as '==';
> you're walking down the path of "GOTO considered harmful", of decrying
> some particular language feature because it can be misused.
//
I agree that both "==" and "is" must be taught. But it's the order in
which things are introduced which I'm quibbling about. Something like
this makes sense (to me):

Lesson 1: Use "==" for comparisons, save "is" for a more advanced
lesson.

Lesson 2: Use "is" for singleton types like "if a is None:" and
other easily defined circumstances.

Lesson 3: The whole truth, accompanied by a whole chapter's worth of
material that describes Python's data model and the difference
between value versus identity and assignment versus binding ...

A beginner, on his first program or two, can understand 1, and perhaps
parrot 2 without understanding (or needing to). But the step from
there to 3 is huge. It's folly to dump that on a first-time
programmer. (It's probably even folly to dump that on a seasoned
programmer just starting in Python. I still remember not understanding
the explanation for "is" when I first read it. And it continued to make
no sense until I had enough experience to understand the difference
betwen C/C++ assignment to variables and Python's binding of variables.)


>
>>> All it takes is a slightly odd or buggy __eq__ implementation and the
>>> == versions will misbehave. To check if an argument is something, you
>>> use "is", not ==.
>> No, sorry, but any use of the word "is" in an English sentence is way too
>> ambiguous to specify a correct translation into code. To check "if a
>> calculation of some value is a million", you'd write
>> value == 1000000
>> not
>> value is 1000000
>> even though there are plenty of other examples where "is" would be correct.
> Granted, English is a poor litmus test for code. But in this
> particular example, we're talking about immutable types (simple
> integers), where value and identity are practically the same. A Python
> implementation would be perfectly justified in interning *every*
> integer, in which case the 'is' would work perfectly here. The
> distinction between the two is important when the objects are mutable
> (so they have an identity that's distinct from their current values).

Granted. But please note: There is *nothing* in that sentence which is
fit for a beginner programmer. ... "immutable", "value/identity",
"interning" ... In one ear and out the other. :-)

>
> ChrisA


rosuav at gmail

Aug 10, 2013, 9:38 PM

Post #25 of 31 (38 views)
Permalink
Re: Python Basic Doubt [In reply to]

On Sun, Aug 11, 2013 at 5:04 AM, Joshua Landau <joshua [at] landau> wrote:
> On 11 August 2013 04:43, Chris Angelico <rosuav [at] gmail> wrote:
>> The
>> distinction between the two is important when the objects are mutable
>> (so they have an identity that's distinct from their current values).
>
> I don't follow this argument. Tuples are immutable yet you're crazy if
> you check their equality with "is". In Python identity and equality
> are very distinct.

True, it's not strictly an issue of mutability of that one level. But
anything that's truly immutable (a tuple/frozenset of ints/strings)
can in theory be interned. In some languages (no Pythons as far as I'm
aware, though one could easily do so and still be fully compliant),
all strings are automatically interned, so there's no difference
between value and identity for them. A tuple containing a list, for
instance, needs its identity; a tuple of three integers is
identifiable entirely by its value.

ChrisA
--
http://mail.python.org/mailman/listinfo/python-list

First page Previous page 1 2 Next page Last page  View All Python python RSS feed   Index | Next | Previous | View Threaded
 
 


Interested in having your list archived? Contact Gossamer Threads
 
  Web Applications & Managed Hosting Powered by Gossamer Threads Inc.