Checking for an "undefined" variable - newbie question

Discussion in 'Python' started by Dan Rawson, Aug 6, 2003.

  1. Dan Rawson

    Dan Rawson Guest

    How do I check if a variable has been defined??

    The following don't appear to work:

    if variable:

    if variable is None:


    I have only one (ugly) solution:

    try:
    variable
    except NameError:
    ...

    which works, but is a bit clumsy if I just want to know if the thing already exists.

    If there's a more elegant way to check this, that would be great!

    Thanks . . . .

    Dan
     
    Dan Rawson, Aug 6, 2003
    #1
    1. Advertising

  2. Dan Rawson

    Duncan Booth Guest

    Dan Rawson <daniel.rawson.take!this!out!@asml.nl> wrote in
    news:bgqmce$qk3d1$-berlin.de:

    > I have only one (ugly) solution:
    >
    > try:
    > variable
    > except NameError:
    > ...
    >
    > which works, but is a bit clumsy if I just want to know if the thing
    > already exists.


    You could check whether the name of the variable is present in 'locals',
    'globals', or 'vars' as appropriate:

    >>> 'variable' in vars()

    0

    --
    Duncan Booth
    int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
    "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
     
    Duncan Booth, Aug 6, 2003
    #2
    1. Advertising

  3. Dan Rawson wrote:

    > How do I check if a variable has been defined??
    >
    > The following don't appear to work:
    >
    > if variable:
    >
    > if variable is None:
    >
    >
    > I have only one (ugly) solution:
    >
    > try:
    > variable
    > except NameError:
    > ...


    This is the canonical solution. Personally, I find it quite nice
    that an ugly architecture (such as one based on whether a variable
    is already defined/initialized rather than initializing it at the
    start with a unique value and testing for that!) requires an ugly
    way of expressing it. Unfortunately there are nicer ones such as
    "if 'variable' not in locals() and 'variable' not in globals():" but
    at least they're verbose and slow:).


    If you can't rule out (e.g.) None as a valid value for your
    variable, just make a unique placeholder value such as [be
    sure to use a MUTABLE value, else uniqueness is not guaranteed]:

    class _uninitialized: pass

    initialize your variable at the start of your scope with

    variable = _uninitialized

    and test at any point within that scope whether the variable
    is still uninitialized or has been assigned an actual value by

    if variable is _uninitialized:

    It seems to me that this is far preferable to any approach
    based on _not_ binding the name 'variable' at all and later
    needing to test whether the name is bound or not.


    Alex
     
    Alex Martelli, Aug 6, 2003
    #3
  4. Dan Rawson

    Dan Rawson Guest

    Duncan Booth wrote:
    > Dan Rawson <daniel.rawson.take!this!out!@asml.nl> wrote in
    > news:bgqmce$qk3d1$-berlin.de:
    >
    >
    >>I have only one (ugly) solution:
    >>
    >>try:
    >> variable
    >>except NameError:
    >> ...
    >>
    >>which works, but is a bit clumsy if I just want to know if the thing
    >>already exists.

    >
    >
    > You could check whether the name of the variable is present in 'locals',
    > 'globals', or 'vars' as appropriate:
    >
    >
    >>>>'variable' in vars()

    >
    > 0
    >

    Ahhhh . . . . thanks! 'locals' and 'globals' I think I understand, but what's the scope for 'vars' ??

    In the specific case in question, these are global variables, so it's relatively easy . . . .

    TIA . . .

    Dan
     
    Dan Rawson, Aug 6, 2003
    #4
  5. Dan Rawson

    Damien Wyart Guest

    * Alex Martelli <> in comp.lang.python:
    > If you can't rule out (e.g.) None as a valid value for your variable,
    > just make a unique placeholder value such as [be sure to use a MUTABLE
    > value, else uniqueness is not guaranteed]:


    Could you expand on this "uniqueness" point ? I don't see very well what
    you mean.


    Thanks in advance,
    --
    Damien Wyart
     
    Damien Wyart, Aug 6, 2003
    #5
  6. Damien Wyart <> writes:

    > * Alex Martelli <> in comp.lang.python:
    > > If you can't rule out (e.g.) None as a valid value for your variable,
    > > just make a unique placeholder value such as [be sure to use a MUTABLE
    > > value, else uniqueness is not guaranteed]:

    >
    > Could you expand on this "uniqueness" point ? I don't see very well what
    > you mean.


    I think Alex is talking about things like this:

    >>> 2 is (1 + 1)

    True
    >>> 200 is (199 + 1)

    False

    Two references to equal immutable objects might as well reference the
    same object, and sometimes this happens (e.g. there is only *one* int
    object for each integer in some range -- I think it's -10..100 in
    today's Python) and sometimes it doesn't.

    TBH, I'm not sure Alex is doing the OP a favour in bringing this
    aspect of the implementation to his attention...

    Cheers,
    mwh

    --
    To summarise the summary of the summary:- people are a problem.
    -- The Hitch-Hikers Guide to the Galaxy, Episode 12
     
    Michael Hudson, Aug 6, 2003
    #6
  7. Quoth Dan Rawson:
    > How do I check if a variable has been defined??

    [...]
    > try:
    > variable
    > except NameError:
    > ...


    This is the answer to your question.

    > If there's a more elegant way to check this, that would be great!


    Why do you want to check it in the first place?

    In particular, why not initialize your variable to some
    out-of-band value (such as None) and test that? E.g.,

    myvar = None
    # ... code which might set myvar to something else ...
    if myvar is None:
    # ...

    --
    Steven Taschuk
    Every public frenzy produces legislation purporting to address it.
    (Kinsley's Law)
     
    Steven Taschuk, Aug 6, 2003
    #7
  8. Dan Rawson <daniel.rawson.take!this!out!@asml.nl> wrote in message news:<bgqmce$qk3d1$-berlin.de>...
    > How do I check if a variable has been defined??
    >
    > The following don't appear to work:
    >
    > if variable:
    >
    > if variable is None:
    >
    >
    > I have only one (ugly) solution:
    >
    > try:
    > variable
    > except NameError:
    > ...
    >
    > which works, but is a bit clumsy if I just want to know if the thing already exists.
    >
    > If there's a more elegant way to check this, that would be great!
    >
    > Thanks . . . .
    >
    > Dan


    IMHO, the try .. except trick is the easiest, efficient and Pythonic
    solution. I would recommend it. If you don't like it, you may try

    if variable in dict

    where dict can be globals(), locals() or vars().

    But still I would prefer the explicit try ... except.


    Michele
     
    Michele Simionato, Aug 6, 2003
    #8
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mantorok Redgormor
    Replies:
    70
    Views:
    1,795
    Dan Pop
    Feb 17, 2004
  2. Shao Miller

    Bounds Checking as Undefined Behaviour?

    Shao Miller, Jul 29, 2010, in forum: C Programming
    Replies:
    29
    Views:
    821
    Shao Miller
    Aug 16, 2010
  3. Grehom
    Replies:
    10
    Views:
    395
    Grehom
    Dec 19, 2005
  4. VK
    Replies:
    45
    Views:
    624
    Dr John Stockton
    Sep 12, 2006
  5. -Lost
    Replies:
    13
    Views:
    378
    Richard Cornford
    Jan 31, 2007
Loading...

Share This Page