In fact, if you are trying to determine if the var parameter was previously set using the get_var call, I would argue that both forms are wrong . Python treats a number of completely ordinary values โโas an estimate of the logical "false": 0, None, [], (,), set (), and {}. So, let var be an integer, and get_var () will return 0. Now, no matter what form you use, get_var () will be called again and again, although we already know that var is 0!
There are several ways to determine if a variable has been defined:
look at the dict returned by globals () or locals ()
wrap the var = var statement in a try / except block, capture on NameError
use a sentinel value, such as None, and initialize var for that value; then you can check if var is None: var = get_var() (using 'is', not '=='). If you're out of luck, and None is the potential value that should be returned from get_var (), then you will need to define your own special, not yet defined value, using something like NOT_DEFINED = object() , initialize var with it, and then you can check if var is NOT_DEFINED .
source share