[Python-Dev] Capabilities

Ka-Ping Yee ping@zesty.ca
Sun, 30 Mar 2003 11:31:37 -0600 (CST)

On Sat, 29 Mar 2003, Ka-Ping Yee wrote:
> Okay, at last to the example, then.

The following is a better formulation in the capability style --
please ignore the previous one.

The previously posted code allows names to carry authority, which
is a big no-no.  This code gets rid of names altogether in the API
for file access; it's better to deal with just objects.

    import os, __builtin__

    class Namespace:
        def __init__(self, *args, **kw):
            for value in args:
                self.__dict__[value.__name__] = value
            for name, value in kw.items():
                self.__dict__[name] = value

    class ImmutableNamespace(Namespace):
        def __setattr__(self, name, value):
            raise TypeError('read-only namespace')

    def ReadStream(file, name):
        def __repr__():
            return '<ReadStream %r>' % name

        return ImmutableNamespace(__repr__, file.read, file.close, name=name)

    def FileReader(path, name):
        def __repr__():
            return '<FileReader %r>' % name

        def open():
            return ReadStream(__builtin__.open(path, 'r'), name)

        def getsize():
            return os.path.getsize(path)

        def getmtime():
            return os.path.getmtime(path)

        return ImmutableNamespace(__repr__, open, getsize, getmtime, name=name)

    def DirectoryReader(path, name):
        def __repr__():
            return '<DirectoryReader %r>' % name

        def getfiles():
            files = []
            for name in os.listdir(path):
                fullpath = os.path.join(path, name)
                if os.path.isfile(fullpath):
                    files.append(FileReader(fullpath, name))
            return files

        def getdirs():
            dirs = []
            for name in os.listdir(path):
                fullpath = os.path.join(path, name)
                if os.path.isdir(fullpath):
                    dirs.append(DirectoryReader(fullpath, name))
            return dirs

        return ImmutableNamespace(__repr__, getfiles, getdirs, name=name)

-- ?!ng