[Zope-Checkins] CVS: Zope3/lib/python/Zope/App/Security - Registry.py:1.1.2.1

Barry Warsaw barry@wooz.org
Thu, 13 Dec 2001 13:00:33 -0500


Update of /cvs-repository/Zope3/lib/python/Zope/App/Security
In directory cvs.zope.org:/tmp/cvs-serv9434/lib/python/Zope/App/Security

Added Files:
      Tag: Zope-3x-branch
	Registry.py 
Log Message:
A new base class from which other *Registry classes can derive.


=== Added File Zope3/lib/python/Zope/App/Security/Registry.py ===
# Registry.py
#
# Copyright (c) 2001 Zope Coporation and Contributors.  All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 1.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS 
# FOR A PARTICULAR PURPOSE.

"""Generic registry of ids to objects."""

from Interface.verify import verify
from Zope.App.Security.IRegisteredObject import IRegisteredObject
from Zope.Exceptions import ZopeError


class AlreadyRegisteredError(ZopeError, ValueError):
    """An attempt was made to register an object with an already registered id.
    """


class Registry:
    def __init__(self, class_):
        """Instantiate a generic registry.

        class_ is the class of the thing that we're going to instantiate.
        """
        assert verify(IRegisteredObject, class_)
        self._class = class_
        self._clear()

    def register(self, id, title='', description=''):
        """Create a registered object with the given id, title, and description

        Register and return the object.  The empty string will be used if
        either the optional title or description is omitted.  The id must be
        unique.

        If the id is already registered, an AlreadyRegisteredError is raised.
        """
        if self._byid.has_key(id):
            raise AlreadyRegisteredError('Id is not unique: %s' % id)
        obj = self._class(id, title, description)
        self._byid[id] = obj
        return obj

    def is_registered(self, id):
        """Return true if an object is registered with the given id.
        Otherwise false is returned.
        """
        return self._byid.has_key(id)

    def getRegisteredObject(self, id):
        """Return the object registered under the given id.

        If no object is registered, a KeyError is raised.
        """
        return self._byid[id]

    def _clear(self):
        # Map ids to instantiated objects
        self._byid = {}