Re: The meaning of "doubt", was Re: Python Basic Doubt
You could say that all translated languages lose something in translation. It's all symbolism. I say sunshine, and you might say Great Ball of' Fire in the s ky. Isay x = 10 in python print x and in c++ something like unsigned int x cin << x; cout >> x; or something like that. It's something you have to think about on a level of the individual knowing, a term, and then symbolizing, which can lose meaning, or equate meaning. Look at the former in language of humans, and the latter of computer language. One can equate or symbolize. On Sat, Aug 10, 2013 at 4:57 PM, Cousin Stanley wrote: > Peter Otten wrote: > > > > > doubt > > > > Oh bother, said Pooh, what's in a word ? > > http://en.wikipedia.org/wiki/Curry > > https://pypi.python.org/pypi/curry/ > > http://en.wikipedia.org/wiki/Currying > > > -- > Stanley C. Kitching > Human Being > Phoenix, Arizona > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Basic Doubt
On Sun, 11 Aug 2013 18:58:25 +0200, Xavi wrote: > Respect to the "Names starting and ending with double-underscore". I > don't know how to get the name of a classe without them. > obj.__class__.__name__ I didn't say you should *never* use them, but most of the time, you don't. However type(obj).__name__ should be better. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Basic Doubt
Thanks to all for your answers, I guess it is more flexible with isinstance (the duck test :) I'm going to change the type checks. Respect to the "Names starting and ending with double-underscore". I don't know how to get the name of a classe without them. obj.__class__.__name__ Thanks. -- Xavi -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Basic Doubt
On Sat, 10 Aug 2013 16:42:22 -0400, Roy Smith wrote: > In article , > Dennis Lee Bieber 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. /steve cheers from the audience Thank you for mentioning this. Using Jython: >>> x = 10 >>> id(x) 1 And using IronPython: >>> x = 10 >>> id(x) 43 "id" does not stand for "memory address". It stands for "identity". -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Basic Doubt
On Sat, 10 Aug 2013 20:21:46 -0700, Gary Herron wrote: > 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. "...except for comparing to None, where 99.99% of the time you do actually want an identity comparison." This can lead into a more detailed explanation for why you should choose one over the other, or the incurious newbie could take it is something to be learned by rote. I have no problem with telling newbies that there is a reason for this apparently arbitrary rule, but they don't need to learn it *right now* if they don't want. In any case, the rule can include "When in doubt, use equals". I'm good with that :-) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Basic Doubt
On Sat, 10 Aug 2013 17:42:21 -0700, 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. py> class Weird: ... def __eq__(self, other): ... return True ... py> definitely_not_None = Weird() py> definitely_not_None == None True Oops. Now Weird is, naturally, weird. But classes may have a legitimate reason to claim to be equal to None, or at least the creator of the class may believe he has a legitimate reason. It's not forbidden, therefore you have to assume somebody will do so. But more importantly, in checking whether some value is a sentinel, the *intention* of the code is to check that the value *actually is* the sentinel, not merely that it happens to be equal to the sentinel. To give an analogy: when you hand the codes to the nuclear arsenal to the President, you want to make sure that it actually *is* the President, not some impostor who merely looks and sounds like him. "value == None" not only risks doing the wrong thing if passed some weird object, but it fails to match the intention of the code. Whereas "value is None" is idiot-proof (it cannot fail -- short of hacking the compiler, you cannot change the meaning of either "is" or "None"), it matches the intention of the code, and therefore is clearer, more explicit, and more idiomatic. And as a bonus, it's faster too. But speed is not why you should use it. You should use it because it matches the intention of the code. You don't want to test for some arbitrary person who happens to look like the President, you want to test for the President himself, and nobody but the President. On the other hand, code like "x is 42.9" does not match the intention of the code, and is likely to fail. "is" is not a synonym for "==". Conflating them is a bad thing, whether you use "is" to check for equality or "==" to check for identity. > Given that, and the implementation dependent oddities, I still believe > that it is *highly* misleading to teach a beginner about "is". Careful -- it's not "is" which is implementation-dependent. The "is" operator works the same way in every Python implementation. What differs are the rules for when new instances are created from literals. > 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.) Easy-peasey. Test code often relies on "is" to check object identity. Occasionally such comparisons work there way into production code, but they're common in tests. In one of my test suites, I have code that verifies that a certain function which takes a list as argument does not modify it in place. So my unit test looks like this: def testNoInPlaceModifications(self): # Test that the function does not modify its input data. data = self.prepare_data() assert len(data) != 1 # Necessary to avoid infinite loop. assert data != sorted(data) saved = data[:] assert data is not saved # <<<=== LOOK HERE === _ = self.func(data) self.assertListEqual(data, saved, "data has been modified") Note that is would be *wrong* to replace the "is not" comparison with not equal to. The list and its copy are, in fact, equal. If they aren't equal, the test fails. In this case, the assertions are there as verifiable comments. They communicate to the reader, "These are the assumptions this test relies on", except unlike comments, if the assumptions are violated, the test will fail. Unlike comments, they cannot ever get out of date. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Basic Doubt
On Sun, Aug 11, 2013 at 5:29 AM, Gary Herron wrote: > 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.) See, that's where the problem is. You will never grok the difference between == and is if you're still thinking about C variables. (Though you *might* be able to explain it by talking solely about char* and the way two C strings can be the same but stored at different places in memory. But that would be unhelpful most of the time.) This is important *early* reading for a new Python programmer: http://mail.python.org/pipermail/tutor/2010-December/080505.html Note that it was originally posted on python-tutor, so it was definitely aimed at the inexperienced. > On 08/10/2013 08:43 PM, Chris Angelico wrote: > 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. :-) Right. This isn't my explanation of 'is' and '=='; it's my explanation of why it's important to HAVE an explanation of the aforementioned. :) Though the difference between value and identity is significant and important, and mutability is bound to crop up fairly early on; so really, it's only the concept of interning that would be really advanced. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Basic Doubt
On Sun, Aug 11, 2013 at 5:04 AM, Joshua Landau wrote: > On 11 August 2013 04:43, Chris Angelico 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
Re: Python Basic Doubt
On 08/10/2013 08:43 PM, Chris Angelico wrote: On Sun, Aug 11, 2013 at 4:21 AM, Gary Herron 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 == 100 not value is 100 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Basic Doubt
On 11 August 2013 04:43, Chris Angelico wrote: > On Sun, Aug 11, 2013 at 4:21 AM, Gary Herron > 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 == 100 >> not >> value is 100 >> 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
Re: Python Basic Doubt
On Sun, Aug 11, 2013 at 4:21 AM, Gary Herron 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 == 100 > not > value is 100 > 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
Re: Python Basic Doubt
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
Re: Python Basic Doubt
On 08/10/2013 06:00 PM, Chris Angelico wrote: On Sun, Aug 11, 2013 at 1:42 AM, Gary Herron 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 == 100 not value is 100 even though there are plenty of other examples where "is" would be correct. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Basic Doubt
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 mailto:python.l...@tim.thechases.com>> 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Basic Doubt
On Sun, Aug 11, 2013 at 4:09 AM, Krishnan Shankar 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
Re: Python Basic Doubt
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 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 > > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Basic Doubt
On Sun, Aug 11, 2013 at 2:25 AM, Terry Reedy 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
Re: Python Basic Doubt
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
Re: Python Basic Doubt
On Sun, Aug 11, 2013 at 1:42 AM, Gary Herron 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
Re: Python Basic Doubt
On 08/10/2013 03:09 PM, Chris Angelico wrote: On Sat, Aug 10, 2013 at 10:48 PM, Gary Herron 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
Re: Python Basic Doubt
On Sat, Aug 10, 2013 at 10:48 PM, Gary Herron 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
Re: Python Basic Doubt
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
Re: Python Basic Doubt
On Sat, Aug 10, 2013 at 7:00 PM, 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...') > > 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
Re: The meaning of "doubt", was Re: Python Basic Doubt
Peter Otten wrote: > > doubt > Oh bother, said Pooh, what's in a word ? http://en.wikipedia.org/wiki/Curry https://pypi.python.org/pypi/curry/ http://en.wikipedia.org/wiki/Currying -- Stanley C. Kitching Human Being Phoenix, Arizona -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Basic Doubt
In article , Dennis Lee Bieber 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
Re: The meaning of "doubt", was Re: Python Basic Doubt
On 8/10/2013 2:36 PM, Peter Otten wrote: Terry Reedy wrote: 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. Quoting http://en.wikipedia.org/wiki/Indian_English """ doubt = question or query; e.g. one would say, 'I have a doubt' when one wishes to ask a question. """ Thank you for verifying by suspicion (in the neutral sense) that this might be a generic Indian English usage. I'd say if Brits can cope (hard as it may be) with the American variant of the language, and native speakers can live with the broken English used to communicate in the rest of the world there is ample room for an Indian flavo(u)r now and then... The issue I raised was one of avoiding misunderstanding, especially in a short subject line. I almost skipped over the post because of it. I could have added a recommendation to be more specific. Any of "Question/confusion/doubt about int identity" would have been better. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Basic Doubt
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
Re: The meaning of "doubt", was Re: Python Basic Doubt
On Sat, 10 Aug 2013 20:36:52 +0200, Peter Otten wrote: > Terry Reedy wrote: > >> 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. > > Quoting http://en.wikipedia.org/wiki/Indian_English > > """ > doubt = question or query; e.g. one would say, 'I have a doubt' when one > wishes to ask a question. > """ > > I'd say if Brits can cope (hard as it may be) with the American variant > of the language, and native speakers can live with the broken English > used to communicate in the rest of the world there is ample room for an > Indian flavo(u)r now and then... +1 Ill take broken English from a non native speaker over the confusion caused by our American cousins who seam to have everything arse about face (especially if you consider the word "Fanny" ) Seriously though I can usually work out what the meaning was, & it is certainly clearer than any attempt I could make in any other language, which is actually quite shameful. -- My way of joking is to tell the truth. That's the funniest joke in the world. -- Muhammad Ali -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Basic Doubt
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
Re: The meaning of "doubt", was Re: Python Basic Doubt
In article , Peter Otten <__pete...@web.de> wrote: > Quoting http://en.wikipedia.org/wiki/Indian_English > > """ > doubt = question or query; e.g. one would say, 'I have a doubt' when one > wishes to ask a question. > """ > > I'd say if Brits can cope (hard as it may be) with the American variant of > the language, and native speakers can live with the broken English used to > communicate in the rest of the world there is ample room for an Indian > flavo(u)r now and then... Yup. I used to work with a development team in Bangalore. One of the amusing aspects of the collaboration was the subtle language issues. For example, apparently, "Roy" is a common *last* name in India. No matter how many times I explained it, the guys over there couldn't seem to get that Roy is my first name and Smith is my last name. So, in settings where everybody was using first names, they would always call me Smith. I shudder to think what carnage I accidentally inflicted on their names :-) And, of course, since we're on the subject, this should be required reading for all programmers: http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about- names/ -- http://mail.python.org/mailman/listinfo/python-list
The meaning of "doubt", was Re: Python Basic Doubt
Terry Reedy wrote: > 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. Quoting http://en.wikipedia.org/wiki/Indian_English """ doubt = question or query; e.g. one would say, 'I have a doubt' when one wishes to ask a question. """ I'd say if Brits can cope (hard as it may be) with the American variant of the language, and native speakers can live with the broken English used to communicate in the rest of the world there is ample room for an Indian flavo(u)r now and then... -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Basic Doubt
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
Re: Python Basic Doubt
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
Re: Python Basic Doubt
On Sat, Aug 10, 2013 at 4:33 PM, 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. 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
Re: Python Basic Doubt
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
Re: Python Basic Doubt
In article , 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. > > 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 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: basic doubt
On 17Jun2010 05:11, Gabriel Genellina wrote: | En Thu, 17 Jun 2010 02:06:54 -0300, madhuri vio | escribió: | | >def h(self,event): | >handle = open("myco.fasta","r") | >for seq_record in SeqIO.parse(handle, "fasta"): | > messenger_rna = coding_myco.fasta.transcribe() | > han1 = open("mycorna.fasta","wU") | > han1.close() | > return self.messenger_rna | > | > | >the error is... | > | >File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__ | >return self.func(*args) | >TypeError: h() takes exactly 2 arguments (0 given) | > | > ia m unable to debug...i am stuck | | This is just a guess, but looks like your h function is a plain | function, not a method, so it doesn't take a "self" parameter. Also, | you are probably using it in some place where the callback doesn't | receive any additional arguments (like a Button command). | Try with def f(): ... | If it doesn't work, show us the part where h is used. And have a look at the documentation for the "functools" module, particularly the "partial" function: f2 = functools.partial(f, arg1, arg2, ...) Then calling f2() will call f(arg1, arg2, ...). So you can pass "f2" to an event handler. Of course, this means you need to know arg1 etc in advance. However, you really do need to show the calling end of your code. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ You see: Mr. Drogo, he married poor Miss Primula Brandybuck. She was our Mr. Bilbo's first cousin on the mother's side (her mother being the youngest of the Old Took's daughters); and Mr. Drogo was his second cousin. So Mr. Frodo is his first *and* second cousin, once removed either way, as the saying is, if you follow me. - the Gaffer, _Lord_of_the_Rings_ -- http://mail.python.org/mailman/listinfo/python-list
Re: basic doubt
En Thu, 17 Jun 2010 02:06:54 -0300, madhuri vio escribió: def h(self,event): handle = open("myco.fasta","r") for seq_record in SeqIO.parse(handle, "fasta"): messenger_rna = coding_myco.fasta.transcribe() han1 = open("mycorna.fasta","wU") han1.close() return self.messenger_rna the error is... File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__ return self.func(*args) TypeError: h() takes exactly 2 arguments (0 given) ia m unable to debug...i am stuck This is just a guess, but looks like your h function is a plain function, not a method, so it doesn't take a "self" parameter. Also, you are probably using it in some place where the callback doesn't receive any additional arguments (like a Button command). Try with def f(): ... If it doesn't work, show us the part where h is used. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: basic doubt
On 06/16/2010 11:06 PM, madhuri vio wrote: > def h(self,event): > handle = open("myco.fasta","r") > for seq_record in SeqIO.parse(handle, "fasta"): > messenger_rna = coding_myco.fasta.transcribe() > han1 = open("mycorna.fasta","wU") > han1.close() > return self.messenger_rna > > > the error is... > > File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__ > return self.func(*args) > TypeError: h() takes exactly 2 arguments (0 given) > > ia m unable to debug...i am stuck You will have to provide more code than this. The traceback error you are getting is coming from Tk's event loop when it tries to execute your callback. Your callback is defined as having two parameters, but whatever is calling it from within Tk is expecting it to have no parameters. Without seeing a complete (but minimal!) code example that folks can run on their own computers and replicate your problem, there's no way for any of us to help you debug your code. Given the nature of your queries, I assume your are most likely in academia, doing bioinformatics research. You would be wise to seek out help from a computer science student or professor. In fact you're likely to receive more help by doing that than from this mailing list, at least at this stage. In your next post, please do at least the following things: 1. Make the e-mail subject clear, precise, and descriptive. "basic doubt" or "gui doubt" is *simply not acceptable*. Instead you might say, "How can I run a function when I click a button in Tk?" or "What does this traceback mean?" 2. Post enough code so that someone can cut and paste it and run it through python to duplicate your error. If you don't, I'm afraid that 95% of the list members are going to silently delete your e-mails, which will no doubt cause you much frustration. Many have already blocked your e-mail address. -- http://mail.python.org/mailman/listinfo/python-list
basic doubt
def h(self,event): handle = open("myco.fasta","r") for seq_record in SeqIO.parse(handle, "fasta"): messenger_rna = coding_myco.fasta.transcribe() han1 = open("mycorna.fasta","wU") han1.close() return self.messenger_rna the error is... File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__ return self.func(*args) TypeError: h() takes exactly 2 arguments (0 given) ia m unable to debug...i am stuck -- madhuri :) -- http://mail.python.org/mailman/listinfo/python-list