Entries tagged "python"

Python LazyDict

Nov 4, 2008 2:42:00 PM

I'm a great fan of the dot notation, instead of foo['bar'] hash notation. Also because the Django and Jinja templating engines use dot notation for all their object attribute/key lookups.

You can also use assignments and lookups on a dictionary, using the __setattr__ and __getattr__ methods:

class LazyDict(dict):
    def __getattr__(self, attr):
        if attr in self:
            return self[attr]
        else:
            raise AttributeError, "'%s' object has no attribute '%s'" \
                % (self.__class__.__name__, attr)

    def __setattr__(self, attr, value):
        if hasattr(super(LazyDict, self), attr):
            raise AttributeError, "'%s' object already has attribute '%s'" \
                % (self.__class__.__name__, attr)
        self[attr] = value

This allows you to do:

>>> from lazydict import LazyDict
>>> foo = LazyDict()
>>> foo.bar = 42
>>> foo.bar
42
>>> foo.biz = LazyDict()
>>> foo.biz.qux
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "lazydict.py", line 6, in __getattr__
AttributeError: LazyDict instance has no attribute 'qux'
>>> foo.biz.qux = object()
>>> foo.biz.qux
<object object at 0xb7d26468>

Update Nov 12, 1008

Incorporated Floes' suggestions from the comment below, thanks!

 

Stacking Django Q lookups in OR/AND fashion

Oct 1, 2008 12:49:00 AM

Just a quick one so I won't forget, I was wondering how to compile a OR lookup stack from a list of Q objects.

>>> # Import the operator built-in module
>>> import operator
>>> from django.db.models import Q
>>> from mytest.models import Test
>>> # Create an arbitrary set of test-data
>>> for x in xrange(0, 99): Test(test=x).save()
>>> # The lookups
>>> lookups = [Q(test=1), Q(test=2), Q(test=23), Q(test=42)]
>>> # Here we use reduce()
>>> print Test.objects.filter(reduce(operator.or_, lookups))
[<Test test=1>, <Test test=2>, <Test test=23>, <Test test=42>]

This also works for operator.and_.

 

Django 1.0 released

Sep 4, 2008 10:46:00 AM

It has been a bumpy ride, and it has taken some time to get there, but the Django 1.0 version has been finally released!

Read on..., 1 comment.

 

ANSI engine

Aug 18, 2008 8:47:00 PM

I wrote an engine that converts ANSI/ASCII files to PNG, just for fun. Check them out here.

 

TextPress, there we go

Jul 27, 2008 3:58:00 PM

After looking for a decent blogging application for some months, I decided to install TextPress from the guys at PoCoo. It includes most of my favorite Python components.

Read on..., 3 comments.

 

Visitors

Locations of visitors to this page