~certify-web-dev/twisted/certify-trunk

« back to all changes in this revision

Viewing changes to twisted/python/components.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2007-01-17 14:52:35 UTC
  • mfrom: (1.1.5 upstream) (2.1.2 etch)
  • Revision ID: james.westby@ubuntu.com-20070117145235-btmig6qfmqfen0om
Tags: 2.5.0-0ubuntu1
New upstream version, compatible with python2.5.

Show diffs side-by-side

added added

removed removed

Lines of Context:
30
30
from twisted.persisted import styles
31
31
 
32
32
# system imports
33
 
import sys
34
 
import types
35
33
import warnings
36
34
 
37
35
# zope3 imports
39
37
from zope.interface.adapter import AdapterRegistry
40
38
 
41
39
class ComponentsDeprecationWarning(DeprecationWarning):
42
 
    """So you can filter new-components related deprecations easier."""
 
40
    """Nothing emits this warning anymore."""
43
41
    pass
44
42
 
45
43
# Twisted's global adapter registry
48
46
# Attribute that registerAdapter looks at. Is this supposed to be public?
49
47
ALLOW_DUPLICATES = 0
50
48
 
 
49
# Define a function to find the registered adapter factory, using either a
 
50
# version of Zope Interface which has the `registered' method or an older
 
51
# version which does not.
 
52
if getattr(AdapterRegistry, 'registered', None) is None:
 
53
    def _registered(registry, required, provided):
 
54
        """
 
55
        Return the adapter factory for the given parameters in the given
 
56
        registry, or None if there is not one.
 
57
        """
 
58
        return registry.get(required).selfImplied.get(provided, {}).get('')
 
59
else:
 
60
    def _registered(registry, required, provided):
 
61
        """
 
62
        Return the adapter factory for the given parameters in the given
 
63
        registry, or None if there is not one.
 
64
        """
 
65
        return registry.registered([required], provided)
 
66
 
 
67
 
51
68
def registerAdapter(adapterFactory, origInterface, *interfaceClasses):
52
69
    """Register an adapter class.
53
70
 
65
82
        origInterface = declarations.implementedBy(origInterface)
66
83
 
67
84
    for interfaceClass in interfaceClasses:
68
 
        factory = self.get(origInterface).selfImplied.get(interfaceClass, {}).get('')
69
 
        if (factory and not ALLOW_DUPLICATES):
 
85
        factory = _registered(self, origInterface, interfaceClass)
 
86
        if factory is not None and not ALLOW_DUPLICATES:
70
87
            raise ValueError("an adapter (%s) was already registered." % (factory, ))
71
88
    for interfaceClass in interfaceClasses:
72
89
        self.register([origInterface], interfaceClass, '', adapterFactory)
82
99
    if not isinstance(fromInterface, interface.InterfaceClass):
83
100
        fromInterface = declarations.implementedBy(fromInterface)
84
101
    factory = self.lookup1(fromInterface, toInterface)
85
 
    if factory == None:
 
102
    if factory is None:
86
103
        factory = default
87
104
    return factory
88
105
 
96
113
        return factory(ob)
97
114
interface.adapter_hooks.append(_hook)
98
115
 
 
116
## backwardsCompatImplements and fixClassImplements should probably stick around for another
 
117
## release cycle. No harm doing so in any case.
99
118
 
100
119
def backwardsCompatImplements(klass):
101
120
    """DEPRECATED.
115
134
    warnings.warn("components.fixClassImplements doesn't do anything in Twisted 2.3, stop calling it.", ComponentsDeprecationWarning, stacklevel=2)
116
135
 
117
136
 
118
 
def getAdapterClass(klass, interfaceClass, default):
119
 
    """DEPRECATEED.
120
 
    
121
 
    Use getAdapterFactory instead.
122
 
    """
123
 
    warnings.warn("components.getAdapterClass is deprecated in Twisted 2.3. Use components.getAdapterFactory instead.", ComponentsDeprecationWarning, stacklevel=2)    
124
 
    return getAdapterFactory(klass, interfaceClass, default)
125
 
 
126
 
def getAdapterClassWithInheritance(klass, interfaceClass, default):
127
 
    """DEPRECATEED.
128
 
    
129
 
    Use getAdapterFactory instead.
130
 
    """
131
 
    warnings.warn("components.getAdapterClassWithInheritance is deprecated in Twisted 2.3. Use components.getAdapterFactory instead.", ComponentsDeprecationWarning, stacklevel=2)    
132
 
    return getAdapterFactory(klass, interfaceClass, default)
133
 
 
134
 
 
135
 
def getRegistry(r=None):
 
137
def getRegistry():
136
138
    """Returns the Twisted global
137
139
    C{zope.interface.adapter.AdapterRegistry} instance.
138
140
    """
139
 
    if r is not None:
140
 
        warnings.warn("components.getRegistry's argument is deprecated in Twisted 2.3 and has been ignored since 2.0.", ComponentsDeprecationWarning, stacklevel=2)
141
141
    return globalRegistry
142
142
 
143
143
# FIXME: deprecate attribute somehow?
144
144
CannotAdapt = TypeError
145
145
 
146
 
 
147
 
class _Nothing:
148
 
    """Default value for functions which raise if default not passed.
149
 
    """
150
 
 
151
 
class MetaInterface(interface.InterfaceClass):
152
 
    def __init__(self, name, bases=(), attrs=None, __doc__=None,
153
 
                 __module__=None):
154
 
        if attrs is not None:
155
 
            if __module__ == None and attrs.has_key('__module__'):
156
 
                __module__ = attrs['__module__']
157
 
                del attrs['__module__']
158
 
            if __doc__ == None and attrs.has_key('__doc__'):
159
 
                __doc__ = attrs['__doc__']
160
 
                del attrs['__doc__']
161
 
 
162
 
            for k, v in attrs.items():
163
 
                if isinstance(v, types.FunctionType):
164
 
                    # Look here: the following line is the only useful thing
165
 
                    # this function is actually doing. z.i interfaces don't
166
 
                    # specify self as the first argument, but t.p.c interfaces
167
 
                    # do, so we need to use the imlevel=1 argument.
168
 
                    attrs[k] = interface.fromFunction(v, name, name=k, imlevel=1)
169
 
                elif not isinstance(v, interface.Attribute):
170
 
                    raise interface.InvalidInterface("Concrete attribute, %s" % k)
171
 
 
172
 
        # BEHOLD A GREAT EVIL SHALL COME UPON THEE
173
 
        if __module__ == None:
174
 
            __module__ = sys._getframe(1).f_globals['__name__']
175
 
            
176
 
        if not __module__.startswith("twisted."):
177
 
            # Don't warn for use within twisted, because twisted classes must
178
 
            # not be switched to z.i.Interface yet, b/c we forgot to deprecate
179
 
            # the "default" kwarg to __call__. Also when t.p.c.Interface is
180
 
            # removed, the rest of twisted can be updated simultaneously. But
181
 
            # everyone else should just use z.i.Interface directly now.
182
 
            warnings.warn("twisted.python.components.Interface is deprecated in Twisted 2.3. Use zope.interface.Interface instead. (also note that you should not use 'self' as the first arg on function decls in z.i.Interfaces).", ComponentsDeprecationWarning, stacklevel=2)
183
 
 
184
 
        return interface.InterfaceClass.__init__(self, name, bases, attrs, __doc__, __module__)
185
 
 
186
 
    def __call__(self, adaptable, alternate=_Nothing, default=_Nothing):
187
 
        if default is not _Nothing:
188
 
            warnings.warn("The 'default=' keyword to Interface.__call__ is deprecated in Twisted 2.3. Use a 2nd positional argument instead.", ComponentsDeprecationWarning, stacklevel=2)
189
 
 
190
 
            if alternate is not _Nothing:
191
 
                raise RuntimeError("Cannot specify both default and alternate to Interface.__call__.")
192
 
            alternate = default
193
 
        
194
 
        if alternate is _Nothing:
195
 
            return interface.InterfaceClass.__call__(self, adaptable)
196
 
        else:
197
 
            return interface.InterfaceClass.__call__(self, adaptable, alternate)
198
 
 
199
 
 
200
 
Interface = MetaInterface("Interface", __module__="twisted.python.components")
201
 
 
202
 
 
203
146
class Adapter:
204
147
    """I am the default implementation of an Adapter for some interface.
205
148
 
314
257
 
315
258
        @return: a list of the interfaces that were removed.
316
259
        """
317
 
        if (isinstance(component, types.ClassType) or
318
 
            isinstance(component, types.TypeType)):
319
 
            warnings.warn("passing interface to removeComponent, you probably want unsetComponent", DeprecationWarning, 1)
320
 
            self.unsetComponent(component)
321
 
            return [component]
322
260
        l = []
323
261
        for k, v in self._adapterCache.items():
324
262
            if v is component:
347
285
            return self._adapterCache[k]
348
286
        else:
349
287
            adapter = interface.__adapt__(self)
350
 
            if adapter is not None and adapter is not _Nothing and not (
 
288
            if adapter is not None and not (
351
289
                hasattr(adapter, "temporaryAdapter") and
352
290
                adapter.temporaryAdapter):
353
291
                self._adapterCache[k] = adapter
354
292
                if (hasattr(adapter, "multiComponent") and
355
293
                    adapter.multiComponent):
356
294
                    self.addComponent(adapter)
 
295
            if adapter is None:
 
296
                return default
357
297
            return adapter
358
298
 
 
299
 
359
300
    def __conform__(self, interface):
360
301
        return self.getComponent(interface)
361
302
 
376
317
    "ComponentsDeprecationWarning", 
377
318
    "registerAdapter", "getAdapterFactory",
378
319
    "Adapter", "Componentized", "ReprableComponentized", "getRegistry",
379
 
 
 
320
    
380
321
    # Deprecated:
381
 
    "Interface", "getAdapterClass", "backwardsCompatImplements",
 
322
    "backwardsCompatImplements",
382
323
    "fixClassImplements",
383
324
]