[Python-ideas] English builtins for Python

Arnaud Delobelle arno at marooned.org.uk
Thu Jun 21 19:41:26 CEST 2007


On Thu, June 21, 2007 10:36 am, Steve Howell wrote:
[...]
> It's amazing how uncommon "the"
> and "a" are in mainstream programming languages.  I'm
> not saying they should be (although I think there's
> some argument to using "the" for singletons), I just
> find it curious that they shouldn't be, and there's
> been enough evolution on programming languages (albeit
> a small amount of time compared to natural languages)
> to suggest that articles (as builtins) are just
> somehow *wrong* in programming languages.  Yet they're
> so incredible popular in "natural" languages.

from random import randrange

ABIGNUMBER = 100000 # or should it be THEBIGNUMBER?

class ArticleError(Exception): pass

def the(s):
    try:
        s = iter(s)
        ret = s.next()
        for el in s: raise ArticleError
        return ret
    except (StopIteration, TypeError):
        raise ArticleError("'the' argument must be a singleton iterable")

def a(s):
    try:
        s = iter(s)
        for i, el in enumerate(s):
            if not randrange(i+1): ret = el
            if i == ABIGNUMBER: return ret
        return ret
    except (NameError, TypeError):
        raise ArticleError("'a' argument must be a non-empty iterable")

an = a # for convenience :)

--------------------- How to use 'a(n)' and 'the' -------

>>> a ('python')
'y'
>>> a ('python')
'n'
>>> an (x for x in range(10) if x+x==x*x)
0
>>> an (x for x in range(10) if x+x==x*x)
0
>>> an (x for x in range(10) if x+x==x*x)
2
>>> the (x for x in range(10) if x+x==x*x)
Traceback (most recent call last):
...
__main__.ArticleError: 'the' argument must be a singleton iterable
>>> the (x for x in range(1, 10) if x+x==x*x)
2
>>> from itertools import count
>>> a (count())
81294
>>> a (count())
41746
>>> from itertools import repeat
>>> a (repeat('spam'))
'spam'
>>>

-- 
Arnaud





More information about the Python-ideas mailing list