Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #3345 > unrolled thread

Equivalent code to the bool() built-in function

Started bycandide <candide@free.invalid>
First post2011-04-16 22:24 +0200
Last post2011-04-18 11:19 +0200
Articles 20 on this page of 46 — 18 participants

Back to article view | Back to comp.lang.python


Contents

  Equivalent code to the bool() built-in function candide <candide@free.invalid> - 2011-04-16 22:24 +0200
    Re: Equivalent code to the bool() built-in function Chris Rebert <clp2@rebertia.com> - 2011-04-16 13:58 -0700
      Re: Equivalent code to the bool() built-in function Ben Finney <ben+python@benfinney.id.au> - 2011-04-17 07:38 +1000
        Re: Equivalent code to the bool() built-in function candide <candide@free.invalid> - 2011-04-17 01:51 +0200
          Re: Equivalent code to the bool() built-in function Chris Rebert <clp2@rebertia.com> - 2011-04-16 17:16 -0700
          Re: Equivalent code to the bool() built-in function Ben Finney <ben+python@benfinney.id.au> - 2011-04-17 12:39 +1000
            Re: Equivalent code to the bool() built-in function candide <candide@free.invalid> - 2011-04-17 10:38 +0200
              Re: Equivalent code to the bool() built-in function Chris Angelico <rosuav@gmail.com> - 2011-04-17 18:46 +1000
                Re: Equivalent code to the bool() built-in function Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2011-04-18 12:12 +1200
                  Re: Equivalent code to the bool() built-in function John Nagle <nagle@animats.com> - 2011-04-18 12:58 -0700
                    Re: Equivalent code to the bool() built-in function Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2011-04-19 12:18 +1200
                    Re: Equivalent code to the bool() built-in function Christian Heimes <lists@cheimes.de> - 2011-04-19 03:39 +0200
                    Re: Equivalent code to the bool() built-in function Kushal Kumaran <kushal.kumaran+python@gmail.com> - 2011-04-19 11:53 +0530
                      Re: Equivalent code to the bool() built-in function Grant Edwards <invalid@invalid.invalid> - 2011-04-19 14:23 +0000
                        Re: Equivalent code to the bool() built-in function Jean-Paul Calderone <calderone.jeanpaul@gmail.com> - 2011-04-19 08:43 -0700
                          Re: Equivalent code to the bool() built-in function Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2011-04-20 11:59 +1200
                        Re: Equivalent code to the bool() built-in function Albert van der Horst <albert@spenarnc.xs4all.nl> - 2011-04-28 16:45 +0000
                          Re: Equivalent code to the bool() built-in function Duncan Booth <duncan.booth@invalid.invalid> - 2011-04-28 17:18 +0000
                    Re: Equivalent code to the bool() built-in function Chris Angelico <rosuav@gmail.com> - 2011-04-19 16:26 +1000
                      Re: Equivalent code to the bool() built-in function Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-04-19 08:43 +0000
                        Re: Equivalent code to the bool() built-in function Chris Angelico <rosuav@gmail.com> - 2011-04-19 19:00 +1000
                        Re: Equivalent code to the bool() built-in function Westley Martínez <anikom15@gmail.com> - 2011-04-19 06:43 -0700
              Re: Equivalent code to the bool() built-in function Ben Finney <ben+python@benfinney.id.au> - 2011-04-17 19:46 +1000
                Re: Equivalent code to the bool() built-in function candide <candide@free.invalid> - 2011-04-18 01:22 +0200
                  Re: Equivalent code to the bool() built-in function Ben Finney <ben+python@benfinney.id.au> - 2011-04-18 09:46 +1000
                  Re: Equivalent code to the bool() built-in function Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2011-04-18 12:08 +1200
                  Re: Equivalent code to the bool() built-in function Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-04-18 00:22 +0000
                    Re: Equivalent code to the bool() built-in function Chris Angelico <rosuav@gmail.com> - 2011-04-18 10:52 +1000
                    Re: Equivalent code to the bool() built-in function Duncan Booth <duncan.booth@invalid.invalid> - 2011-04-18 10:01 +0000
              Re: Equivalent code to the bool() built-in function Daniel Kluev <dan.kluev@gmail.com> - 2011-04-17 21:11 +1100
        Re: Equivalent code to the bool() built-in function Daniel Kluev <dan.kluev@gmail.com> - 2011-04-18 10:45 +1100
          Re: Equivalent code to the bool() built-in function Ben Finney <ben+python@benfinney.id.au> - 2011-04-18 10:36 +1000
        Re: Re: Equivalent code to the bool() built-in function Chris Angelico <rosuav@gmail.com> - 2011-04-18 11:52 +1000
        Re: Re: Equivalent code to the bool() built-in function Dave Angel <davea@ieee.org> - 2011-04-17 21:46 -0400
        Re: Re: Equivalent code to the bool() built-in function Daniel Kluev <dan.kluev@gmail.com> - 2011-04-18 14:16 +1100
        Re: Equivalent code to the bool() built-in function Ned Deily <nad@acm.org> - 2011-04-17 21:40 -0700
        Re: Equivalent code to the bool() built-in function Chris Angelico <rosuav@gmail.com> - 2011-04-18 14:53 +1000
          Re: Equivalent code to the bool() built-in function Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2011-04-19 12:22 +1200
            Re: Equivalent code to the bool() built-in function Albert van der Horst <albert@spenarnc.xs4all.nl> - 2011-04-28 16:55 +0000
        Re: Equivalent code to the bool() built-in function Chris Rebert <clp2@rebertia.com> - 2011-04-17 22:49 -0700
          Re: Equivalent code to the bool() built-in function Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-04-18 06:14 +0000
        Re: Equivalent code to the bool() built-in function Chris Angelico <rosuav@gmail.com> - 2011-04-18 16:03 +1000
    Re: Equivalent code to the bool() built-in function Ben Finney <ben+python@benfinney.id.au> - 2011-04-17 07:13 +1000
      Re: Equivalent code to the bool() built-in function candide <candide@free.invalid> - 2011-04-17 01:51 +0200
    Re: Equivalent code to the bool() built-in function Raymond Hettinger <python@rcn.com> - 2011-04-18 01:33 -0700
      Re: Equivalent code to the bool() built-in function candide <candide@free.invalid> - 2011-04-18 11:19 +0200

Page 2 of 3 — ← Prev page 1 [2] 3  Next page →


#3553

FromChris Angelico <rosuav@gmail.com>
Date2011-04-19 19:00 +1000
Message-ID<mailman.555.1303203623.9059.python-list@python.org>
In reply to#3551
On Tue, Apr 19, 2011 at 6:43 PM, Steven D'Aprano
<steve+comp.lang.python@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 (((port<1024) + (!ip.startswith("192.168.")) +
(greylist[ip]>time()) + (++spewcnt>10))>=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

[toc] | [prev] | [next] | [standalone]


#3560

FromWestley Martínez <anikom15@gmail.com>
Date2011-04-19 06:43 -0700
Message-ID<mailman.559.1303220632.9059.python-list@python.org>
In reply to#3551
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.python@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 (((port<1024) + (!ip.startswith("192.168.")) +
> (greylist[ip]>time()) + (++spewcnt>10))>=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.

[toc] | [prev] | [next] | [standalone]


#3385

FromBen Finney <ben+python@benfinney.id.au>
Date2011-04-17 19:46 +1000
Message-ID<878vv9gqhq.fsf@benfinney.id.au>
In reply to#3378
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

[toc] | [prev] | [next] | [standalone]


#3435

Fromcandide <candide@free.invalid>
Date2011-04-18 01:22 +0200
Message-ID<4dab7654$0$7290$426a74cc@news.free.fr>
In reply to#3385
Le 17/04/2011 11:46, Ben Finney a écrit :
 > 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.

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 from<URL: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.

[toc] | [prev] | [next] | [standalone]


#3438

FromBen Finney <ben+python@benfinney.id.au>
Date2011-04-18 09:46 +1000
Message-ID<87liz8fnl0.fsf@benfinney.id.au>
In reply to#3435
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

[toc] | [prev] | [next] | [standalone]


#3439

FromGregory Ewing <greg.ewing@canterbury.ac.nz>
Date2011-04-18 12:08 +1200
Message-ID<911dnaF58aU1@mid.individual.net>
In reply to#3435
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

[toc] | [prev] | [next] | [standalone]


#3441

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2011-04-18 00:22 +0000
Message-ID<4dab845d$0$29986$c3e8da3$5496439d@news.astraweb.com>
In reply to#3435
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

[toc] | [prev] | [next] | [standalone]


#3445

FromChris Angelico <rosuav@gmail.com>
Date2011-04-18 10:52 +1000
Message-ID<mailman.489.1303087959.9059.python-list@python.org>
In reply to#3441
On Mon, Apr 18, 2011 at 10:22 AM, Steven D'Aprano
<steve+comp.lang.python@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

[toc] | [prev] | [next] | [standalone]


#3481

FromDuncan Booth <duncan.booth@invalid.invalid>
Date2011-04-18 10:01 +0000
Message-ID<Xns9ECB701D0C11Fduncanbooth@127.0.0.1>
In reply to#3441
Steven D'Aprano <steve+comp.lang.python@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

[toc] | [prev] | [next] | [standalone]


#3388

FromDaniel Kluev <dan.kluev@gmail.com>
Date2011-04-17 21:11 +1100
Message-ID<mailman.457.1303035118.9059.python-list@python.org>
In reply to#3378
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

[toc] | [prev] | [next] | [standalone]


#3437

FromDaniel Kluev <dan.kluev@gmail.com>
Date2011-04-18 10:45 +1100
Message-ID<mailman.485.1303083918.9059.python-list@python.org>
In reply to#3349
On Sun, Apr 17, 2011 at 8:38 AM, Ben Finney <ben+python@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_FAST                0 (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

[toc] | [prev] | [next] | [standalone]


#3444

FromBen Finney <ben+python@benfinney.id.au>
Date2011-04-18 10:36 +1000
Message-ID<87hb9wfla1.fsf@benfinney.id.au>
In reply to#3437
Daniel Kluev <dan.kluev@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

[toc] | [prev] | [next] | [standalone]


#3448

FromChris Angelico <rosuav@gmail.com>
Date2011-04-18 11:52 +1000
Message-ID<mailman.491.1303091579.9059.python-list@python.org>
In reply to#3349
On Mon, Apr 18, 2011 at 11:46 AM, Dave Angel <davea@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

[toc] | [prev] | [next] | [standalone]


#3451

FromDave Angel <davea@ieee.org>
Date2011-04-17 21:46 -0400
Message-ID<mailman.490.1303091226.9059.python-list@python.org>
In reply to#3349
On 01/-10/-28163 02:59 PM, Daniel Kluev wrote:
> On Sun, Apr 17, 2011 at 8:38 AM, Ben Finney<ben+python@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

[toc] | [prev] | [next] | [standalone]


#3452

FromDaniel Kluev <dan.kluev@gmail.com>
Date2011-04-18 14:16 +1100
Message-ID<mailman.494.1303096602.9059.python-list@python.org>
In reply to#3349
On Mon, Apr 18, 2011 at 12:46 PM, Dave Angel <davea@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

[toc] | [prev] | [next] | [standalone]


#3455

FromNed Deily <nad@acm.org>
Date2011-04-17 21:40 -0700
Message-ID<mailman.495.1303101664.9059.python-list@python.org>
In reply to#3349
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,
 nad@acm.org

[toc] | [prev] | [next] | [standalone]


#3456

FromChris Angelico <rosuav@gmail.com>
Date2011-04-18 14:53 +1000
Message-ID<mailman.496.1303102402.9059.python-list@python.org>
In reply to#3349
On Mon, Apr 18, 2011 at 2:40 PM, Ned Deily <nad@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

[toc] | [prev] | [next] | [standalone]


#3512

FromGregory Ewing <greg.ewing@canterbury.ac.nz>
Date2011-04-19 12:22 +1200
Message-ID<9142usF51iU2@mid.individual.net>
In reply to#3456
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

[toc] | [prev] | [next] | [standalone]


#4234

FromAlbert van der Horst <albert@spenarnc.xs4all.nl>
Date2011-04-28 16:55 +0000
Message-ID<lkdgbp.i1l@spenarnc.xs4all.nl>
In reply to#3512
In article <9142usF51iU2@mid.individual.net>,
Gregory Ewing  <greg.ewing@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@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst

[toc] | [prev] | [next] | [standalone]


#3457

FromChris Rebert <clp2@rebertia.com>
Date2011-04-17 22:49 -0700
Message-ID<mailman.497.1303105783.9059.python-list@python.org>
In reply to#3349
On Sun, Apr 17, 2011 at 9:53 PM, Chris Angelico <rosuav@gmail.com> wrote:
> On Mon, Apr 18, 2011 at 2:40 PM, Ned Deily <nad@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

[toc] | [prev] | [next] | [standalone]


Page 2 of 3 — ← Prev page 1 [2] 3  Next page →

Back to top | Article view | comp.lang.python


csiph-web