tags:

views:

408

answers:

2

I'm debugging some Python that takes, as input, a list of objects, each with some attributes.

I'd like to hard-code some test values -- let's say, a list of four objects whose "foo" attribute is set to some number.

Is there a more concise way than this?

x1.foo = 1
x2.foo = 2
x3.foo = 3
x4.foo = 4
myfunc([x1, x2, x3, x4])

Ideally, I'd just like to be able to say something like:

myfunc([<foo=1>, <foo=2>, <foo=3>, <foo=4>])

(Obviously, that is made-up syntax. But is there something similar that really works?)

Note: This will never be checked in. It's just some throwaway debug code. So don't worry about readability or maintainability.

+6  A: 

Have a look at this:


class MiniMock(object):
    def __new__(cls, **attrs):
        result = object.__new__(cls)
        result.__dict__ = attrs
        return result

def print_foo(x):
    print x.foo

print_foo(MiniMock(foo=3))
Tetha
+6  A: 

I like Tetha's solution, but it's unnecessarily complex. Here's something simpler:

>>> class MicroMock(object):
>>>     def __init__(self, **kwargs):
>>>         self.__dict__.update(kwargs)
>>>
>>> print_foo(MicroMock(foo=3))
3
DzinX
However, if you're creating a whole bunch of these, you might save some time/memory by using the given dictionary instead of creating a new one and copying all the entries. Doesn't *really* matter, though.
jleedev
+1: use this all the time.
S.Lott
well, I might be subjective, but I see no substantial simplification. Yes, you use __init__ and update, but youre still fiddling around with __dict__.
Tetha
You're right, there's no significant simplification. It's just shorter and doesn't use __new__, that's all.
DzinX