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


Groups > comp.lang.python > #46401

Re: Getting a callable for any value?

References <CANm61jeHSZL1FQvTr9FS0QKEhFPXug0fibXBEA-4guYF1Lf7UQ@mail.gmail.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2013-05-29 12:20 -0600
Subject Re: Getting a callable for any value?
Newsgroups comp.lang.python
Message-ID <mailman.2371.1369851646.3114.python-list@python.org> (permalink)

Show all headers | View raw


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

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


Thread

Re: Getting a callable for any value? Ian Kelly <ian.g.kelly@gmail.com> - 2013-05-29 12:20 -0600

csiph-web