Re: Equivalent code to the bool() built-in function
In article iok5tg$svv$1...@reader1.panix.com, Grant Edwards invalid@invalid.invalid wrote: On Tue, Apr 19, 2011 at 7:09 AM, Christian Heimes li...@cheimes.de wrote: Am 18.04.2011 21:58, schrieb John Nagle: ?? ?? This is typical for languages which backed into a bool type, rather than having one designed in. ??The usual result is a boolean type with numerical semantics, like ?? True + True 2 I find the behavior rather useful. It allows multi-xor tests like: if a + b + c + d != 1: ?? ??raise ValueError(Exactly one of a, b, c or d must be true.) I guess I never thought about it, but there isn't an 'xor' operator to go along with 'or' and 'and'. Must not be something I need very often. There is. applied to booleans is xor. -- Grant Edwards grant.b.edwardsYow! I am having FUN... at I wonder if it's NET FUN or gmail.comGROSS FUN? -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert@spearc.xs4all.nl =n http://home.hccnet.nl/a.w.m.van.der.horst -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
In article 9142usf51...@mid.individual.net, Gregory Ewing greg.ew...@canterbury.ac.nz wrote: Chris Angelico wrote: Remind me some day to finish work on my ultimate programming language, which starts out with a clean slate and lets the programmer define his own operators and everything. Didn't someone already do that and call it lisp? :-) Lisp is betrayed by its brackets. He wants Forth. -- Greg Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert@spearc.xs4all.nl =n http://home.hccnet.nl/a.w.m.van.der.horst -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
I'm not not touching you! -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
Albert van der Horst alb...@spenarnc.xs4all.nl wrote: I guess I never thought about it, but there isn't an 'xor' operator to go along with 'or' and 'and'. Must not be something I need very often. There is. applied to booleans is xor. Best to get into the habit of using '!=' otherwise you'll find Python 3.x a bit frustrating. However, that only works if you have exactly two values: both 'and' and 'or' will extend easily to any number of values: True and False and True False False or False or True or False True but using != for 'xor' doesn't extend the same way: False != False != True False You can use 'sum(...)==1' for a larger number of values but do have to be careful that all of them are bools (or 0|1). -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Tue, Apr 19, 2011 at 7:09 AM, Christian Heimes li...@cheimes.de wrote: Am 18.04.2011 21:58, schrieb John Nagle: This is typical for languages which backed into a bool type, rather than having one designed in. The usual result is a boolean type with numerical semantics, like True + True 2 I find the behavior rather useful. It allows multi-xor tests like: if a + b + c + d != 1: raise ValueError(Exactly one of a, b, c or d must be true.) Unless you're sure all of a, b, c, and d are boolean values, an int with a negative value slipping in could result in the sum equaling 1, but more than one of the variables evaluating to True in boolean contexts. -- regards, kushal -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Tue, Apr 19, 2011 at 4:23 PM, Kushal Kumaran kushal.kumaran+pyt...@gmail.com wrote: if a + b + c + d != 1: raise ValueError(Exactly one of a, b, c or d must be true.) Unless you're sure all of a, b, c, and d are boolean values, an int with a negative value slipping in could result in the sum equaling 1, but more than one of the variables evaluating to True in boolean contexts. If they're all expressions, then you can easily guarantee that. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Tue, 19 Apr 2011 16:26:50 +1000, Chris Angelico wrote: On Tue, Apr 19, 2011 at 4:23 PM, Kushal Kumaran kushal.kumaran+pyt...@gmail.com wrote: if a + b + c + d != 1: raise ValueError(Exactly one of a, b, c or d must be true.) Unless you're sure all of a, b, c, and d are boolean values, an int with a negative value slipping in could result in the sum equaling 1, but more than one of the variables evaluating to True in boolean contexts. If they're all expressions, then you can easily guarantee that. *raises eyebrow* Either of these should do the job: sum(map(bool, (a, b, c, d))) sum(bool(x) for x in (a, b, c, d)) but I don't see how (arbitrary expression) + (another expression) + ... + (last expression) can have any guarantees applied. I mean, you can't even guarantee that they won't raise an exception. Can you explain what you mean? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Tue, Apr 19, 2011 at 6:43 PM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: but I don't see how (arbitrary expression) + (another expression) + ... + (last expression) can have any guarantees applied. I mean, you can't even guarantee that they won't raise an exception. Can you explain what you mean? What Christian posted isn't something I've often done, but here's something slightly different that exploits the same comparisons-return-summable-values concept: A condition with N subconditions is deemed to be satisfied if a minimum of M of them are true. This is a general case of the boolean Or (N = 2, M = 1) and And (N = 2, M = 2), but does not have a direct equivalent in binary operators. You simply sum the subconditions, compare against M, and you have your answer. if (((port1024) + (!ip.startswith(192.168.)) + (greylist[ip]time()) + (++spewcnt10))=3) // flag this packet as suspicious Contrived example as I don't recall any specifics right now, but this will pick up any packets where three or more of the conditions are met. Useful only in fairly specific situations, but I don't know of any way to do this with just AND/OR/NOT that would be as clear and simple. Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Tue, 2011-04-19 at 19:00 +1000, Chris Angelico wrote: On Tue, Apr 19, 2011 at 6:43 PM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: but I don't see how (arbitrary expression) + (another expression) + ... + (last expression) can have any guarantees applied. I mean, you can't even guarantee that they won't raise an exception. Can you explain what you mean? What Christian posted isn't something I've often done, but here's something slightly different that exploits the same comparisons-return-summable-values concept: A condition with N subconditions is deemed to be satisfied if a minimum of M of them are true. This is a general case of the boolean Or (N = 2, M = 1) and And (N = 2, M = 2), but does not have a direct equivalent in binary operators. You simply sum the subconditions, compare against M, and you have your answer. if (((port1024) + (!ip.startswith(192.168.)) + (greylist[ip]time()) + (++spewcnt10))=3) // flag this packet as suspicious Contrived example as I don't recall any specifics right now, but this will pick up any packets where three or more of the conditions are met. Useful only in fairly specific situations, but I don't know of any way to do this with just AND/OR/NOT that would be as clear and simple. Chris Angelico Exclusive or: if not (True and False and False and False) or (False and True and False and False) or (False and False and True and False) or (False and False and False and True): ... print(True) Maybe a little silly. -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Tue, Apr 19, 2011 at 7:09 AM, Christian Heimes li...@cheimes.de wrote: Am 18.04.2011 21:58, schrieb John Nagle: ?? ?? This is typical for languages which backed into a bool type, rather than having one designed in. ??The usual result is a boolean type with numerical semantics, like ?? True + True 2 I find the behavior rather useful. It allows multi-xor tests like: if a + b + c + d != 1: ?? ??raise ValueError(Exactly one of a, b, c or d must be true.) I guess I never thought about it, but there isn't an 'xor' operator to go along with 'or' and 'and'. Must not be something I need very often. -- Grant Edwards grant.b.edwardsYow! I am having FUN... at I wonder if it's NET FUN or gmail.comGROSS FUN? -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Apr 19, 10:23 am, Grant Edwards inva...@invalid.invalid wrote: On Tue, Apr 19, 2011 at 7:09 AM, Christian Heimes li...@cheimes.de wrote: Am 18.04.2011 21:58, schrieb John Nagle: ?? ?? This is typical for languages which backed into a bool type, rather than having one designed in. ??The usual result is a boolean type with numerical semantics, like ?? True + True 2 I find the behavior rather useful. It allows multi-xor tests like: if a + b + c + d != 1: ?? ??raise ValueError(Exactly one of a, b, c or d must be true.) I guess I never thought about it, but there isn't an 'xor' operator to go along with 'or' and 'and'. Must not be something I need very often. You also can't evaluate xor without evaluating both operands, meaning there is never a short-circuit; both and and or can short-circuit, though. Also boolean xor is the same as !=. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
Jean-Paul Calderone wrote: Also boolean xor is the same as !=. Only if you have booleans. Even without short circuiting, a boolean xor operator could provide the service of automatically booling things for you (is that a word?). Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Mon, Apr 18, 2011 at 3:49 PM, Chris Rebert c...@rebertia.com wrote: Pro: You can do anything. Con: You can do anything. I think someone already beat you to it. They call their invention Lisp. :-P Bah! Lisp comes, out of the box, with far too many features! No no no. If you want the + operator to add two numbers, you have to say so! (Obviously there'll be extensive use of #include or equivalent.) It started out as a serious idea - a really clean language that would, like Lua or Python, be nicely embeddable in larger programs - and specifically, I wanted an expression evaluator that could have d-notation added to it. But the realisation that such a language consisted of a foot, a machine gun, and a belt of ammunition kinda led to it being dropped. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Sun, 17 Apr 2011 22:49:41 -0700, Chris Rebert wrote: Pro: You can do anything. Con: You can do anything. I think someone already beat you to it. They call their invention Lisp. :-P Also Forth. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Apr 16, 1:24 pm, candide cand...@free.invalid wrote: Consider the following code : # -- def bool_equivalent(x): return True if x else False It's faster to write: def bool_equivalent(x): return not not x Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
Le 18/04/2011 10:33, Raymond Hettinger a écrit : # -- def bool_equivalent(x): return True if x else False It's faster to write: def bool_equivalent(x): return not not x faster and ... smarter ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: So in Python 2.2, Python introduced two new built-in names, True and False, with values 1 and 0 respectively: [steve@sylar ~]$ python2.2 Python 2.2.3 (#1, Aug 12 2010, 01:08:27) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type help, copyright, credits or license for more information. True, False (1, 0) type(True) type 'int' Also in Python 2.2 (and I think earlier but I don't have anything earlier to check) there was an interesting property that while all other integers from -1 to 99 were optimised to share a single instance, there were actually 2 instances of 0 and 1: Python 2.2.3 (#1, Sep 26 2006, 18:12:26) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-56)] on linux2 Type help, copyright, credits or license for more information. 2-1 is 1 1 True is 1 0 (True is 1) is 0 0 (True is 1) is False 1 The code for the win32api made use of this fact to determine whether to pass int or bool types through to COM methods. -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On 4/17/2011 5:12 PM, Gregory Ewing wrote: Chris Angelico wrote: Well, of course you can always implement bool as an int; Which Python used to do once upon a time -- and still does in a way, because bool is a subclass of int. The bool type was added mainly to provide a type that prints out as 'True' or 'False' rather than 1 or 0. This can be a considerable help for debugging and keeping the conceptual meaning of one's data clear. This is typical for languages which backed into a bool type, rather than having one designed in. The usual result is a boolean type with numerical semantics, like True + True 2 which ought to either generate a TypeError or be interpreted as or, but due to the legacy botch, does not. Pascal got this right. (A nice feature of Pascal was that packed array of boolean was a bit array). C, which originally lacked a bool type, got it wrong. So did Python. Java is in the middle, with an isolated boolean type but a system that allows casts. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
John Nagle wrote: Pascal got this right. (A nice feature of Pascal was that packed array of boolean was a bit array). C, which originally lacked a bool type, got it wrong. So did Python. If Python had had a boolean type from the beginning, it probably wouldn't have been a subclass of int -- that was more or less forced by backwards compatibility issues. Java is in the middle, with an isolated boolean type but a system that allows casts. I'm not sure that's all that much different from Pascal, where you can use ord() to turn a boolean into an int if you want to. At least you're being explicit. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
Chris Angelico wrote: Remind me some day to finish work on my ultimate programming language, which starts out with a clean slate and lets the programmer define his own operators and everything. Didn't someone already do that and call it lisp? :-) -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
Am 18.04.2011 21:58, schrieb John Nagle: This is typical for languages which backed into a bool type, rather than having one designed in. The usual result is a boolean type with numerical semantics, like True + True 2 I find the behavior rather useful. It allows multi-xor tests like: if a + b + c + d != 1: raise ValueError(Exactly one of a, b, c or d must be true.) Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
Le 17/04/2011 04:39, Ben Finney a écrit : Why do you need to know? (I should have asked that question earlier.) First because I was doubting the true interest of the bool() type. In fact, it appears that it's _semantically_ a shortcut for True if x else False. I could't imagine a builtin function having a so trivial implementation. Compare with float() or int(). I also try to consider how essential the bool() type is. Again compare with int() or str() types. In the orther hand, I'm builting a sort of documentation for learning Python. In order to spell out the purposes of the bool() type, I guessed that giving an equivalence code could help. -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Sun, Apr 17, 2011 at 6:38 PM, candide candide@free.invalid wrote: I also try to consider how essential the bool() type is. Again compare with int() or str() types. Well, of course you can always implement bool as an int; C has done this for decades, and it hasn't killed it. You can also implement integers as strings - REXX manages quite well, and gets some advantages therefrom. But having an explicit bool type has its benefits too. Essential? No. Useful? Certainly. Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
candide candide@free.invalid writes: First because I was doubting the true interest of the bool() type. In fact, it appears that it's _semantically_ a shortcut for True if x else False. That bends my brain. Both ‘True’ and ‘False’ are instances of the ‘bool’ type. So of course the ‘bool’ constructor will return them. What is the “shortcut” you refer to? Remember, the point of a type is to encapsulate both behaviour and an exclusive domain of possible values. The Boolean type is particularly simple, so I don't see why you would be surprised that the behaviour of the ‘bool’ constructor is simple – that's a feature of that type. In the orther hand, I'm builting a sort of documentation for learning Python. Something different from URL:http://docs.python.org/tutorial/. In order to spell out the purposes of the bool() type, I guessed that giving an equivalence code could help. The purpose of the ‘bool’ type is to have a data type which captures the behaviour of only Boolean values, and no other values. -- \ Eccles: “I just saw the Earth through the clouds!” Lew: “Did | `\ it look round?” Eccles: “Yes, but I don't think it saw me.” | _o__)—The Goon Show, _Wings Over Dagenham_ | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Sun, Apr 17, 2011 at 7:38 PM, candide candide@free.invalid wrote: I could't imagine a builtin function having a so trivial implementation. As it was pointed out, its not function, its type, SETBUILTIN(bool, PyBool_Type); While its __new__ is indeed trivial (in essence, it just calls PyObject_IsTrue), it also provides needed comparison ops, repr and other magic methods for the type. You can check Objects/boolobject.c in python repository if its implementation is interesting for you. -- With best regards, Daniel Kluev -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
Le 17/04/2011 11:46, Ben Finney a écrit : candidecandide@free.invalid writes: First because I was doubting the true interest of the bool() type. In fact, it appears that it's _semantically_ a shortcut for True if x else False. That bends my brain. Both ‘True’ and ‘False’ are instances of the ‘bool’ type. So of course the ‘bool’ constructor will return them. A user of the Python programming language can sensibly handle boolean values and write a lot of good code and at the same time completely ignore all the object oriented stuff behind the True and False instances. What is the “shortcut” you refer to? bool(x) is nothing more than a shortcut for the following expression : True if x else False. Compare for instance with the str() type whose implementation is far more complicated. When learning Python, you early and communly use str() type but use sparingly the bool() type. On the other hand, the learner cannot replace himself the service str() provide (hard to write an equivalent code). It's not the case for the bool() type : True if foo else False. Remember, the point of a type is to encapsulate both behaviour and an exclusive domain of possible values. The Boolean type is particularly simple, so I don't see why you would be surprised that the behaviour of the ‘bool’ constructor is simple – that's a feature of that type. In fact, bool() is so simple that at first glance I didn't see any use for it. In the orther hand, I'm builting a sort of documentation for learning Python. Something different fromURL:http://docs.python.org/tutorial/. More : something _opposite_ to the official Python tutorial ;) I found this tutorial very unfriendly and very unsmooth, poorly structured, providing overloaded examples, unable to distinguish essential from incidental, full of bad explanations, etc. OOP presentation is terribly verbose and speculative, chapter on error handling is very hard to follow if you are not aware of the exception mechanism, etc This is not a surprise, as the abstract explains : This tutorial does not attempt to be comprehensive and cover every single feature, or even every commonly used feature. The nice graphical aspect of the tutorial (thanks to Sphinx) doesn't compensate the many weaknesses of the content. -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Sun, Apr 17, 2011 at 8:38 AM, Ben Finney ben+pyt...@benfinney.id.au wrote: It won't look up the *name* ‘bool’, but it will use that object. Any boolean expression is going to be calling the built-in ‘bool’ type constructor. So the answer to the OP's question is no: the function isn't equivalent to the type, because the OP's ‘bool_equivalent’ function necessarily uses the built-in ‘bool’ type, while the reverse is not true. Actually, as I was curious myself, I've checked sources and found that `True if x else False` will _not_ call bool(), it calls PyObject_IsTrue() pretty much directly. import dis def bool2(x): ... return True if x else False ... dis.dis(bool2) 2 0 LOAD_FAST0 (x) 3 POP_JUMP_IF_FALSE 10 6 LOAD_GLOBAL 0 (True) 9 RETURN_VALUE 10 LOAD_GLOBAL 1 (False) 13 RETURN_VALUE case POP_JUMP_IF_FALSE: w = POP(); if (w == Py_True) { Py_DECREF(w); goto fast_next_opcode; } if (w == Py_False) { Py_DECREF(w); JUMPTO(oparg); goto fast_next_opcode; } err = PyObject_IsTrue(w); Py_DECREF(w); if (err 0) err = 0; else if (err == 0) JUMPTO(oparg); else break; continue; So technically these implementations are equivalent besides the fact that bool() is type rather than function. -- With best regards, Daniel Kluev -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
candide candide@free.invalid writes: Le 17/04/2011 11:46, Ben Finney a écrit : What is the “shortcut” you refer to? bool(x) is nothing more than a shortcut for the following expression : True if x else False. We're going around in circles. I've already pointed out that ‘bool(x)’ is what the expression you're talking about will do behind the scenes for the ‘if x’ clause *anyway*. It's bizarre to call that a shortcut. You seem to expect the documentation to be explicit about everything the implementation does. Either that, or you're not making much sense. -- \ “Pray, v. To ask that the laws of the universe be annulled in | `\ behalf of a single petitioner confessedly unworthy.” —Ambrose | _o__) Bierce, _The Devil's Dictionary_, 1906 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
candide wrote: bool(x) is nothing more than a shortcut for the following expression : True if x else False. It's a much shorter and easier-to-read shortcut. Also keep in mind that if-else expressions are quite a recent addition to the language. Before that, we had 'not not x' as another equivalent -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
Chris Angelico wrote: Well, of course you can always implement bool as an int; Which Python used to do once upon a time -- and still does in a way, because bool is a subclass of int. The bool type was added mainly to provide a type that prints out as 'True' or 'False' rather than 1 or 0. This can be a considerable help for debugging and keeping the conceptual meaning of one's data clear. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Mon, 18 Apr 2011 01:22:59 +0200, candide wrote: What is the “shortcut” you refer to? bool(x) is nothing more than a shortcut for the following expression : True if x else False. Nothing more? That's completely incorrect. bool is a type object, not an expression, so you can do things like these: isinstance(Hello world, (float, bool)) False issubclass(bool, list) False types = [str, complex, float, bool] [f(x) for f, x in zip(types, (1, 2, 3, 4))] ['1', (2+0j), 3.0, True] For that reason alone, bool is useful. Compare for instance with the str() type whose implementation is far more complicated. So what? What's your point? Types and functions don't exist because they're *complicated*, but because they're *useful*. bool is useful: in order for True and False to print as True and False, they need to belong to a type that has that behaviour. bool is that type. Consequently, calling bool(x) returns a canonical True/False from any arbitrary object, but that's not the primary purpose for bool existing. When learning Python, you early and communly use str() type but use sparingly the bool() type. So what? What's your point? A little bit of history may make things more clear to you. Up to version 2.1, Python had no built-in True and False values. This *almost always* worked fine, since you can always say (e.g.): if x: do_something() elif y or z: do_something_else() for any objects x, y and z. But it wasn't quite ideal, because: * if flags are written 0 and 1, that frequently fools people into thinking they are meant to be understood as *integer* values rather than boolean values, and they will do arithmetic on those flags; * people coming from other languages were confused and worried by the lack of bools and found it difficult to get used to the Python truth-testing idiom; * people would define a standard pair of True/False values at the top of each module, so they could refer to flags by name rather than value; * there was never any consistency, people would write any of: true = 1; false = 0 FALSE = 0; TRUE = not FALSE True = -1; False = not True or whatever other idiom they preferred, or they'd write custom classes that printed as true/TRUE/True etc. So in Python 2.2, Python introduced two new built-in names, True and False, with values 1 and 0 respectively: [steve@sylar ~]$ python2.2 Python 2.2.3 (#1, Aug 12 2010, 01:08:27) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type help, copyright, credits or license for more information. True, False (1, 0) type(True) type 'int' Then in Python 2.3, Python introduced the bool type, which gave True and False an independent type (bool) with a prettier display. For backwards compatibility reasons, bool is actually a subclass of int, so that code that does arithmetic on flags continues to work. The ternary if operator `true-value if flag else false-value` wasn't introduced until version 2.5. So as you can see, while you are correct *today* that the function call bool(x) is equivalent to True if x else False, for at least seven versions of Python (1.4, 1.5, 1.6, 2.0 through 2.4) that was not correct. Furthermore, why would you write True if x else False (twenty characters) instead of bool(x) (seven characters)? bool is the canonical way to get an explicit boolean value. It's even shorter than not not x (nine characters), and far more obvious than either of the alternatives. You're also correct that there very rarely is a need to explicitly convert arbitrary objects to booleans. That's okay. That's not why bool exists, that's just an occasionally useful side-effect. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
Daniel Kluev dan.kl...@gmail.com writes: Actually, as I was curious myself, I've checked sources and found that `True if x else False` will _not_ call bool(), it calls PyObject_IsTrue() pretty much directly. Sure. By ‘bool(x)’ I'm referring only to the implementation inside that constructor. So technically these implementations are equivalent besides the fact that bool() is type rather than function. What is confusing me is why on Earth this matters to the OP. -- \“Most people don't realize that large pieces of coral, which | `\ have been painted brown and attached to the skull by common | _o__)wood screws, can make a child look like a deer.” —Jack Handey | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Mon, Apr 18, 2011 at 10:22 AM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: types = [str, complex, float, bool] [f(x) for f, x in zip(types, (1, 2, 3, 4))] ['1', (2+0j), 3.0, True] I believe this one would work fine with a function defined as per OP - zip takes callables, which could be types or functions. * if flags are written 0 and 1, that frequently fools people into thinking they are meant to be understood as *integer* values rather than boolean values, and they will do arithmetic on those flags; Depending on what you mean by arithmetic, that can be a good thing. I've frequently, in various languages, used booleans as though they were integers - for instance, indexing a list with an integer plus a condition. Contrived example: mode = 2 ... print (default, default-root, modeA,modeA-root, modeB,modeB-root, ) [mode+mode+(uid==0)] For debugging output, where I want to keep it as self-contained as possible, constructs like these are very handy - especially as they can be embedded inside other expressions. Every language I've used except BASIC has used True == 1, False == 0, but I'm sure there are some which use other values. If True == -1, then you simply subtract the bool from the int instead of adding them. If it's something else, you arrange the array accordingly. * there was never any consistency, people would write any of: true = 1; false = 0 FALSE = 0; TRUE = not FALSE True = -1; False = not True Just as long as someone doesn't use: true = 1; false = -1 which results in the annoying situation that: if x == false: is different from: if x: But on the plus side, TheDailyWTF.com is never short of publishable material... Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: Equivalent code to the bool() built-in function
On 01/-10/-28163 02:59 PM, Daniel Kluev wrote: On Sun, Apr 17, 2011 at 8:38 AM, Ben Finneyben+pyt...@benfinney.id.au wrote: It won't look up the *name* ‘bool’, but it will use that object. Any boolean expression is going to be calling the built-in ‘bool’ type constructor. So the answer to the OP's question is no: the function isn't equivalent to the type, because the OP's ‘bool_equivalent’ function necessarily uses the built-in ‘bool’ type, while the reverse is not true. Actually, as I was curious myself, I've checked sources and found that `True if x else False` will _not_ call bool(), it calls PyObject_IsTrue() pretty much directly. You miss Ben's point, and got it backwards. He didn't say that the function will call the bool() type (constructor), but that it will use the bool type; in other words, it will return True or False. The one that may not is the function bool(). print bool(143) True bool = int print bool(143) 143 Once bool has been reassigned, calling it may not return True or False any more. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: Equivalent code to the bool() built-in function
On Mon, Apr 18, 2011 at 11:46 AM, Dave Angel da...@ieee.org wrote: bool = int Any language that allows you to do this is either awesome or terrifying. Come to think of it, there's not a lot of difference. Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: Equivalent code to the bool() built-in function
On Mon, Apr 18, 2011 at 12:46 PM, Dave Angel da...@ieee.org wrote: He didn't say that the function will call the bool() type (constructor), but that it will use the bool type; Actually, he did say exactly that Any boolean expression is going to be _calling the built-in ‘bool’ type constructor_ (underscores are mine) The one that may not is the function bool(). Its not function, its type. There is no wrapper, bool(x) is direct constructor call. Once bool has been reassigned, calling it may not return True or False any more. Not sure what did you want to show with this example. You just assigned name in locals() namespace. Boolean type itself didn't change because of that and would still call PyObject_IsTrue() and return according constant. Sure, python allows to change namespaces in very flexible way, but we are talking about specific objects (PyBool_Type) rather than pointers to them. in other words, it will return True or False. Well, his code explicitly returns True or False, so this was not doubted. Although I agree with Ben that this doesn't have any practical meaning. bool() is more readable and implementation-independent way to do explicit casting to boolean than the hack in OP. -- With best regards, Daniel Kluev -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
Chris Angelico: Dave Angel: bool = int Any language that allows you to do this is either awesome or terrifying. Come to think of it, there's not a lot of difference. Even better: $ python2.7 -c 'False = True; print False' True Alas: $ python3 -c 'False = True; print(False)' File string, line 1 SyntaxError: assignment to keyword -- Ned Deily, n...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Mon, Apr 18, 2011 at 2:40 PM, Ned Deily n...@acm.org wrote: Chris Angelico: Dave Angel: bool = int Any language that allows you to do this is either awesome or terrifying. Come to think of it, there's not a lot of difference. Even better: $ python2.7 -c 'False = True; print False' True http://bofh.ch/bofh/bofh13.html Alas: $ python3 -c 'False = True; print(False)' File string, line 1 SyntaxError: assignment to keyword Someone in Python3 dev thinks it's a bad idea to shoot yourself in the foot. Remind me some day to finish work on my ultimate programming language, which starts out with a clean slate and lets the programmer define his own operators and everything. Pro: The expression evaluator can be taught to interpret Dungeons Dragons notation - 2d6 means random(1,6)+random(1,6). Con: The same expression might mean something completely different in another program. Pro: You can do anything. Con: You can do anything. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Sun, Apr 17, 2011 at 9:53 PM, Chris Angelico ros...@gmail.com wrote: On Mon, Apr 18, 2011 at 2:40 PM, Ned Deily n...@acm.org wrote: snip Even better: $ python2.7 -c 'False = True; print False' True http://bofh.ch/bofh/bofh13.html Alas: $ python3 -c 'False = True; print(False)' File string, line 1 SyntaxError: assignment to keyword Someone in Python3 dev thinks it's a bad idea to shoot yourself in the foot. Remind me some day to finish work on my ultimate programming language, which starts out with a clean slate and lets the programmer define his own operators and everything. Pro: The expression evaluator can be taught to interpret Dungeons Dragons notation - 2d6 means random(1,6)+random(1,6). Con: The same expression might mean something completely different in another program. Pro: You can do anything. Con: You can do anything. I think someone already beat you to it. They call their invention Lisp. :-P Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Sat, Apr 16, 2011 at 1:24 PM, candide candide@free.invalid wrote: Consider the following code : # -- def bool_equivalent(x): return True if x else False # testing ... def foo(x): return 10*x class C: pass for x in [42, (my,baby), baobab, max, foo, C] + [None, 0, , [], {},()]: print bool(x)==bool_equivalent(x) # -- Is the bool_equivalent() function really equivalent to the bool() built-in function ? The ternary operator, if-statement, and `while` all do the equivalent of an implicit bool() on their condition, so bool_equivalent() will always give the same result as bool() because it's indeed using the moral equivalent of bool() behind the scenes. That is, `True if x else False` conceptually gets compiled down to `True if bool(x) == 1 else False` (but without doing a run-time lookup of bool). Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
candide candide@free.invalid writes: Is the bool_equivalent() function really equivalent to the bool() built-in function ? The ‘bool’ built-in is not a function. type(bool) type 'type' -- \ “Generally speaking, the errors in religion are dangerous; | `\those in philosophy only ridiculous.” —David Hume, _A Treatise | _o__) of Human Nature_, 1739 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
Chris Rebert c...@rebertia.com writes: That is, `True if x else False` conceptually gets compiled down to `True if bool(x) == 1 else False` (but without doing a run-time lookup of bool). It won't look up the *name* ‘bool’, but it will use that object. Any boolean expression is going to be calling the built-in ‘bool’ type constructor. So the answer to the OP's question is no: the function isn't equivalent to the type, because the OP's ‘bool_equivalent’ function necessarily uses the built-in ‘bool’ type, while the reverse is not true. -- \“Perchance you who pronounce my sentence are in greater fear | `\ than I who receive it.” —Giordano Bruno, burned at the stake by | _o__) the Catholic church for the heresy of heliocentrism, 1600-02-16 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
Le 16/04/2011 23:38, Ben Finney a écrit : So the answer to the OP's question is no: the function isn't equivalent to the type, Can bool() type and bool_equivalent() function return different values ? because the OP's ‘bool_equivalent’ function necessarily uses the built-in ‘bool’ type, while the reverse is not true. The documentation doesn't seem to state it performs this call. I'm referring to -- §5.10 Boolean operations in Document Reference Python 2.7 -- bool()'s description in Library Reference -- §5.1 Truth Value Testing in Library Reference -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
Le 16/04/2011 23:13, Ben Finney a écrit : The ‘bool’ built-in is not a function. type(bool) type 'type' Oops, unfortunate confusion!! but built-in types and built-in functions are sometimes so similar from the user's point of view ;) All the same, you can notice that the official documentation describes bool() as a built-in function, cf. http://docs.python.org/library/functions.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
On Sat, Apr 16, 2011 at 4:51 PM, candide candide@free.invalid wrote: Le 16/04/2011 23:38, Ben Finney a écrit : So the answer to the OP's question is no: the function isn't equivalent to the type, Can bool() type and bool_equivalent() function return different values ? No. The distinction being drawn is rather pedantic, IMO. because the OP's ‘bool_equivalent’ function necessarily uses the built-in ‘bool’ type, while the reverse is not true. The documentation doesn't seem to state it performs this call. This is why I used the qualifiers the equivalent of and conceptually. I'm referring to -- §5.10 Boolean operations in Document Reference Python 2.7 -- bool()'s description in Library Reference bool([x])Convert a value to a Boolean, using the standard truth testing procedure. -- §5.1 Truth Value Testing in Library Reference This describes the standard truth testing procedure. Ideally, this section would be linked to in bool()'s docs. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent code to the bool() built-in function
candide candide@free.invalid writes: Le 16/04/2011 23:13, Ben Finney a écrit : The ‘bool’ built-in is not a function. Oops, unfortunate confusion!! but built-in types and built-in functions are sometimes so similar from the user's point of view ;) Yes, intentionally so, because: All the same, you can notice that the official documentation describes bool() as a built-in function, cf. http://docs.python.org/library/functions.html sometimes functions are replaced by types, or vice versa, and the user code doesn't have to know. Sadly, the result can be that the documentation is sometimes out of date with the implementation :-) candide candide@free.invalid writes: Le 16/04/2011 23:38, Ben Finney a écrit : So the answer to the OP's question is no: the function isn't equivalent to the type, Can bool() type and [my example] bool_equivalent() function return different values ? Why do you need to know? (I should have asked that question earlier.) because the OP's ‘bool_equivalent’ function necessarily uses the built-in ‘bool’ type, while the reverse is not true. The documentation doesn't seem to state it performs this call. Right, just as APIs that return strings won't explicitly talk about calling the ‘str’ type constructor. I don't understand why you expect that. -- \ “My business is to teach my aspirations to conform themselves | `\ to fact, not to try and make facts harmonise with my | _o__) aspirations.“ —Thomas Henry Huxley, 1860-09-23 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list