On 5/29/2013 1:46 PM, Croepha wrote:
Is there anything like this in the standard library?

class AnyFactory(object):
def __init__(self, anything):
self.product = anything
def __call__(self):
return self.product
def __repr__(self):
return "%s.%s(%r)" % (self.__class__.__module__, self.__class__.__name__, self.product)

my use case is: collections.defaultdict(AnyFactory(collections.defaultdict(AnyFactory(None))))

And I think lambda expressions are not preferable...


It's not clear to me that this does what you want. Won't your defaultdict use the same defaultdict for all of its default values? This is hard to describe in English but:

    d = 
collections.defaultdict(AnyFactory(collections.defaultdict(AnyFactory(None))))

    d[1][1] = 1
    d[2][2] = 2

    print d[1]
    #->  defaultdict(__main__.AnyFactory(None), {1: 1, 2: 2})
    print d[1] is d[2]
    #->  True

It might not be possible to get this right without lambdas:

    d = collections.defaultdict(lambda: collections.defaultdict(lambda: None))

    d[1][1] = 1
    d[2][2] = 2

    print d[1]
    #->  defaultdict(<function <lambda> at 0x02091D70>, {1: 1})
    print d[1] is d[2]
    #->  False


--Ned.

I found itertools.repeat(anything).next and functools.partial(copy.copy, anything)

but both of those don't repr well... and are confusing...

I think AnyFactory is the most readable, but is confusing if the reader doesn't know what it is, am I missing a standard implementation of this?




-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to