"0 in [True,False]" returns True

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • bonono@gmail.com

    #16
    Re: "0 in [True,False]" returns True


    Erik Max Francis wrote:[color=blue]
    > Paul Rubin wrote:
    >[color=green]
    > > Steve Holden <steve@holdenwe b.com> writes:[color=darkred]
    > >> The really interesting question your post raises, though, is "Why do
    > >> you feel it's necessary to test to see whether a variable is a
    > >> Boolean?".[/color]
    > >
    > > What's the point of having Booleans, if you can't tell them from integers?[/color]
    >
    > Because
    >
    > return True
    >
    > is clearer than
    >
    > return 1
    >
    > if the purpose of the return value is to indicate a Boolean rather than
    > an arbitrary integer.
    >[/color]
    True, but if that is the only reason, Two built-in value of
    True/False(0/1) serves the need which is what is now(well sort of). Why
    have seperate types and distinguish them ?
    [color=blue][color=green][color=darkred]
    >>>True == 1[/color][/color][/color]
    True[color=blue][color=green][color=darkred]
    >>>True is 1[/color][/color][/color]
    False

    Comment

    • Steve Holden

      #17
      Re: &quot;0 in [True,False]&quot; returns True

      Antoon Pardon wrote:[color=blue]
      > Op 2005-12-13, Steve Holden schreef <steve@holdenwe b.com>:
      >[color=green]
      >>Pierre Quentel wrote:
      >>[color=darkred]
      >>>Hi all,
      >>>
      >>>In some program I was testing if a variable was a boolean, with this
      >>>test : if v in [True,False]
      >>>
      >>>My script didn't work in some cases and I eventually found that for v =
      >>>0 the test returned True
      >>>
      >>>So I changed my test for the obvious "if type(v) is bool", but I still
      >>>find it confusing that "0 in [True,False]" returns True
      >>>
      >>>By the way, I searched in the documentation what "obj in list" meant and
      >>>couldn't find a precise definition (does it test for equality or
      >>>identity with one of the values in list ? equality, it seems) ; did I
      >>>miss something ?
      >>>[/color]
      >>
      >>It actually uses the __contains__() method of the right-hand operand,
      >>and in the case of a list that will test for equality of the left-hand
      >>operand to one of the list elements. Since False == 0 that's why you see
      >>what you do.
      >>
      >>The really interesting question your post raises, though, is "Why do you
      >>feel it's necessary to test to see whether a variable is a Boolean?".[/color]
      >
      >
      > I can give you one example. I have written a tube class. A tube behaves
      > like Queue but it has additional code so that it can be registed with
      > gtk in the same way as file descriptor can be registered with
      > io_add_watch. The way this is implemented is by registering an idle
      > handler when the tube is not empty and removing it when the tube is
      > empty. So I have a variable cb_src (for callback source) that can be
      > a boolean or an integer. The possible values are
      >
      > False: Not registered by the user
      > True: Registered by the user but no nternal idle callback registerd
      > a number: gtk integer ID, from the registered idle callback handler.
      >[/color]
      Well I guess you'd better hope that gtk never returns a zero or one, then.

      Note, though, that True and False are defined to be singleton instances,
      so it *is* permissible to say

      if i is False:
      [color=blue][color=green][color=darkred]
      >>> 0 is False[/color][/color][/color]
      False[color=blue][color=green][color=darkred]
      >>> 1 is True[/color][/color][/color]
      False[color=blue][color=green][color=darkred]
      >>>[/color][/color][/color]

      However I must say the coupling in that interface has a very definite
      code smell. Why not use two variables, a Boolean "registered " and an
      integer ID that is meaningless when registered is False?

      regards
      Steve
      --
      Steve Holden +44 150 684 7255 +1 800 494 3119
      Holden Web LLC www.holdenweb.com
      PyCon TX 2006 www.python.org/pycon/

      Comment

      • Erik Max Francis

        #18
        Re: &quot;0 in [True,False]&quot; returns True

        bonono@gmail.co m wrote:
        [color=blue]
        > True, but if that is the only reason, Two built-in value of
        > True/False(0/1) serves the need which is what is now(well sort of). Why
        > have seperate types and distinguish them ?[/color]

        Because of this:

        x = True
        y = 1 # but I mean it to represent true

        print x, y

        Besides, it's not the only reason, but it's a good one.

        --
        Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
        San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
        Ipsa scientia potestas est. "Knowledge itself is power."
        -- a Latin proverb

        Comment

        • bonono@gmail.com

          #19
          Re: &quot;0 in [True,False]&quot; returns True


          Erik Max Francis wrote:[color=blue]
          > bonono@gmail.co m wrote:
          >[color=green]
          > > True, but if that is the only reason, Two built-in value of
          > > True/False(0/1) serves the need which is what is now(well sort of). Why
          > > have seperate types and distinguish them ?[/color]
          >
          > Because of this:
          >
          > x = True
          > y = 1 # but I mean it to represent true
          >
          > print x, y
          >
          > Besides, it's not the only reason, but it's a good one.
          >[/color]
          True too, and could be the reason(or similar too) why the OP wants to
          test the type rather than the logical value of it.

          Comment

          • Erik Max Francis

            #20
            Re: &quot;0 in [True,False]&quot; returns True

            bonono@gmail.co m wrote:
            [color=blue]
            > True too, and could be the reason(or similar too) why the OP wants to
            > test the type rather than the logical value of it.[/color]

            The type is for the self-documentation purposes. The value is the same;
            so no, that's not a good reason either.

            --
            Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
            San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
            Ipsa scientia potestas est. "Knowledge itself is power."
            -- a Latin proverb

            Comment

            • Duncan Booth

              #21
              Re: &quot;0 in [True,False]&quot; returns True

              wrote:
              [color=blue][color=green]
              >> if the purpose of the return value is to indicate a Boolean rather than
              >> an arbitrary integer.
              >>[/color]
              > True, but if that is the only reason, Two built-in value of
              > True/False(0/1) serves the need which is what is now(well sort of). Why
              > have seperate types and distinguish them ?
              >[color=green][color=darkred]
              >>>>True == 1[/color][/color]
              > True[color=green][color=darkred]
              >>>>True is 1[/color][/color]
              > False
              >[/color]

              Within Python that would probably be sufficient, but some external
              libraries e.g. COM or XMLRPC make a distinction between integers and
              booleans, so it makes it more convenient if there is a defined way to
              distinguish between calling one overloaded method which takes an integer or
              another of the same name which take a boolean.

              Before Python had a separate boolean type there was an implementation
              detail which mean that it was possible to distinguish the constants 0 and 1
              which were generated by a comparison from other constant 0 and 1 values.
              The python COM libraries used this 'feature'.

              XMLRPC has its own Boolean class which is used in Python versions where
              boolean is not a builtin.

              Another reason to have a boolean type is of course to provide a cast:

              def isNameSet(self) :
              return boolean(self.na me)

              instead of:

              def isNameSet(self) :
              if self.name:
              return True
              else:
              return False

              Comment

              • quentel.pierre@wanadoo.fr

                #22
                Re: &quot;0 in [True,False]&quot; returns True

                Ok, I'll explain why I wanted to test if the value was a boolean

                I have a program that generates HTML tags with attributes. The
                principle is that
                TAG('text',arg1 =val1,arg2=val2 )
                generates
                <TAG arg1="val1" arg2="val2">tex t</TAG>

                For HTML attributes that don't have an explicit value (such as the
                SELECTED attribute in OPTION) the keyword argument to the function must
                have the value True

                My program has a class for each tag, all derived from a generic TAG
                class whose __init__ method takes the arguments :
                def __init__(self, innerHTML="", **attrs):

                I have to handle differently the cases where the value is a boolean or
                another type:
                - if it's a boolean then if the value is True, generate the argument
                name ; if the value is False, don't generate anything
                - if it's not a boolean, generate arg="val". Specifically, it val is 0,
                generate val = "0"

                Testing with "if v:" as suggested would fail for val = 0

                Anyway, I exposed my silly "if v in [True,False]" just to give my
                opinion that I found confusing that
                0 in [True,False]
                or (boolean type checking set aside)
                0 in [1,range(2),Fals e,'text']

                return True

                Regards,
                Pierre

                Comment

                • bonono@gmail.com

                  #23
                  Re: &quot;0 in [True,False]&quot; returns True


                  Erik Max Francis wrote:[color=blue]
                  > bonono@gmail.co m wrote:
                  >[color=green]
                  > > True too, and could be the reason(or similar too) why the OP wants to
                  > > test the type rather than the logical value of it.[/color]
                  >
                  > The type is for the self-documentation purposes. The value is the same;
                  > so no, that's not a good reason either.
                  >[/color]
                  I don't know why he wants it, let alone whether it is a good or bad
                  reason. The only thing I read from his post is that he wants to
                  distinguish the type, why and how it fits in his big picture, no one
                  but he knows. It could be for similar reason, say to document the
                  content of data, store it in text file, translate it to another
                  language(say converting python object to js object but I forgot if
                  javascript treat 0/1 the same way as python).

                  Comment

                  • quentel.pierre@wanadoo.fr

                    #24
                    Re: &quot;0 in [True,False]&quot; returns True

                    Thanks for the link Carsten, the explanation is clear

                    I didn't know where to search in the Python documentation, there isn't
                    a section about keywords (always wondered why without daring to say -
                    now it's done). So I typed ' "in" operator Python ' in Google, which
                    gave :
                    - on the first page a link to AM Kuchling's and Moshe Zadka's "What's
                    new in Python 2.0" which said :
                    "obj in seq returns true if obj is present in the sequence seq; Python
                    computes this by simply trying every index of the sequence until either
                    obj is found or an IndexError is encountered"
                    - on the second page a link to the Python tutorial that says : "The
                    comparison operators in and not in check whether a value occurs (does
                    not occur) in a sequence"

                    I couldn't tell if "present in the sequence" or "obj is found" or
                    "occurs/does not occur in a sequence" meant "is equal to" or "is the
                    same object as". The answer you pointed me to is clear, but for some
                    reason I didn't have the idea of looking in the section "Sequence Types
                    -- str, unicode, list, tuple, buffer, xrange" for the definition of
                    "in" (after all "in" is also used in list comprehensions, generator
                    expressions, exec, etc... and for iteration on iterators)

                    Regards,
                    Pierre

                    Comment

                    • Duncan Booth

                      #25
                      Re: &quot;0 in [True,False]&quot; returns True

                      wrote:
                      [color=blue]
                      > For HTML attributes that don't have an explicit value (such as the
                      > SELECTED attribute in OPTION) the keyword argument to the function must
                      > have the value True
                      >[/color]

                      A better way to do this (given that HTML defines exactly which attributes
                      do not take a value) is to use the attribute name and simply generate the
                      attribute only if the value is non-false.

                      From Zope's TAL parser:

                      BOOLEAN_HTML_AT TRS = [
                      # List of Boolean attributes in HTML that may be given in
                      # minimized form (e.g. <img ismap> rather than <img ismap="">)
                      # From http://www.w3.org/TR/xhtml1/#guidelines (C.10)
                      "compact", "nowrap", "ismap", "declare", "noshade", "checked",
                      "disabled", "readonly", "multiple", "selected", "noresize",
                      "defer"
                      ]

                      EMPTY_HTML_TAGS = [
                      # List of HTML tags with an empty content model; these are
                      # rendered in minimized form, e.g. <img />.
                      # From http://www.w3.org/TR/xhtml1/#dtds
                      "base", "meta", "link", "hr", "br", "param", "img", "area",
                      "input", "col", "basefont", "isindex", "frame",
                      ]

                      Comment

                      • Fredrik Lundh

                        #26
                        Re: &quot;0 in [True,False]&quot; returns True

                        Duncan Booth wrote:
                        [color=blue]
                        > Another reason to have a boolean type is of course to provide a cast:
                        >
                        > def isNameSet(self) :
                        > return boolean(self.na me)
                        >
                        > instead of:
                        >
                        > def isNameSet(self) :
                        > if self.name:
                        > return True
                        > else:
                        > return False[/color]

                        given that Python already had a function for this, that wasn't
                        much of a reason:
                        [color=blue][color=green][color=darkred]
                        >>> help(operator.t ruth)[/color][/color][/color]
                        Help on built-in function truth in module operator:

                        truth(...)
                        truth(a) -- Return True if a is true, False otherwise.

                        (truth returned 1 or 0 in pre-boolean versions)

                        (btw, instead of speculating about the rationale, why don't you all
                        go and read Guido's PEP ?)

                        </F>



                        Comment

                        • bonono@gmail.com

                          #27
                          Re: &quot;0 in [True,False]&quot; returns True


                          Fredrik Lundh wrote:[color=blue]
                          > Duncan Booth wrote:
                          >[color=green]
                          > > Another reason to have a boolean type is of course to provide a cast:
                          > >
                          > > def isNameSet(self) :
                          > > return boolean(self.na me)
                          > >
                          > > instead of:
                          > >
                          > > def isNameSet(self) :
                          > > if self.name:
                          > > return True
                          > > else:
                          > > return False[/color]
                          >
                          > given that Python already had a function for this, that wasn't
                          > much of a reason:
                          >[color=green][color=darkred]
                          > >>> help(operator.t ruth)[/color][/color]
                          > Help on built-in function truth in module operator:
                          >
                          > truth(...)
                          > truth(a) -- Return True if a is true, False otherwise.
                          >
                          > (truth returned 1 or 0 in pre-boolean versions)
                          >[/color]
                          I see you skip another use case of XMLRPC Duncan mentioned, is that a
                          valid reason ?

                          Comment

                          • Fredrik Lundh

                            #28
                            Re: &quot;0 in [True,False]&quot; returns True

                            Duncan Booth wrote:[color=blue]
                            >[color=green]
                            > > For HTML attributes that don't have an explicit value (such as the
                            > > SELECTED attribute in OPTION) the keyword argument to the function must
                            > > have the value True[/color]
                            >
                            > A better way to do this (given that HTML defines exactly which attributes
                            > do not take a value) is to use the attribute name and simply generate the
                            > attribute only if the value is non-false.[/color]

                            footnote: strictly speaking, minimized attributes have values but no names;
                            it's up to the parser to determine what attribute you're setting when you
                            specify the value.

                            (for example, in <img ismap>, "ismap" is the value, not the attribute name.
                            it's up to the parser to figure out (from the DTD) that this value can only
                            be used by the "ismap" attribute, and interpret it as <img ismap=ismap>)

                            </F>



                            Comment

                            • Fredrik Lundh

                              #29
                              Re: &quot;0 in [True,False]&quot; returns True

                              bonono@gmail.co m wrote:
                              [color=blue]
                              > I see you skip another use case of XMLRPC Duncan mentioned, is that a
                              > valid reason ?[/color]

                              the PEP has the answer. also see my reply to Erik Max Francis:



                              (the silly Boolean class in that post is taken from Python's xmlrpclib library)

                              </F>



                              Comment

                              • Stefan Rank

                                #30
                                Re: &quot;0 in [True,False]&quot; returns True

                                on 13.12.2005 11:39 Fredrik Lundh said the following:[color=blue]
                                > Duncan Booth wrote:[color=green]
                                >>Another reason to have a boolean type is of course to provide a cast:
                                >>
                                >> def isNameSet(self) :
                                >> return boolean(self.na me)[/color][/color]
                                [snip][color=blue]
                                >
                                > given that Python already had a function for this, that wasn't
                                > much of a reason:
                                >[color=green][color=darkred]
                                >>>>help(operat or.truth)[/color][/color]
                                >
                                > Help on built-in function truth in module operator:
                                >
                                > truth(...)
                                > truth(a) -- Return True if a is true, False otherwise.
                                >[/color]
                                [snip]

                                As operator.truth( ) is equivalent to bool()
                                and as it is the only thing in operator that is not really reflecting an
                                operator, I had a look into PEP3000 to see if (the redundant)
                                operator.truth is going to be removed. It is not mentioned.

                                (not that I really care, but I thought I could provide something
                                productively new to discuss about, to end the "why is bool an int?"
                                discussion ;-)

                                stefan

                                Comment

                                Working...