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


Groups > comp.lang.python > #46401 > unrolled thread

Re: Getting a callable for any value?

Started byIan Kelly <ian.g.kelly@gmail.com>
First post2013-05-29 12:20 -0600
Last post2013-05-29 12:20 -0600
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#46401 — Re: Getting a callable for any value?

FromIan Kelly <ian.g.kelly@gmail.com>
Date2013-05-29 12:20 -0600
SubjectRe: Getting a callable for any value?
Message-ID<mailman.2371.1369851646.3114.python-list@python.org>
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)

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web