Archive for the 'Python' Category

Easy examples of redundancy

2008-07-29-Tue

The following are some examples of simple redundancies in procedural programming. They are given in Python. I typically run into these when I simplify my code after writing it for the first time or after making edits.
Using if-else to assign a Boolean:
if condition:
x = True
else:
x = False
Simplified:
x [...]

Department of redundancy department: Python lambdas

2008-07-29-Tue

A coworker recently pointed out the lambda (anonymous function) in this piece of code that I wrote was redundant:
project_key_regex = re.compile(r”^project(\d+)$”)
for key in filter(lambda k: project_key_regex.match(k), req.args.keys()):

It would be improved like this:
project_key_regex = re.compile(r”^project(\d+)$”)
for key in filter(project_key_regex.match, req.args.keys()):

Apparently, methods of an object can be thought of as [...]

My misinterpretation of Python decorators

2008-06-22-Sun

DrProject is written in Python, but I had only a little experience with Python when I first started. So I had to learn many things along the way, sometimes in the hard way.
Today’s topic is the semantics of decorators in Python (PEP 318). I used to think I knew how they worked, but I was [...]

Default behaviour of comparisons in Python

2008-06-09-Mon

Browsing DrProject’s code base a moment ago, I came across this piece of code in drproject.project.Project: (I abbreviated the long expression a bit)
def get_members(self):
members = [m.user for m in Membership.query.filter_by(...)]
members.sort()
[...]

Singleton metaclass example

2008-05-21-Wed

Here’s a metaprogramming example that I conceived, involving the use of a metaclass to implement the singleton property.
class Counter(object):

    global_count = 0
    count_by_class = {}

    @staticmethod
    def count(obj):
        cls = obj.__class__
        class_count = Counter.count_by_class.get(cls, 0)
        result = (Counter.global_count, class_count)
        Counter.global_count += 1
        Counter.count_by_class[cls] = class_count + 1
        return result

class CountedObject(object):

    def __init__(self):
        print “Creating instance [...]