[Python-ideas] anonymous object support

Nick Coghlan ncoghlan at gmail.com
Tue Jul 26 02:18:33 CEST 2011


On Tue, Jul 26, 2011 at 12:13 AM, Herman Sheremetyev
<herman at swebpage.com> wrote:
> A multi-line solution first requires a user-defined class. And I feel
> like we really shouldn't have to define a class just to create an
> object that we throw away two lines later.

Defining classes isn't a big deal. It's just fancy syntax for calling
the metaclass (as the equivalent code based on a direct call to type
shows).

If it really bothers you, hide it in a helper function:

def anon_object(**class_attrs):
    class Anon(object):
        pass
    Anon.__dict__.update(class_attrs)
    return Anon()

def anon_object(**class_attrs):
    return type('Anon', (), class_attrs)()

Or you could have a bit of mercy on the people that are going to have
to maintain this code and give the class a meaningful name that will
be displayed in tracebacks. Maybe go crazy and do something radical
like give it a docstring. The person lost in the maze of twisty
anonymous objects, strangely alike, may be you in 6 months time.

> Using type()'s current
> totally unwieldy API to do such an extremely simple and common thing
> is again not really a good answer IMO.

What you propose is not common. You have presented no use cases other
than mock objects, and you have stated that your own proposal is
inadequate for that use case. Anonymous objects trade a little bit of
typing and thought for the code author for the loss of meaningful
information that could benefit future maintainers.

There is absolutely zero reason to add additional complexity to the
language core or the standard library for such a niche (and
questionable) use case when a simple wrapper function around type can
do the job.

Regards,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list