[Python-ideas] anonymous object support

Herman Sheremetyev herman at swebpage.com
Sun Jul 24 16:04:53 CEST 2011


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()

It would be a bit easier if Python allowed attributes to be set on
instances of builtins the way it does for user-defined classes. This
would at least allow something like:

obj = object()
obj.foo = lambda x: x

Alas, that is not possible either as the assignment raises an
AttributeError when dealing with instances of builtins.

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

Python implementation of __new__ would look something like the
following, though I suppose this would need to be done at the C level
in reality:

  def __new__(typ, **kwargs):
    obj = object.__new__(typ)
    for attr, value in kwargs.items():
      setattr(obj, attr, value)
    return obj

So why do we need this? Primarily, this sort of thing is very common
in tests where it is often useful to generate anonymous objects with
default values. As a result, a number of libraries have risen to fill
this need which is a pretty strong indicator that it is a useful
pattern, and everyone using one of a dozen different libraries to
accomplish the same basic task does not seem very Pythonic. I could
also see this being quite useful in quick prototyping scenarios in
order to avoid using dicts when an object is more suitable without
requiring the overhead of defining a class.

I'm curious if people on this list would be interested in seeing
support for this added to the language, or if there are some good
reasons I have overlooked for why this sort of change might be
undesirable.

Cheers,

-Herman



More information about the Python-ideas mailing list