[Python-ideas] User-defined literals

Nick Coghlan ncoghlan at gmail.com
Thu Jun 4 15:48:43 CEST 2015


On 4 June 2015 at 23:06, Paul Moore <p.f.moore at gmail.com> wrote:
> As a straw man how about a new syntax (this won't work as written,
> because it'll clash with the "<" operator, but the basic idea works):
>
>     LITERAL_CALL = PRIMARY "<" <any source character except right
> angle bracket>* ">"

The main idea I've had for compile time metaprogramming that I figured
I might be able to persuade Guido not to hate is:

   python_ast, names2cells, unbound_names =
!(this_is_an_arbitrary_python_expression)

As suggested by the assignment target names, the default behaviour
would be to compile the expression to a Python AST, and then at
runtime provide some relevant information about the name bindings
referenced from it. (I haven't even attempted to implement this,
although I've suggested it to some of the SciPy folks as an idea they
might want to explore to make R style lazy evaluation easier)

By using the prefix+delimiters notation, it would become possible to
later have variants that were similarly transparent to the compiler,
but *called* a suitably registered callable at compile time to do the
conversion to runtime Python objects. For example:

   !sh(shell command)
   !format(format string with implicit interpolation)
   !sql(SQL query)

So for custom numeric types, you could register:

    d = !decimal(1.2)
    r = !rational(22/7)

This isn't an idea I'm likely to have time to pursue myself any time
soon (if ever), but I think it addresses the key concern with syntax
customisation by ensuring that customisations have *names*, and that
they're clearly distinguished from normal code.

Cheers,
Nick.


More information about the Python-ideas mailing list