Getting a callable for any value?

Ian Kelly ian.g.kelly at gmail.com
Wed May 29 14:20:02 EDT 2013


On Wed, May 29, 2013 at 11:46 AM, Croepha <croepha at gmail.com> 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)

In other words, the function (lambda: x) with a repr that tells you
what x is?  Not that I'm aware of, but you could just do something
like:

def return_x(): return x

And then the repr will include the name "return_x", which will give
you a hint as to what it does.

Also, "AnyFactory" is a misleading name because the class above is not
a factory.

> my use case is:
> collections.defaultdict(AnyFactory(collections.defaultdict(AnyFactory(None))))
>
> And I think lambda expressions are not preferable...

What you have above is actually buggy.  Your "AnyFactory" will always
return the *same instance* of the passed in defaultdict, which means
that no matter what key you give to the outer defaultdict, you always
get the same inner defaultdict.

Anyway, I think it's clearer with lambdas:

defaultdict(lambda: defaultdict(lambda: None))

But I can see your point about the repr.  You could do something like this:

class NoneDefaultDict(dict):
    def __missing__(self, key):
        return None
    def __repr__(self):
        return "NoneDefaultDict(%s)" % super(NoneDefaultDict, self).__repr__()

some_dict = defaultdict(NoneDefaultDict)



More information about the Python-list mailing list