Getting a callable for any value?

C

Croepha

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

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

Steven D'Aprano

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top