Friday, September 30, 2011

__slots__ cannot be updated

>>> class Slots(object):  __slots__ = ()
>>> Slots.__slots__ = ('t',)
>>> Slots.__slots__
>>> s2 = Slots()
>>> s2.t = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Slots' object has no attribute 't'


With three kinds of member access, it is easier to use than ever.

>>> def namedtupledict(*a, **kw):
...    namedtuple = collections.namedtuple(*a, **kw)
...    def getitem(self, key):
...       if type(key) == str:
...           return getattr(self, key)
...       return tuple.__getitem__(self, key)
...    namedtuple.__getitem__ = getitem
...    return namedtuple
>>> t = namedtupledict('t', 'a b c')
>>> t1 = t(1,2,3)
>>> t1.a
>>> t1[0]
>>> t1['a']

Thursday, September 29, 2011

Wednesday, September 21, 2011

I'm my own grandpa.

A fellow Pythonaut had a simple problem...
How to test code with dependencies on the date?  Specifically, a Django project with models that have DateTimeFields with auto_now=True.

The chosen approach was to monkey-patch in order to return a constant value.
The first snag: is a C class.  This means it is not monkey-patchable.

This can be solved by monkey-patching the entire class.  The most straightforward thing to replace with is a new subclass of, whose only change is to override the today() function.

The second problem: there are now two kinds of's floating around the system.  Those by, and those created by every other function, which being C code will still return the same class.

Specifically, DateTimeField validates isinstance(data, before saving to the database.

A class which is simultaneously a super and subclass of is required.
Override __subclasshook__ so that isinstance(super(, is True.

>>> class DateProxy(
...    __metaclass__ = abc.ABCMeta
...    @classmethod
...    def __subclasshook__(cls, C): return True
...    @classmethod
...    def today(cls): return,9,20)
>>> = DateProxy

In other words, the superclass is also a subclass.  The parent of the parent being the grandparent, this class is it's own grandpa.