checking whether a var is empty or not

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

    checking whether a var is empty or not

    Are these equivelent? Is one approach prefered
    over the other

    #check to see if var contains something... if so
    proceed.
    if var is not None:
    continue

    #check to see if var is empty... if so prompt user
    again.
    if not var:
    print "Please specify the amount."
    ...
  • David M. Cooke

    #2
    Re: checking whether a var is empty or not

    At some point, Bart Nessux <bart_nessux@ho tmail.com> wrote:
    [color=blue]
    > Are these equivelent? Is one approach prefered over the other
    >
    > #check to see if var contains something... if so proceed.
    > if var is not None:
    > continue
    >
    > #check to see if var is empty... if so prompt user again.
    > if not var:
    > print "Please specify the amount."
    > ...[/color]

    They're not equivalent: if var is None, the first doesn't trigger, but
    the second does.

    Do you mean:

    if var is None:
    # do something
    if not var:
    # do something

    The first if only triggers if var is the singleton None.
    The second if will trigger if var is False, 0, 0.0, 0j, '', [], (), None,
    or anything else that has a length of 0 or var.__nonzero__ () returns
    False. In this case, you're checking if var is false in a boolean
    logic context.

    If you're checking arguments to a function to see if a non-default
    argument has been passed, you probably want the first, like this:

    def function(var=No ne):
    if var is None:
    # do something to get a default argument

    But if you want a flag that's true or false, you want the second:
    def function(var):
    if var:
    # yes, do something
    else:
    # no, do something else

    --
    |>|\/|<
    /--------------------------------------------------------------------------\
    |David M. Cooke
    |cookedm(at)phy sics(dot)mcmast er(dot)ca

    Comment

    • Jeff Shannon

      #3
      Re: checking whether a var is empty or not

      Bart Nessux wrote:
      [color=blue]
      > Are these equivelent? Is one approach prefered over the other
      >
      > #check to see if var contains something... if so proceed.
      > if var is not None:
      > continue
      >
      > #check to see if var is empty... if so prompt user again.
      > if not var:
      > print "Please specify the amount."
      > ...[/color]


      They're not quite equivalent. The second form ('if not var') will
      resolve to be true if var is any value that resolves to false -- this
      could be None, 0, [], {}, '', or some user-defined objects. The first
      form will only be true if var is None.

      This could be significant if, for instance, 0 is a valid value. You
      might want to initialize var to None, conditionally assign an integer to
      it, and then later see if an integer (including 0) was actually
      assigned. In that case, you'd need to use the first form.

      Jeff Shannon
      Technician/Programmer
      Credit International

      Comment

      • Pierre-Frédéric Caillaud

        #4
        Re: checking whether a var is empty or not



        This smells like PHP to me...

        if var is not None:
        if var has not been assigned, it raises an exception.
        if var has been assigned, it contains a value which can be None or
        someting else.

        This is different from PHP where you can't know if a variable exists or
        not, because a non-existent variable will contain null if you check it,
        and putting null in a variable is like deleting it, but noone knows
        because there's no way of checking if a variable really exists, etc.

        [color=blue]
        > Are these equivelent? Is one approach prefered over the other
        >
        > #check to see if var contains something... if so proceed.
        > if var is not None:
        > continue
        >
        > #check to see if var is empty... if so prompt user again.
        > if not var:
        > print "Please specify the amount."
        > ...[/color]

        Comment

        • Dave Benjamin

          #5
          Re: checking whether a var is empty or not

          In article <opsbxubr1g1v4i jd@musicbox>, Pierre-Frédéric Caillaud wrote:[color=blue]
          >
          > This smells like PHP to me...
          >
          > if var is not None:
          > if var has not been assigned, it raises an exception.
          > if var has been assigned, it contains a value which can be None or
          > someting else.
          >
          > This is different from PHP where you can't know if a variable exists or
          > not, because a non-existent variable will contain null if you check it,
          > and putting null in a variable is like deleting it, but noone knows
          > because there's no way of checking if a variable really exists, etc.[/color]

          No, in PHP, you can find out if a variable exists using isset(). And trying
          to dereference an uninitialized variable will generate a warning if you have
          error reporting turned up all the way (error_reportin g(E_ALL)).

          --
          .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.

          "When the country is confused and in chaos, information scientists appear."
          Librarian's Lao Tzu: http://www.geocities.com/onelibrarian.geo/lao_tzu.html

          Comment

          • Dave Cole

            #6
            Re: checking whether a var is empty or not

            Dave Benjamin wrote:[color=blue]
            > In article <opsbxubr1g1v4i jd@musicbox>, Pierre-Frédéric Caillaud wrote:
            >[color=green]
            >> This smells like PHP to me...
            >>
            >>if var is not None:
            >> if var has not been assigned, it raises an exception.
            >> if var has been assigned, it contains a value which can be None or
            >>someting else.
            >>
            >> This is different from PHP where you can't know if a variable exists or
            >>not, because a non-existent variable will contain null if you check it,
            >>and putting null in a variable is like deleting it, but noone knows
            >>because there's no way of checking if a variable really exists, etc.[/color]
            >
            >
            > No, in PHP, you can find out if a variable exists using isset(). And trying
            > to dereference an uninitialized variable will generate a warning if you have
            > error reporting turned up all the way (error_reportin g(E_ALL)).[/color]
            [color=blue][color=green][color=darkred]
            >>> def isset(var):[/color][/color][/color]
            .... return var in globals()
            ....[color=blue][color=green][color=darkred]
            >>> print isset('var')[/color][/color][/color]
            0[color=blue][color=green][color=darkred]
            >>> var = 43
            >>> print isset('var')[/color][/color][/color]
            1

            Not that I can see any good use for this :-).

            - Dave

            --

            Comment

            • Dave Benjamin

              #7
              Re: checking whether a var is empty or not

              In article <ap%Pc.22247$%r .245331@nasal.p acific.net.au>, Dave Cole wrote:[color=blue]
              > Dave Benjamin wrote:[color=green]
              >>
              >> No, in PHP, you can find out if a variable exists using isset(). And trying
              >> to dereference an uninitialized variable will generate a warning if you have
              >> error reporting turned up all the way (error_reportin g(E_ALL)).[/color]
              >[color=green][color=darkred]
              > >>> def isset(var):[/color][/color]
              > ... return var in globals()
              > ...[color=green][color=darkred]
              > >>> print isset('var')[/color][/color]
              > 0[color=green][color=darkred]
              > >>> var = 43
              > >>> print isset('var')[/color][/color]
              > 1
              >
              > Not that I can see any good use for this :-).[/color]

              Not that there's *any* reason to do anything like this, *ever* ;) but...
              [color=blue][color=green][color=darkred]
              >>> import inspect
              >>> def isset(v):[/color][/color][/color]
              .... return v in globals() or v in inspect.current frame().f_back. f_locals
              ....[color=blue][color=green][color=darkred]
              >>> isset('a')[/color][/color][/color]
              False[color=blue][color=green][color=darkred]
              >>> a = 5
              >>> isset('a')[/color][/color][/color]
              True[color=blue][color=green][color=darkred]
              >>> def f():[/color][/color][/color]
              .... b = 6
              .... print isset('b')
              .... print isset('c')
              ....[color=blue][color=green][color=darkred]
              >>> f()[/color][/color][/color]
              True
              False[color=blue][color=green][color=darkred]
              >>> c = 42
              >>> f()[/color][/color][/color]
              True
              True

              Verdict: Just catch the NameError, already! =)

              --
              .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.

              "When the country is confused and in chaos, information scientists appear."
              Librarian's Lao Tzu: http://www.geocities.com/onelibrarian.geo/lao_tzu.html

              Comment

              • Pierre-Frédéric Caillaud

                #8
                Re: checking whether a var is empty or not

                [color=blue]
                > No, in PHP, you can find out if a variable exists using isset(). And
                > trying
                > to dereference an uninitialized variable will generate a warning if you
                > have
                > error reporting turned up all the way (error_reportin g(E_ALL)).
                >[/color]

                WRONG !!!!!

                Example in this stupid language :

                <?php

                echo "<p>one : ";
                var_dump(isset( $a ));

                $a = 1;
                echo "<p>two : ";
                var_dump(isset( $a ));

                $a = null;
                echo "<p>three : ";
                var_dump(isset( $a ));

                ?>

                Output :


                one : bool(false)

                two : bool(true)

                three : bool(false)


                Get it ?



                Comment

                • Pierre-Frédéric Caillaud

                  #9
                  Re: checking whether a var is empty or not


                  import inspect
                  def isset(v):
                  return v in globals() or v in inspect.current frame().f_back. f_locals

                  Why would you want that ?

                  Use this PHP emulator :

                  from (all installed modules...) import *

                  If you want to emulate PHP, you should only use global variables, and
                  don't forget to copy those into all the modules you import (and of course,
                  update globals with all variables coming from all modules).

                  Comment

                  • Dave Benjamin

                    #10
                    Re: checking whether a var is empty or not

                    In article <opsb9nh9xd1v4i jd@musicbox>, Pierre-Frédéric Caillaud wrote:[color=blue]
                    >[color=green]
                    >> No, in PHP, you can find out if a variable exists using isset(). And
                    >> trying
                    >> to dereference an uninitialized variable will generate a warning if you
                    >> have
                    >> error reporting turned up all the way (error_reportin g(E_ALL)).[/color]
                    >
                    > WRONG !!!!!
                    > Example in this stupid language :
                    >
                    ><?php
                    >
                    > echo "<p>one : ";
                    > var_dump(isset( $a ));
                    >
                    > $a = 1;
                    > echo "<p>two : ";
                    > var_dump(isset( $a ));
                    >
                    > $a = null;
                    > echo "<p>three : ";
                    > var_dump(isset( $a ));
                    >
                    > ?>
                    >
                    > Output :
                    >
                    > one : bool(false)
                    > two : bool(true)
                    > three : bool(false)
                    >
                    > Get it ?[/color]

                    I stand corrected. That is rather stupid.

                    Well, I try to use nulls sparingly and always initialize my variables, which
                    may explain why in the five or so years I've been using PHP, I've never run
                    into this problem. Likewise, I don't think I've ever had to use the
                    corresponding idiom in Python:

                    try:
                    a
                    except NameError:
                    # ...

                    At the very least, I'll be testing for a's existence in some namespace, so
                    I'll be looking for an AttributeError.

                    --
                    .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.

                    "When the country is confused and in chaos, information scientists appear."
                    Librarian's Lao Tzu: http://www.geocities.com/onelibrarian.geo/lao_tzu.html

                    Comment

                    Working...