[Python-ideas] anonymous object support

Herman Sheremetyev herman at swebpage.com
Tue Jul 26 04:58:22 CEST 2011


On Tue, Jul 26, 2011 at 11:42 AM, Guido van Rossum <guido at python.org> wrote:
> On Mon, Jul 25, 2011 at 7:30 PM, Herman Sheremetyev <herman at swebpage.com> wrote:
>> On Tue, Jul 26, 2011 at 9:18 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> <snip>
>>> 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.
>>
>> As you yourself pointed out, the complexity is already there in the
>> core language hiding in a single line of API description to the type()
>> function. It's already there to be used, but provides very little
>> documentation and an API that is sure to baffle anyone that comes
>> across code that uses it.
>>
>> To reiterate, I am proposing improving the type() API to provide some
>> reasonable defaults while retaining backwards compatibility.
>
> Can you summarize the proposal for those who didn't follow the thread
> blow-by-blow? Your first message proposed keyword arguments to
> object(), which can't fly because object() creates objects without a
> __dict__. Now you suddenly seem to have switched to adding more
> complexity to type(). But what exactly?

So the initial solution with type() posted above was:

    obj = type('Foo', (), dict(foo=(lambda x: x)))()

Adding the necessary "self" to the lambda, using an empty name, and
replacing dict() with {} makes it slightly easier to parse:

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

[here are the API changes I propose]

Going an extra step and making it possible for the dictionary to be passed in as
keyword arguments would make it even nicer:

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

And going one final step to give those first two positional arguments
default values (empty
string and empty tuple? or "Anonymous" and empty tuple?) would make it
even better:

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

>> In other
>> words, making an *existing* difficult-to-use API into an intuitive
>> one.
>>
>> FWIW, I think the type() function is not really a great choice for
>> making classes on the fly. But if that's what we have to use then
>> let's at least make it a little more user-friendly.
>
> So you are proposing to make an undesirable API more user-friendly.
> Isn't that creating an attractive nuisance?

Well, I think it's not very intuitive that type() can be used as a
class constructor. But it is what it is at this stage, so if I come
across it in code or write it myself I'd rather it provided some
reasonable defaults.

-Herman



More information about the Python-ideas mailing list