[Python-3000] Brainstorming: literal construction hooks (original) (raw)

Michael Urman murman at gmail.com
Sat Apr 22 04:41:17 CEST 2006


This idea isn't fully fleshed out, but I wanted to air it to see if it took wind or fell flat. Please forgive inaccuracies between lexing and parsing.

It's about being able to override what a given literal is turned into. It would only take effect in a limited scope, either per module, per compile/exec, or something similar. When a literal of a registered token type is parsed, its string would be passed to the provided function and whose return value would be used for the object. The following example, when registered, would be used to turn all float literals into decimal instances.

def float_literal(literal):
    return decimal.Decimal(literal)

More simply decimal.Decimal could be registered as the literal constructor if just the literal's string is used. Alternative signatures could allow a single function to handle multiple token types, or could make applying modifications to normal types simpler, but would prevent the obvious use of decimal.Decimal as above. I see token_type and value (as normally parsed) as obvious candidates for this.

This could be used for people who want to create auto-substituting string literals (which I dislike for I18N reasons) without having to shoehorn its own syntax into the language.

There's a lot of holes to this story, including at least how these functions are registered, and which additional arguments (if any) are necessary. Shall we try to fill these holes in?

Michael

Michael Urman http://www.tortall.net/mu/blog



More information about the Python-3000 mailing list