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


Groups > comp.lang.python > #46399

Re: Getting a callable for any value?

Date 2013-05-29 14:10 -0400
From Ned Batchelder <ned@nedbatchelder.com>
Subject Re: Getting a callable for any value?
References <CANm61jeHSZL1FQvTr9FS0QKEhFPXug0fibXBEA-4guYF1Lf7UQ@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.2369.1369851066.3114.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

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

csiph-web