testing for valid reference: obj vs. None!=obs vs. obj is not None

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • alf

    #1

    testing for valid reference: obj vs. None!=obs vs. obj is not None

    Hi,

    I have a reference to certain objects. What is the most pythonic way to
    test for valid reference:

    if obj:

    if None!=obs:

    if obj is not None:

    --
    alfz1
  • Carl Banks

    #2
    Re: testing for valid reference: obj vs. None!=obs vs. obj is not None


    alf wrote:
    Hi,
    >
    I have a reference to certain objects. What is the most pythonic way to
    test for valid reference:
    >
    if obj:
    >
    if None!=obs:
    >
    if obj is not None:
    If you're checking whether an object is None or not, the third is the
    best way.

    Some people might say you should use the first: this works sometimes,
    but sometimes an object that is not None can be false, in which case
    this test will fail. (I'll give you an example of one place where it
    bit me: in ElementTree. An Element is false if there are no
    subelements, thus to test whether a certain element exist, you can't
    just say "if aaa.find('bbb') ", because a bbb tag exists, it is false
    unless it has subelements of its own. You must instead say "if
    aaa.find('bbb') is not None".)

    The second test is slower than the first and adds nothing. Whether
    something is None is an identity test; identity tests should use is.


    Carl Banks

    Comment

    • Bruno Desthuilliers

      #3
      Re: testing for valid reference: obj vs. None!=obs vs. obj is notNone

      alf a écrit :
      Hi,
      >
      I have a reference to certain objects. What is the most pythonic way to
      test for valid reference:
      >
      if obj:
      Don't do this:

      for o in [0, '', [], {}, ()]:
      print obj, bool(obj), obj is None

      if None!=obs:
      In python, assignement is a statement, not an expression, so there's no
      way you could write 'if obj = None' by mistake (-syntax error). So
      this style is unpythonic. Also, None is a singleton, and identity test
      is way faster than equality test.
      if obj is not None:
      That's the good one.

      Comment

      • BJörn Lindqvist

        #4
        Re: testing for valid reference: obj vs. None!=obs vs. obj is not None

        I have a reference to certain objects. What is the most pythonic way to
        test for valid reference:
        >
        if obj:
        >
        if None!=obs:
        >
        if obj is not None:
        The third way is the most precise way. It is often used in combination
        with default arguments.

        def __init__(self, amount = None):
        if amount is not None:
        self.amount = amount
        else:
        self.amount = self.calc_amoun t()

        However, the first way is shorter and more concise. It really depends
        on what obj is supposed to be and where you get obj from. If it is a
        database and obj is an instance:

        obj = db.get("sometab le", id = 33)

        (assuming db.get returns None if the object isn't found) Then "if
        obj:" clearly is the right test. In general, I think "If obj:" is the
        right answer, except when dealing with default arguments. And you must
        be aware that some objects, like 0, [] or {} evaluate to False -- it
        is possible that that could create some subtle bugs.

        --
        mvh Björn

        Comment

        • Sandra-24

          #5
          Re: testing for valid reference: obj vs. None!=obs vs. obj is not None


          alf wrote:
          Hi,
          >
          I have a reference to certain objects. What is the most pythonic way to
          test for valid reference:
          >
          if obj:
          >
          if None!=obs:
          >
          if obj is not None:
          I like this way the most. I used timeit to benchmark this against the
          first one, expecting it to be faster (the first is a general false
          test, the last should just be comparing pointers) but it's slower.
          Still I don't expect that to ever matter, so I use it wherever I wish
          to test for None, it reads the best of all of them.

          -Sandra

          Comment

          • Carl Banks

            #6
            Re: testing for valid reference: obj vs. None!=obs vs. obj is not None

            Bruno Desthuilliers wrote:
            In python, assignement is a statement, not an expression, so there's no
            way you could write 'if obj = None' by mistake (-syntax error). So
            this style is unpythonic. Also, None is a singleton, and identity test
            is way faster than equality test.
            Playing Devil's advocate here: if you were to write "x!=None", then x's
            __eq__ method is invoked, which might not account for the possibility
            that the other operand is None.

            However, if you write "None!=x", then None's __eq__ method is invoked,
            which accounts for any given type.


            Carl Banks

            Comment

            • Paul Rubin

              #7
              Re: testing for valid reference: obj vs. None!=obs vs. obj is not None

              alf <ask@mewrites :
              I have a reference to certain objects. What is the most pythonic way
              to test for valid reference:
              If you're intending to use None as a sentinel for an invalid reference,
              then use
              if obj is not None:
              You could also make a unique sentinel:

              Sentinel = object()
              ...
              if obj is not Sentinel: ...

              "if obj" isn't necessarily what you want; obj might be a valid but
              empty container.

              "if obj != None" is also wrong, for reasons someone else explained.

              Comment

              • Bruno Desthuilliers

                #8
                Re: testing for valid reference: obj vs. None!=obs vs. obj is notNone

                Carl Banks wrote:
                Bruno Desthuilliers wrote:
                >In python, assignement is a statement, not an expression, so there's no
                >way you could write 'if obj = None' by mistake (-syntax error). So
                >this style is unpythonic. Also, None is a singleton, and identity test
                >is way faster than equality test.
                >
                Playing Devil's advocate here: if you were to write "x!=None", then x's
                __eq__ method is invoked, which might not account for the possibility
                that the other operand is None.
                >
                However, if you write "None!=x", then None's __eq__ method is invoked,
                which accounts for any given type.
                >
                Well... Since we all know it should be an identity test anyway... <g>



                --
                bruno desthuilliers
                python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
                p in 'onurb@xiludom. gro'.split('@')])"

                Comment

                • Gabriel Genellina

                  #9
                  Re: testing for valid reference: obj vs. None!=obs vs. obj is not None

                  At Monday 4/9/2006 17:02, alf wrote:
                  >I have a reference to certain objects. What is the most pythonic way to
                  >test for valid reference:
                  By "valid reference" you mean, you have initially:
                  obj = None
                  and you want to detect whether obj is bound to another, different,
                  object, right?
                  if obj:
                  This checks whether obj is considered True, not whether it is None.
                  e.g. obj=[] would not pass.
                  if None!=obs:
                  Would be OK, but the next one is better:
                  if obj is not None:
                  This is what you are looking for! :)



                  Gabriel Genellina
                  Softlab SRL





                  _______________ _______________ _______________ _____
                  Preguntá. Respondé. Descubrí.
                  Todo lo que querías saber, y lo que ni imaginabas,
                  está en Yahoo! Respuestas (Beta).
                  ¡Probalo ya!


                  Comment

                  • alf

                    #10
                    Re: testing for valid reference: obj vs. None!=obs vs. obj is notNone

                    alf wrote:
                    Hi,
                    >
                    I have a reference to certain objects. What is the most pythonic way to
                    test for valid reference:
                    >
                    if obj:
                    >
                    if None!=obs:
                    >
                    if obj is not None:
                    >
                    thx for all answers - now "if obj is not None:" in an obvious choice ...

                    Comment

                    Working...