Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #46399 > unrolled thread

Re: Getting a callable for any value?

Started byNed Batchelder <ned@nedbatchelder.com>
First post2013-05-29 14:10 -0400
Last post2013-05-29 14:10 -0400
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Getting a callable for any value? Ned Batchelder <ned@nedbatchelder.com> - 2013-05-29 14:10 -0400

#46399 — Re: Getting a callable for any value?

FromNed Batchelder <ned@nedbatchelder.com>
Date2013-05-29 14:10 -0400
SubjectRe: Getting a callable for any value?
Message-ID<mailman.2369.1369851066.3114.python-list@python.org>

[Multipart message — attachments visible in raw view] — view raw

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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web