Python: list comprehensions

# Python's list comprehensions are awesome.

vals = [expression 
        for value in collection 
        if condition]

# This is equivalent to:

vals = []
for value in collection:
    if condition:
        vals.append(expression)

# Example:

>>> even_squares = [x * x for x in range(10) if not x % 2]
>>> even_squares
[0, 4, 16, 36, 64]
Advertisements

Python: Dict get with default value to void key not found error

# The get() method on dicts
# and its "default" argument

name_for_userid = {
    382: "Aseem",
    590: "Bob",
    951: "Dilbert",
}

def greeting(userid):
    return "Hi %s!" % name_for_userid.get(userid, "there")

>>> greeting(382)
"Hi Aseem!"

>>> greeting(333333)
"Hi there!"

Python: emulate switch/case statements by using dict with lambda functions

# Because Python has first-class functions they can
# be used to emulate switch/case statements

def dispatch_if(operator, x, y):
    if operator == 'add':
        return x + y
    elif operator == 'sub':
        return x - y
    elif operator == 'mul':
        return x * y
    elif operator == 'div':
        return x / y
    else:
        return None


def dispatch_dict(operator, x, y):
    return {
        'add': lambda: x + y,
        'sub': lambda: x - y,
        'mul': lambda: x * y,
        'div': lambda: x / y,
    }.get(operator, lambda: None)()


>>> dispatch_if('mul', 2, 8)
16

>>> dispatch_dict('mul', 2, 8)
16

>>> dispatch_if('unknown', 2, 8)
None

>>> dispatch_dict('unknown', 2, 8)
None

Python: Functions are first-class citizens

# Functions are first-class citizens in Python.

# They can be passed as arguments to other functions,
# returned as values from other functions, and
# assigned to variables and stored in data structures.

>>> def myfunc(a, b):
...     return a + b
...
>>> funcs = [myfunc]
>>> funcs[0]
<function myfunc at 0x107012230>
>>> funcs[0](2, 3)
5

Python: __dict__ class instance members are really dictionaries

Python class instance members are really dictionaries/mappings. For example,

    class Foo:
        def __init__(self, name=''):
            self.name = name

You can access the name member:

    In [2]: f = Foo('vito')

    In [3]: f.name
    Out[3]: 'vito'

You can also do:

    In [4]: f.__dict__['name']
    Out[4]: 'vito'

In fact, you can see all the data members:

    In [5]: f.__dict__
    Out[5]: {'name': 'vito'}

This gives us a quick way of creating an object at run time, say when parsing a text file. For a very contrived example, we have a text file that looks like this:

    name=John,age=35,hobby=philately
    name=Sally,age=28
    name=Vito,age=18,sex=male
    name=Maria,age=58

We can grab all the data into a bunch of objects like this:

    class Person:
        def __init__(self, name=''):
            self.name = name

    if __name__ == '__main__':
        f = open('people.dat', 'ro')
        people = []
        for l in f.readlines():
            people.append(Person())
            lsp = l.strip().split(',')
            p = []
            for i in lsp:
                p.append(i.split('='))
            people[-1].__dict__ = dict(p)

        for p in people:
            print p.__dict__

And the output is:

    {'hobby': 'philately', 'age': '35', 'name': 'John'}
    {'age': '28', 'name': 'Sally'}
    {'age': '18', 'name': 'Vito', 'sex': 'male'}
    {'age': '58', 'name': 'Maria'}

Python: What Are Namespaces?

A namespace is basically a system to make sure that all the names in a program are unique and can be used without any conflict. You might already know that everything in Python—like strings, lists, functions, etc.—is an object. Another interesting fact is that Python implements namespaces as dictionaries. There is a name-to-object mapping, with the names as keys and the objects as values. Multiple namespaces can use the same name and map it to a different object. Here are a few examples of namespaces:

  • Local Namespace: This namespace includes local names inside a function. This namespace is created when a function is called, and it only lasts until the function returns.
  • Global Namespace: This namespace includes names from various imported modules that you are using in a project. It is created when the module is included in the project, and it lasts until the script ends.
  • Built-in Namespace: This namespace includes built-in functions and built-in exception names.

For example, the math and cmath modules have a lot of functions that are common to both of them, like log10()acos()cos()exp(), etc. If you are using both of these modules in the same program, the only way to use these functions unambiguously is to prefix them with the name of the module, like math.log10() and cmath.log10().