In Python, don’t initialize local variables unnecessarily

A common pattern:

def foo():
    x = some value # but do we need this? (short answer: no)
    if something:
        # ... do stuff ...
        x = 'bla'
    else:
        x = 'blo'

The variable x is being initialized before the if/else, but the intention of the programmer is that its value will actually be determined by the if/else itself. If somebody later comes around and mistakenly removes one of the assignments (inside ‘if’ or ‘else’), no runtime error will occur and x will remain initialized to a probably wrong value.

Leaving out the initialization is better – in that case, forgetting to set x in one of the branches will cause an UnboundLocalError:

>>> def foo():
...     if False:
...         x = 0
...     return x
... 
>>> foo()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 4, in foo
UnboundLocalError: local variable 'x' referenced before assignment

Errors are good! (when they flag buggy code)

Now, what if we also have an x declared in the global scope? Because of how Python handles variable scope, the error will still happen (which is good).

>>> x = 1
>>> def foo():
...     if False:
...         x = 0
...     return x
... 
>>> foo()
Traceback (most recent call last):
..
UnboundLocalError: local variable 'x' referenced before assignment

Summary: In Python, don’t initialize variables until you know what value to assign to them.

Advertisements
In Python, don’t initialize local variables unnecessarily

4 thoughts on “In Python, don’t initialize local variables unnecessarily

    1. If your intention is to leave out the else branch, that’s fine. But when you have an else branch anyway that also assigns to the variable, there’s no reason to also initialize it before the if/else.

  1. My intention is not to leave out the else branch. Probably this is my C/Java/whatever statically typed language background: 1) you need to declare a variable; 2) variable scope is limited to it’s declaration scope (with C this means that your variable scope will be the particular IF branch only).
    Although I’m surprised that you start your post with rather weird example and call it “common”. I haven’t seen such uses in the wild. Also there are I would say “common” guidelines on structuring your code (in almost any language) which suggest you putting your “happy path” on the first nesting level (which means if you remove all IFs you will get the happy path). So, initialization of variable in both branches of IF violate that and personally I don’t see any profit in having both branches in general case.

    1. The issue under consideration comes up when you *do* have an else branch (e.g. because it is doing something different than the if branch) and omitting it is not an option. In that case you shouldn’t initialize the variable before the if/else.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s