How to create a date in Python?

Date objects can be created using the method. This method takes year, month and day parameters.

import datetime
# Create 7th Feb 2011
d =,2,7)
assert str(d) == '2011-02-07'

How to create an enum in Python?

Python does not have any syntax for creating enums (it’s proposal was rejected), but there are some alternatives.

1. Using a class

class Numbers(object):
    ONE = 1
    TWO = 2
    THREE = 3
assert Numbers.ONE == 1
assert Numbers.TWO == 2
assert Numbers.THREE == 3

2. Use a function that dynamically creates a new class

def enum(**enums):
    return type('Enum', (object,), enums)
Numbers = enum(ONE=1, TWO=2, THREE=3)
assert Numbers.ONE == 1
assert Numbers.TWO == 2
assert Numbers.THREE == 3

3. Create a new object that extends Python’s set

class Enum(set):
    def __getattr__(self, name):
        if name in self:
            return name
        raise AttributeError
Numbers = Enum( "ONE TWO THREE".split() )
error = False
    print Numbers.ONE
    print Numbers.TWO
    print Numbers.THREE
    error = True
assert error == False
    print Numbers.FOUR
    error = True
assert error == True

How to test if a variable exists in Python?

We can check if a variable is defined in Python using a try/except.

    print x
except NameError:
    x = 0
assert x == 0

How to create a lambda function in Python?

A lambda function is essentially a function that has no name. They are often used as parameters to other functions.

A simple lambda function to square numbers may be created as follows:

# Create a lambda function that takes one parameter and returns it's square
# and assign to the variable f
f = lambda x: x*x
assert f(2) == 4
assert f(3) == 9

We can also pass lambda functions as function parameters without assigning to to intermediate variables.

# Create a function that takes a function and a list, then applies the function to each element of the list
def map(f, list):
    for i in range(0,len(list)):
        list[i] = f(list[i])
# Create a simple test list
list = [1,2,3]
# Call our map function passing in a lambda square function and the test list
map( lambda x: x*x, list )
assert list[0] == 1
assert list[1] == 4
assert list[2] == 9

Note that lambda functions do not include a return statement.

How to loop over an array in Python?

You can use a for in loop to get the elements of the array.

colours = ["red","green","blue"]
for colour in colours:
    print colour
# red
# green
# blue

However if you also need access to the position of the element in the array we can use a for in loop over a range

colours = ["red","green","blue"]
for i in range(0, len(colours)):
    print i, colour[i]
# 0 red
# 1 green
# 2 blue

How to dynamically create a class at runtime in Python?

Python has a type() function that is used to provide the type of an object, but this same function can be used to dynamically create classes at runtime.

For example, suppose we have the following class:

class Foo(object):
    x = 10
    y = 20
    def get_x(self):
        return self.x
    def get_y(self):
        return self.y

We can create an identical class using the type() function.

Bar = type(
                x = 10,
                y = 20,
                get_x=lambda self:self.x,
                get_y=lambda self:self.y

And testing these are the equivalent.

f = Foo()
b = Bar()
assert f.x == b.x == 10
assert f.y == b.y == 20
assert f.get_x() == b.get_x() == 10
assert f.get_y() == b.get_y() == 20

For more information see:

How to define constants in Python?

Python does not have any particular language construct for declaring constants, so they are typically declared as just variables names with all capital letters.


Alternatively they may be declared as class variables.

class Post(object):
    NEW = 1
    ARCHIVED = 2
    DELETED = 3
assert Post.NEW == 1
assert Post.ARCHIVED == 2
assert Post.DELETED == 3

How to create a class in Python?

The simplest class is something like:

class Foo(object):

This can be initialised with an __init__() method

class Foo(object):
    def __init__(self): = None

We can then add additional methods

class Foo(object):
    def __init__(self): = None
    def set_name(self, name): = name
    def get_name(self):

This class is then used as follows

o = Foo()
assert o.get_name() == "Hello"

We can then implement simple inheritance

class Bar(Foo):

Add a constructor

class Bar(Foo):
    def __init__(self):

This object is then used as follows

o = Bar()
assert o.get_name() == "World"

How to create a switch statement in Python?

Python does not support a switch statement, but instead prefers an if/elif/else statement.

x = 5
value = 0
if x < 5:
    value = -1
elif x > 5:
    value = 1
    value = 0
assert value == 0

A proposal to include a switch statement in the language has been rejected.

How to JSON encode data in Python?

Python provides a json library that enables JSON encoding of data.

import json
data = dict(
    first = "Foo",
    last = "Bar",
assert json.dumps(data) == '{"last": "Bar", "first": "Foo"}'

For more information see