Getting a callable for any value?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu May 30 02:41:01 EDT 2013
On Wed, 29 May 2013 12:46:19 -0500, 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))))
That's not a use-case. That's a code snippet. What does it mean? Why
would you write such an ugly thing? What does it do? I get a headache
just looking at it.
I *think* it's a defaultdict that returns a defaultdict on KeyError,
where the *second* defaultdict returns None.
from collections import defaultdict
defaultdict(lambda: defaultdict(lambda: None))
looks more reasonable to me. I don't know why you need to wrap such a
simple pair of functions in a class. This is not Java.
http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html
(Twice in one day I have linked to this.)
I'm not sure why you care about the repr of the "AnythingFactory" object.
You stuff it directly into the defaultdict, where you are very unlikely
to need to inspect it. You only ever see the defaultdicts they return,
and they already have a nice repr.
--
Steven
More information about the Python-list
mailing list