Printing locals()

Here is a trick how one can print out variables more easily in Python.

Python has a locals() function which gives you back a dictionary of local variables within the function. Python string formatting, also called string interpolation, accepts dictionary like fillers.  You can combine these two so that you do not need to explicitly pass input variables for the string formatting making your code more readable. This is very useful e.g. in the logging situations.

# -*- coding: utf-8 -*-

# Python 2.6+ future compatibility declarations
from __future__ import absolute_import, division, print_function, unicode_literals

def my_function():

    foo = 12  # NOQA
    bar = "Toholampi city coders - http://www.toholampi.fi"  # NOQA
    baz = 3.0  # NOQA

    print("Foo %(foo)s, bar %(bar)s and baz %(baz)s went to a bar..." \
        % locals())
    # versus
    # print("Foo %s, bar %s and baz %s went to a bar..." % \
    #    (foo, bar, baz))

my_function()

Convenient, isn’t it?

Note about linting this kind of functions: pyflakes linter will complain about unused variables as it does not have function or module scope warning disable. # NOQA hints flake8 to ignore unused variable warning.

 

\"\" Subscribe to RSS feed Follow me on Twitter Follow me on Facebook Follow me Google+

Leave a Reply

Your email address will not be published. Required fields are marked *