[Python-ideas] anonymous object support

Antoine Pitrou solipsis at pitrou.net
Sun Jul 24 16:30:55 CEST 2011


On Sun, 24 Jul 2011 23:04:53 +0900
Herman Sheremetyev <herman at swebpage.com>
wrote:
> It is currently somewhat difficult/awkward to create arbitrary
> "anonymous" objects in Python. For example, to make some object that
> simply has a foo() method you have to declare a class that defines
> foo() and instantiate it:
> 
> class Foo:
>   def foo(self, x): return x
> obj = Foo()
> 
[...]
> 
> obj = object()
> obj.foo = lambda x: x

Well, really, you're saving *one* line of code all the while making
things more obscure (if "obj" gets printed out for whatever reason, you
won't ever know it's a Foo or has a foo method).

> I would like to propose a different solution: alter object.__new__()
> to support keyword arguments and set the attributes named in the
> keyword arguments to their requested value. This would get us code
> like:
> 
> obj = object(foo=1, bar=lambda x: x)
> obj.foo
> >>> 1
> obj.bar(2)
> >>> 2

If that's all you need, you just have to write a convenience function
that you put in some utilities module:

class AnonymousObject:
    pass

def make(**kwargs):
    obj = AnonymousObject()
    for k, v in kwargs.items():
        setattr(obj, k, v)
    return obj


and then:

>>> from myutils import make
>>> obj = make(foo=1, bar=lambda x: x)
>>> obj.foo
1
>>> obj.bar(1)
1


Or you can also create a namedtuple class, if there's a well-defined
set of attributes your instance(s) will have.

Regards

Antoine.





More information about the Python-ideas mailing list