ActiveState Code

Recipe 576447: Dummy object


Have you wished for a completely Dummy object, one that you can do whatever you want to it? One you can return and all expressions will work?

No???

Hmm.. ok. But here it is anyway.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Dummy(object):
    def __getattr__(self, attr):
        try:
            return super(self.__class__, self).__getattr__(attr)
        except AttributeError:
            if attr in ('__base__', '__bases__', '__basicsize__', '__cmp__',
                        '__dictoffset__', '__flags__', '__itemsize__',
                        '__members__', '__methods__', '__mro__', '__name__',
                        '__subclasses__', '__weakrefoffset__',
                        '_getAttributeNames', 'mro'):
                raise
            else:
                return self
    def next(self):
        raise StopIteration
    def __repr__(self):
        return 'Dummy()'
    def __init__(self, *args, **kwargs):
        pass
    def __len__(self):
        return 0
    def __eq__(self, other):
        return self is other
    def __hash__(self):
        return hash(None)
    def __call__(self, *args, **kwargs):
        return self
    __sub__ = __div__ = __mul__ = __floordiv__ = __mod__ = __and__ = __or__ = \
    __xor__ = __rsub__ = __rdiv__ = __rmul__ = __rfloordiv__ = __rmod__ = \
    __rand__ = __rxor__ = __ror__ = __radd__ = __pow__ = __rpow__ = \
    __rshift__ = __lshift__ = __rrshift__ = __rlshift__ = __truediv__ = \
    __rtruediv__ = __add__ = __getitem__ = __neg__ = __pos__ = __abs__ = \
    __invert__ = __setattr__ = __delattr__ = __delitem__ = __setitem__ = \
    __iter__ = __call__

Dummy = Dummy()

Discussion

You can now use Dummy anytime any object is required.

>>> a = Dummy() ; d = Dummy() ; j = Dummy(3)
>>> j **= (d + 3) * (a / j)
>>> print j is j('parameters', any='parameters').attribute.access.is_.allowed['and item']()()
True
>>> print (d < j, d > j, d == j)
(False, False, True)
>>> print sorted([Dummy(n + d) for n in xrange(3)]), sorted(a)
[Dummy(), Dummy(), Dummy()] []
>>> print '%d == %d == 0' % (len(a), len(list(a)))
0 == 0 == 0

Comments

  1. 1. At 12:51 a.m. on 24 aug 2008, Louis Riviere said:

    see : Null in recipe 68205

  2. 2. At 9:29 a.m. on 27 aug 2008, nosklo (the author) said:

    Thanks for pointing me this recipe, Louis.

    But since I use a different approach, testing for special attributes and overriding all main functions of objects. Null works only for attributes and calls, and raises errors for a lot of uses.

    I guess that's why I named it Dummy, it can act as a list, or as a dict, or as anything else.

Sign in to comment