2

This will work fine:

a = 1
if a:
  b = a

but this will not work:

if a:
  b = a

it is not like this "if" statement will be executed given that we are explicitly saying..

 "if a exists" 

so why does it error ? if it does not exist then simply do not do anything within the parameters of that if statement.

UPDATE

it turns out "if a" means.. "if a value for a" means in python.

i am looking for the equivalency for "if a exists at all then move forward"

Anto
  • 6,806
  • 8
  • 43
  • 65
  • 3
    You are **not** saying 'if `a` exists'. You are asking if the *value `a` references is true or false*. Names reference objects, objects have a boolean value. – Martijn Pieters Sep 03 '14 at 11:23
  • 1
    Why do you need to know if a name is defined? It sounds as if you want to do `a = None` first instead. – Martijn Pieters Sep 03 '14 at 11:24
  • Use None or some other value as your "not set yet" value. – djhoese Sep 03 '14 at 11:25
  • 1
    Good primer on Python names: http://nedbatchelder.com/text/names.html – jonrsharpe Sep 03 '14 at 11:25
  • @user4003832 no, you're saying *"does the object referenced by the name `a` evaluate True-y or False-y?"* If the name `a` isn't assigned, you get a `NameError`. – jonrsharpe Sep 03 '14 at 11:26
  • @user4003832: no, you are [testing for boolean truth](https://docs.python.org/2/library/stdtypes.html#truth-value-testing). The value exists, but it may be a value that is considered false (empty, numeric 0, `False` or `None`). – Martijn Pieters Sep 03 '14 at 11:26
  • when at school someones name is called.. if no answer is given.. they are not present at all. what is the equivalency of that ? –  Sep 03 '14 at 11:30
  • 1
    You could catch `NameError`. But the point is that this simply isn't how you usually code in Python. You should *know" whether `a` is defined at that point or not, and if that means assigning `None` to it earlier on, so be it. – Lukas Graf Sep 03 '14 at 11:32
  • 2
    Variables are not school students, and attempting to code by an analogy between them is not helpful. – interjay Sep 03 '14 at 11:38
  • 1
    @user4003832: A teacher trying to resolve a bunch of names into actual pupils is very far removed from a program using names. Sounds like you want to store stuff in a dictionary instead and test for keys being present. `if keyname in dictionary:` is far closer to `if pupil present in class`. – Martijn Pieters Sep 03 '14 at 11:40
  • You're trying to impose *your* ideas of how things are supposed to work on Python here. You won't have any success with that (in any language for that matter). – Lukas Graf Sep 03 '14 at 11:41
  • can i at least set the "a" to "0" or something and "if a:" will not execute as a result ? –  Sep 03 '14 at 11:53
  • found something with lots of votes: http://stackoverflow.com/questions/843277/how-do-i-check-if-a-variable-exists-in-python –  Sep 03 '14 at 11:55

2 Answers2

7

You can use locals():

if 'a' in locals():
    # variable 'a' is defined

You can also use Python's principle that it's easier to ask for forgiveness than permission:

try:
    b
    # if we get here, variable 'b' is defined
except NameError:
    # variable 'b' is not defined

As mentioned in the documentation:

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
3

When a name doesn't exist (hasn't been bound to, so there are no assignments binding a value to it, no import statements exist that assign an imported object to the name and no function arguments exist), then Python throws an exception.

You can handle that exception; a global name throws NameError, a local name throws an UnboundLocalError. Catching the exception with a try...except statement also can tell you if the exception wasn't thrown:

try:
    somename
except NameError:
    # name does not exist
else:
    # name exists

See the Execution model documentation on what makes a name exist or not.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343