Proposal: Magic Constants

Bernhard Herzog bh at intevation.de
Wed Aug 27 11:05:13 EDT 2003


"John Roth" <newsgroups at jhrothjr.com> writes:

> "Chris Gonnerman" <chris.gonnerman at newcenturycomputers.net> wrote:
>> Modules to handle alternate numeric formats, such
>> as decimal, fixed-point, rational, etc. would
>> include a call to a builtin registration function
>> which would allow them to "take over" a specific
>> alphabetic specifier.
>
> There's another namespace with a possibility
> of collisions here, and also the same old "we
> can't make one of these a builtin because it
> might break user code."

This could be alleviated by doing something similar to how metaclasses
can be specified at the module level. Put a dictionary mapping suffixes
to constructors into a module level variable called e.g. __literals__ so
that you'd either do it by hand like this:

__literals__ = {"r": Rational}

or if you only need e.g. rational literals in your module could do

from rational import __literals__

Assuming the rational module provides a suitable dictionary for the
user's convenience.

> One overall thought: why limit it to numbers?
> The new datetime module would benefit from
> a datetime literal, but that would have to be
> a character string.

Indeed. 

Allowing this for strings would also provide a way to get self
interpolating string literals because the constructor could use
introspection to get a dictionary with all local variables in the
calling scope.

> Another thing to think about is whether
> this could cause problems with existing
> code. I can't immediately think of a case
> where a literal can be next to a character,

I think "1.or 2" would have to produce a syntax error under the new
rules.


    Bernhard

-- 
Intevation GmbH                                 http://intevation.de/
Sketch                                 http://sketch.sourceforge.net/
Thuban                                  http://thuban.intevation.org/




More information about the Python-list mailing list