[Python-ideas] anonymous object support

Herman Sheremetyev herman at swebpage.com
Mon Jul 25 11:44:57 CEST 2011


On Mon, Jul 25, 2011 at 7:47 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> On Mon, Jul 25, 2011 at 2:03 AM, Guido van Rossum <guido at python.org> wrote:
>> Also, every one believes there own favorite feature to be so important
>> that it's worth changing the language, but they don't want to grant
>> that to anybody else's favorite feature... :-)
>
> We've actually been down the 'namespace object' road years ago (Steve
> Bethard even wrote a proto-PEP IIRC) and it suffered the same fate as
> most enum PEPs: everyone has slightly different ideas on what should
> be supported, so you end up being faced with one of two options:
> 1. Ignore some of the use cases (so some users still have to do their own thing)
> 2. Support all of the use cases by increasing the API complexity (so
> many users will still do their own thing instead of learning the new
> API)
>
> In this space, collections.namedtuple is a well-executed variant of
> the first alternative. There are some use cases it doesn't handle, but
> it covers many of them and does it well.
>
> For the OP's use case, I'll simply note that this functionality is
> already provided by the type builtin:
>
> obj = type('Foo', (), dict(foo=(lambda x: x)))()

This one-liner with type is neat. For the record, it's missing "self"
so a working version would be a tad bit longer.

Using an empty name and using {} instead of dict() makes it look almost usable:

obj = type('', (), {'foo': lambda self, x: x})()

I think it would actually *be* usable if the dictionary passed in as
the last argument could also be built out of keyword arguments:

obj = type('', (), foo=lambda self, x: x)()

Giving those first two positional arguments default values (empty
string and empty tuple?) would make it even better:

obj = type(foo=lambda self, x: x)()

That's only one set of parens away from my initial proposal, but I
think it's close enough. Would there be any objections to changing the
type() API to support this?

Cheers,

-Herman



More information about the Python-ideas mailing list