[Python-ideas] JavaScript-Style Object Creation in Python (using a constructor function instead of a class to create objects)

Steven D'Aprano steve at pearwood.info
Sun May 14 07:39:21 EDT 2017

On Sun, May 14, 2017 at 07:35:38AM +0000, Simon Ramstedt wrote:

> Leaving the possible replacement for classes aside, do you have an opinion
> specifically about the following?
> def obj.my_function(a, b):
>    ...
> as syntactic sugar for
> def my_function(a, b):
>   ...
> obj.my_function = my_function

Personally, I don't object to it, I can see the idea has some merit.

See the most recent discussion here:


> In my experience this pattern comes actually up quite a bit. E.g. when
> working with these "symbolic" machine learning frameworks like theano or
> tensorflow. Apart from that it mixins very easy.
> What do you think are the odds of something like this actually making it
> into the Python and if greater than 0 in which timeframe?

Somebody would need to propose some compelling use-cases for where this 
is clearly better than the status quo. Guido would have to not object. 
Somebody would have to volunteer to do the work, and it would have to 
not cause an unacceptible performance hit. (I doubt that it would, 
since it's just a small amount of new syntactic sugar.)

If you can show actual real-life code that would be improved by this new 
feature, that would increase the probability.

If you can prove that it would be a benefit to (let's say) the Theano 
community, that would increase the probability.

If you volunteered to do the work, rather than expect somebody else to 
do it, that would *significantly* increase the probability of it 
actually happening, provided the suggestion was actually accepted.

If you read the previous discussion, I think the conclusion was that 
there is nothing that 

def Some_Object.name(x): ...

can do that cannot be emulated by a decorator:

def name(x): ...

*except* that the decorator solution would leave the function "name" 
polluting the current namespace, and the new syntax could avoid that.

And even that is easy to work-around:

del name

So I think the probability is low, but not zero. It would help if you 
could prove a significant real-world use-case for injecting functions 
into existing objects.


More information about the Python-ideas mailing list