Life's better without braces

Bernhard Herzog herzog at online.de
Fri Feb 25 13:21:38 EST 2000


Michael Hudson <mwh21 at cam.ac.uk> writes:

> Gerrit Holl <gerrit.holl at pobox.com> writes:
> 
> > <quote name="Andrew M. Kuchling" date="951150482">
> > > [2] I occasionally think about this problem.  The setup: GvR was far
> > > too profligate in adding functions to bltinmodule.c that could have
> > > been written in pure Python instead.  So, how many built-in functions
> > > can you re-implement in pure Python? 
> > 
> > These are possible:
> > 
> > abs, callable, chr, delattr, divmod,
> > execfile, filter, getattr, hex, input, int, isinstance, issubclass,
> > len, list, long, map, max, min, oct, range, raw_input, reduce, reload,
> > repr, setattr, tuple, vars.

Is it posssible to implement getattr, setattr and delattr without eval
or exec? How do you implement len for builtin types without
iterating through the indices until an IndexError is raised?

How do you implement callable?

I think you forgot str and cmp, but they're easy:

def str(obj):
    return "%s" % (obj,)

def cmp(a, b):
    if a > b:
        return 1
    if a < b:
        return -1
    return 0

ord should also be possible.

> > These aren't:
> > 
> > apply, buffer, coerce, compile, complex, dir, eval, exit, globals, hash,
> > id, intern, locals, round, slice, type, xrange


> To followup to a different bit of the thread about 30 seconds after
> the last one, I think you can actually do quite a few of these.
> 
> `compile' would be a lot of work, but given the `new' module,
> definitely possible (ask Jeremy Hylton!).
> `dir' shouldn't be too hard given `type' & some knowledge of Python
> internals.
> `eval' can be done using `compile' & `exec'.
> `globals' and `locals' can be done using the usual sys.exc_traceback
> mucking around.
> The builtin `exit' is just a string!

slice is also possible:

class slicefactory:

    def __getitem__(self, slice):
        return slice

    def slice(self, *args):
        start = 0
        step = 1
        if len(args) == 1:
            stop = args[0]
        elif len(args) == 2:
            start, stop = args
        elif len(args) == 3:
            start, stop, step = args
        return self[start:stop:step]

slice = slicefactory().slice

When I tested this, it turned out that you can't compare slices
properly:

>>> slice(5, 20, 3) == slice(5, 20, 3)
0


complex is trivial:

def complex(r, i = 0):
    return r + i * 1j 

and round wouldn't be too difficult either, I guess.




-- 
Bernhard Herzog   | Sketch, a drawing program for Unix
herzog at online.de  | http://sketch.sourceforge.net/



More information about the Python-list mailing list