Search code examples
pythonvariablesif-statementsemantics

What does "if var" mean in python?


This is a function in python to validate a day entry.

def valid_day(day):
    if day and day.isdigit():#if day
        day = int(day)
        if day > 0 and day <= 31:
            return day

I want to know what the expression if day means (in terms of semantics).

I only know the effect of if on boolean expressions not on variables like integers or arrays.


Solution

  • In Python, writing

    if var:

    has the same effect as writing

    if bool(var):

    (where bool is the built-in bool type which also acts as a constructor function for bool objects).

    If the value is already a bool (valued True or False) the meaning is clear -- bool(var) returns the same value. For other types, there's almost always a conversion to bool available which depends on the type. For integers (as in C) it's the same as var!=0; for lists or dicts or strings, it's the same as len(var)!=0, and so forth. You can find this in the Python docs.

    When you define your own class you can define a method via def __nonzero__(self): , which will be called in this context (when your object is passed to bool explicitly, or implicitly in an if -- or while for that matter).

    A notable exception: numpy array objects do not convert to bool (they raise an exception). They need to be explicitly converted using constructs like (arr!=0).any() or (arr>0).all()

    On similar lines: Don't get into the habit of writing any of

    if x == True:     # This only works as expected when x is a bool, or 0, or 1
    if x is True:     # Can be useful but you need to understand what it really means.
    if x == None:     # Often works as expected, except when it doesn't
    

    Comparison to None should always be done with

    if x is None: (or) if x is not None:

    There is only one None object, and x is None will tell you if x refers to that object, and will always give you a bool (True if so, False for any other object). Comparing x==None (a mistake I frequently made when starting to use Python) will usually work, but it activates the generic comparison machinery of Python, which is not what you probably want; if x is an instance of a class, the comparison could raise an exception. is is simple and quick and just does that identity test - it can't be overloaded.

    Likewise, if x is True means "if x is the boolean object meaning true, and no other object at all" -- which can be useful, but is too narrow for the case when you are just testing truth value. Somebody might end up passing 1, which will fail an 'is True' test, but otherwise acts very much like True.