[Python-ideas] Why shouldn't Python be better at implementing Domain Specific Languages?

Matthew Einhorn moiein2000 at gmail.com
Fri Aug 31 14:57:18 EDT 2018


On Thu, Aug 30, 2018 at 8:31 PM James Lu <jamtlu at gmail.com> wrote:

> Why shouldn't Python be better at implementing Domain Specific Languages?
>
> [snip]
>
> It would be nice if there was a DSL for describing neural networks (Keras).
> The current syntax looks like this:
>
> model.add(Dense(units=64, activation='relu', input_dim=100))
> model.add(Dense(units=10, activation='softmax'))
>
>
How about something like this?

with model:
    with Dense() as dense:
        dense.units = 64
        dense.activation = 'relu'
        dense.input_dim = 100

    with Dense() as dense:
        dense.units = 10
        dense.activation = 'softmax'

The `with` creates a context to which subsequent layers are added when
created within the context.

But it does suffer from the fact that the `with` object's (or the
underlying stack that would implement
this in the model/layers) scope is not local to the function, so if within
the `with` context you call a
function that creates a layer, the layer will be added to the caller's
context, which would be surprising.

I was working on a similar approach for a python GUI, and `with` seemed
like a very nice candidate,
but ran into this issue, which didn't seem to have a clean fix.

I also thought about using an decorator that pre-processes the AST for a
GUI description, which for
your example would look like something like:

with model:
    with Dense():
        units = 64
        activation = 'relu'
        input_dim = 100

    with Dense():
        units = 10
        activation = 'softmax'

But here the issues are (a) the similarity with local variables may be
confusing (b) you'd need to
either make all `with` statements special, or annotate the `with`
statements that are going to be
processed by the compiler (e.g. by prefixing the object with a dash). It
seemed messy
enough that I'm still pondering this.

Matt
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180831/7d7af904/attachment.html>


More information about the Python-ideas mailing list