Getting a callable for any value?

Ned Batchelder ned at nedbatchelder.com
Wed May 29 14:10:58 EDT 2013


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?
>
>
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130529/d5957e33/attachment.html>


More information about the Python-list mailing list