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

Nick Coghlan ncoghlan at gmail.com
Wed May 17 07:43:01 EDT 2017


On 17 May 2017 at 13:14, Juancarlo Añez <apalala at gmail.com> wrote:
> On Tue, May 16, 2017 at 5:04 PM, Guido van Rossum <gvanrossum at gmail.com>
> wrote:
> What I like about attrs is:
>
> * The class level declaration of instance attributes
> * That the reasonable init, repr, and eq are generated

These are also the two main benefits for my own use cases, with easy
conversion to JSON compatible dicts being third.

I'm less bothered by the wordiness, hence my suggestion for borrowing
the attrs API design and doing this as a standard library module along
the lines of:

    from autoclass import data_record, field

    @data_record
    class Point3D:
        x: int = field(default=0)
        y: int = field(default=0)
        z: int = field(default=0)

While that's wordier than dedicated syntax in the simple cases, it
also means that

- if we want to define additional templates in the future, it just
means adding a new decorator to the autoclass module
- things like ORMs and other class based schema DSLs are a natural
extension of this "runtime class template" model,
- class level settings (e.g. declaring post-init immutability) are
just keyword arguments to a function call
- field level settings (e.g. omitting the field from the generated
repr) are just keyword arguments to a function call

Those last two points echo the primary reason that print was converted
from a statement to a builtin in Python 3

That said, even with this model, the base case of "fields with an
immutable or shared default" could potentially be simplified to:

    from autoclass import data_record

    @data_record
    class Point3D:
        x: int = 0
        y: int = 0
        z: int = 0

However, the potentially surprising behaviour there is that to
implement it, the decorator not only has to special case the output of
"field()" calls, but also has to special case any object that
implements the descriptor protocol to avoid getting confused by normal
method and property definitions.

Cheers,
Nick.

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


More information about the Python-ideas mailing list