This file is indexed.

/usr/share/pyshared/zope/container/contained.py is in python-zope.container 3.12.0-0ubuntu2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.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.
#
##############################################################################
"""Classes to support implementing `IContained`
"""
__docformat__ = 'restructuredtext'

import zope.component
import zope.interface.declarations
from zope.interface import providedBy
from zope.interface.declarations import getObjectSpecification
from zope.interface.declarations import ObjectSpecification
from zope.event import notify
from zope.location.interfaces import ILocation, ISublocations
from zope.security.checker import selectChecker, CombinedChecker
from zope.lifecycleevent import ObjectModifiedEvent

from zope.container.i18n import ZopeMessageFactory as _
from zope.location.interfaces import IContained
from zope.container.interfaces import INameChooser
from zope.container.interfaces import IReservedNames, NameReserved
from zope.container.interfaces import IContainerModifiedEvent
from zope.container._zope_container_contained import ContainedProxyBase
from zope.container._zope_container_contained import getProxiedObject

from zope.lifecycleevent import ObjectMovedEvent
from zope.lifecycleevent import ObjectAddedEvent
from zope.lifecycleevent import ObjectRemovedEvent

# BBB ZODB3 < 3.10
try:
    from ZODB.interfaces import IBroken
except ImportError:
    from zope.broken.interfaces import IBroken


class Contained(object):
    """Stupid mix-in that defines `__parent__` and `__name__` attributes"""

    zope.interface.implements(IContained)

    __parent__ = __name__ = None

class ContainerModifiedEvent(ObjectModifiedEvent):
    """The container has been modified."""

    zope.interface.implements(IContainerModifiedEvent)


def dispatchToSublocations(object, event):
    """Dispatch an event to sublocations of a given object

       When a move event happens for an object, it's important to notify
       subobjects as well.

       We do this based on locations.

       Suppose, for example, that we define some location objects.

         >>> class L(object):
         ...     zope.interface.implements(ILocation)
         ...     def __init__(self, name):
         ...         self.__name__ = name
         ...         self.__parent__ = None
         ...     def __repr__(self):
         ...         return '%s(%s)' % (
         ...                 self.__class__.__name__, str(self.__name__))

         >>> class C(L):
         ...     zope.interface.implements(ISublocations)
         ...     def __init__(self, name, *subs):
         ...         L.__init__(self, name)
         ...         self.subs = subs
         ...         for sub in subs:
         ...             sub.__parent__ = self
         ...     def sublocations(self):
         ...         return self.subs

         >>> c = C(1,
         ...       C(11,
         ...         L(111),
         ...         L(112),
         ...         ),
         ...       C(12,
         ...         L(121),
         ...         L(122),
         ...         L(123),
         ...         L(124),
         ...         ),
         ...       L(13),
         ...       )

       Now, if we call the dispatcher, it should call event handlers
       for all of the objects.

       Lets create an event handler that records the objects it sees:

         >>> seen = []
         >>> def handler(ob, event):
         ...     seen.append((ob, event.object))

       Note that we record the the object the handler is called on as
       well as the event object:

       Now we'll register it:

         >>> from zope import component
         >>> from zope.lifecycleevent.interfaces import IObjectMovedEvent
         >>> component.provideHandler(handler, [None, IObjectMovedEvent])

       We also register our dispatcher:

         >>> component.provideHandler(dispatchToSublocations,
         ...   [None, IObjectMovedEvent])

       We can then call the dispatcher for the root object:

         >>> event = ObjectRemovedEvent(c)
         >>> dispatchToSublocations(c, event)

       Now, we should have seen all of the subobjects:

         >>> seenreprs = map(repr, seen)
         >>> seenreprs.sort()
         >>> seenreprs
         ['(C(11), C(1))', '(C(12), C(1))', '(L(111), C(1))',""" \
          """ '(L(112), C(1))', '(L(121), C(1))', '(L(122), C(1))',""" \
          """ '(L(123), C(1))', '(L(124), C(1))', '(L(13), C(1))']

       We see that we get entries for each of the subobjects and
       that,for each entry, the event object is top object.

       This suggests that location event handlers need to be aware that
       the objects they are called on and the event objects could be
       different.

       """
    subs = ISublocations(object, None)
    if subs is not None:
        for sub in subs.sublocations():
            for ignored in zope.component.subscribers((sub, event), None):
                pass # They do work in the adapter fetch

class ContainerSublocations(object):
    """Get the sublocations for a container

       Obviously, this is the container values:

         >>> class MyContainer(object):
         ...     def __init__(self, **data):
         ...         self.data = data
         ...     def __iter__(self):
         ...         return iter(self.data)
         ...     def __getitem__(self, key):
         ...         return self.data[key]

         >>> container = MyContainer(x=1, y=2, z=42)
         >>> adapter = ContainerSublocations(container)
         >>> sublocations = list(adapter.sublocations())
         >>> sublocations.sort()
         >>> sublocations
         [1, 2, 42]

       """

    def __init__(self, container):
        self.container = container

    def sublocations(self):
        container = self.container
        for key in container:
            yield container[key]


def containedEvent(object, container, name=None):
    """Establish the containment of the object in the container

    The object and necessary event are returned. The object may be a
    `ContainedProxy` around the original object. The event is an added
    event, a moved event, or None.

    If the object implements `IContained`, simply set its `__parent__`
    and `__name__` attributes:

        >>> container = {}
        >>> item = Contained()
        >>> x, event = containedEvent(item, container, u'foo')
        >>> x is item
        True
        >>> item.__parent__ is container
        True
        >>> item.__name__
        u'foo'

    We have an added event:

        >>> event.__class__.__name__
        'ObjectAddedEvent'
        >>> event.object is item
        True
        >>> event.newParent is container
        True
        >>> event.newName
        u'foo'
        >>> event.oldParent
        >>> event.oldName

    Now if we call contained again:

        >>> x2, event = containedEvent(item, container, u'foo')
        >>> x2 is item
        True
        >>> item.__parent__ is container
        True
        >>> item.__name__
        u'foo'

    We don't get a new added event:

        >>> event

    If the object already had a parent but the parent or name was
    different, we get a moved event:

        >>> x, event = containedEvent(item, container, u'foo2')
        >>> event.__class__.__name__
        'ObjectMovedEvent'
        >>> event.object is item
        True
        >>> event.newParent is container
        True
        >>> event.newName
        u'foo2'
        >>> event.oldParent is container
        True
        >>> event.oldName
        u'foo'

    If the `object` implements `ILocation`, but not `IContained`, set its
    `__parent__` and `__name__` attributes *and* declare that it
    implements `IContained`:

        >>> from zope.location import Location
        >>> item = Location()
        >>> IContained.providedBy(item)
        False
        >>> x, event = containedEvent(item, container, 'foo')
        >>> x is item
        True
        >>> item.__parent__ is container
        True
        >>> item.__name__
        'foo'
        >>> IContained.providedBy(item)
        True


    If the `object` doesn't even implement `ILocation`, put a
    `ContainedProxy` around it:

        >>> item = []
        >>> x, event = containedEvent(item, container, 'foo')
        >>> x is item
        False
        >>> x.__parent__ is container
        True
        >>> x.__name__
        'foo'

    Make sure we don't lose existing directly provided interfaces.

        >>> from zope.interface import Interface, directlyProvides
        >>> class IOther(Interface):
        ...     pass
        >>> from zope.location import Location
        >>> item = Location()
        >>> directlyProvides(item, IOther)
        >>> IOther.providedBy(item)
        True
        >>> x, event = containedEvent(item, container, 'foo')
        >>> IOther.providedBy(item)
        True
    """

    if not IContained.providedBy(object):
        if ILocation.providedBy(object):
            zope.interface.alsoProvides(object, IContained)
        else:
            object = ContainedProxy(object)

    oldparent = object.__parent__
    oldname = object.__name__

    if oldparent is container and oldname == name:
        # No events
        return object, None

    object.__parent__ = container
    object.__name__ = name

    if oldparent is None or oldname is None:
        event = ObjectAddedEvent(object, container, name)
    else:
        event = ObjectMovedEvent(object, oldparent, oldname, container, name)

    return object, event

def contained(object, container, name=None):
    """Establish the containment of the object in the container

    Just return the contained object without an event. This is a convenience
    "macro" for:

       ``containedEvent(object, container, name)[0]``

    This function is only used for tests.
    """
    return containedEvent(object, container, name)[0]

def notifyContainerModified(object, *descriptions):
    """Notify that the container was modified."""
    notify(ContainerModifiedEvent(object, *descriptions))

def setitem(container, setitemf, name, object):
    """Helper function to set an item and generate needed events

    This helper is needed, in part, because the events need to get
    published after the `object` has been added to the `container`.

    If the item implements `IContained`, simply set its `__parent__`
    and `__name__` attributes:

    >>> class IItem(zope.interface.Interface):
    ...     pass
    >>> class Item(Contained):
    ...     zope.interface.implements(IItem)
    ...     def setAdded(self, event):
    ...         self.added = event
    ...     def setMoved(self, event):
    ...         self.moved = event

    >>> from zope.lifecycleevent.interfaces import IObjectAddedEvent
    >>> from zope.lifecycleevent.interfaces import IObjectMovedEvent

    >>> from zope import component
    >>> component.provideHandler(lambda obj, event: obj.setAdded(event),
    ...   [IItem, IObjectAddedEvent])
    >>> component.provideHandler(lambda obj, event: obj.setMoved(event),
    ...   [IItem, IObjectMovedEvent])

    >>> item = Item()

    >>> container = {}
    >>> setitem(container, container.__setitem__, u'c', item)
    >>> container[u'c'] is item
    1
    >>> item.__parent__ is container
    1
    >>> item.__name__
    u'c'

    If we run this using the testing framework, we'll use `getEvents` to
    track the events generated:

    >>> from zope.component.eventtesting import getEvents
    >>> from zope.lifecycleevent.interfaces import IObjectModifiedEvent

    We have an added event:

    >>> len(getEvents(IObjectAddedEvent))
    1
    >>> event = getEvents(IObjectAddedEvent)[-1]
    >>> event.object is item
    1
    >>> event.newParent is container
    1
    >>> event.newName
    u'c'
    >>> event.oldParent
    >>> event.oldName

    As well as a modification event for the container:

    >>> len(getEvents(IObjectModifiedEvent))
    1
    >>> getEvents(IObjectModifiedEvent)[-1].object is container
    1

    The item's hooks have been called:

    >>> item.added is event
    1
    >>> item.moved is event
    1

    We can suppress events and hooks by setting the `__parent__` and
    `__name__` first:

    >>> item = Item()
    >>> item.__parent__, item.__name__ = container, 'c2'
    >>> setitem(container, container.__setitem__, u'c2', item)
    >>> len(container)
    2
    >>> len(getEvents(IObjectAddedEvent))
    1
    >>> len(getEvents(IObjectModifiedEvent))
    1

    >>> getattr(item, 'added', None)
    >>> getattr(item, 'moved', None)

    If the item had a parent or name (as in a move or rename),
    we generate a move event, rather than an add event:

    >>> setitem(container, container.__setitem__, u'c3', item)
    >>> len(container)
    3
    >>> len(getEvents(IObjectAddedEvent))
    1
    >>> len(getEvents(IObjectModifiedEvent))
    2
    >>> len(getEvents(IObjectMovedEvent))
    2

    (Note that we have 2 move events because add are move events.)

    We also get the move hook called, but not the add hook:

    >>> event = getEvents(IObjectMovedEvent)[-1]
    >>> getattr(item, 'added', None)
    >>> item.moved is event
    1

    If we try to replace an item without deleting it first, we'll get
    an error:

    >>> setitem(container, container.__setitem__, u'c', [])
    Traceback (most recent call last):
    ...
    KeyError: u'c'


    >>> del container[u'c']
    >>> setitem(container, container.__setitem__, u'c', [])
    >>> len(getEvents(IObjectAddedEvent))
    2
    >>> len(getEvents(IObjectModifiedEvent))
    3


    If the object implements `ILocation`, but not `IContained`, set it's
    `__parent__` and `__name__` attributes *and* declare that it
    implements `IContained`:

    >>> from zope.location import Location
    >>> item = Location()
    >>> IContained.providedBy(item)
    0
    >>> setitem(container, container.__setitem__, u'l', item)
    >>> container[u'l'] is item
    1
    >>> item.__parent__ is container
    1
    >>> item.__name__
    u'l'
    >>> IContained.providedBy(item)
    1

    We get new added and modification events:

    >>> len(getEvents(IObjectAddedEvent))
    3
    >>> len(getEvents(IObjectModifiedEvent))
    4

    If the object doesn't even implement `ILocation`, put a
    `ContainedProxy` around it:

    >>> item = []
    >>> setitem(container, container.__setitem__, u'i', item)
    >>> container[u'i']
    []
    >>> container[u'i'] is item
    0
    >>> item = container[u'i']
    >>> item.__parent__ is container
    1
    >>> item.__name__
    u'i'
    >>> IContained.providedBy(item)
    1

    >>> len(getEvents(IObjectAddedEvent))
    4
    >>> len(getEvents(IObjectModifiedEvent))
    5

    We'll get type errors if we give keys that aren't unicode or ascii keys:

    >>> setitem(container, container.__setitem__, 42, item)
    Traceback (most recent call last):
    ...
    TypeError: name not unicode or ascii string

    >>> setitem(container, container.__setitem__, None, item)
    Traceback (most recent call last):
    ...
    TypeError: name not unicode or ascii string

    >>> setitem(container, container.__setitem__, 'hello ' + chr(200), item)
    Traceback (most recent call last):
    ...
    TypeError: name not unicode or ascii string

    and we'll get a value error of we give an empty string or unicode:

    >>> setitem(container, container.__setitem__, '', item)
    Traceback (most recent call last):
    ...
    ValueError: empty names are not allowed

    >>> setitem(container, container.__setitem__, u'', item)
    Traceback (most recent call last):
    ...
    ValueError: empty names are not allowed

    """
    # Do basic name check:
    if isinstance(name, str):
        try:
            name = unicode(name)
        except UnicodeError:
            raise TypeError("name not unicode or ascii string")
    elif not isinstance(name, unicode):
        raise TypeError("name not unicode or ascii string")

    if not name:
        raise ValueError("empty names are not allowed")

    old = container.get(name)
    if old is object:
        return
    if old is not None:
        raise KeyError(name)

    object, event = containedEvent(object, container, name)
    setitemf(name, object)
    if event:
        notify(event)
        notifyContainerModified(container)

fixing_up = False
def uncontained(object, container, name=None):
    """Clear the containment relationship between the `object` and
    the `container`.

    If we run this using the testing framework, we'll use `getEvents` to
    track the events generated:

    >>> from zope.component.eventtesting import getEvents
    >>> from zope.lifecycleevent.interfaces import IObjectModifiedEvent
    >>> from zope.lifecycleevent.interfaces import IObjectRemovedEvent

    We'll start by creating a container with an item:

    >>> class Item(Contained):
    ...     pass

    >>> item = Item()
    >>> container = {u'foo': item}
    >>> x, event = containedEvent(item, container, u'foo')
    >>> item.__parent__ is container
    1
    >>> item.__name__
    u'foo'

    Now we'll remove the item. It's parent and name are cleared:

    >>> uncontained(item, container, u'foo')
    >>> item.__parent__
    >>> item.__name__

    We now have a new removed event:

    >>> len(getEvents(IObjectRemovedEvent))
    1
    >>> event = getEvents(IObjectRemovedEvent)[-1]
    >>> event.object is item
    1
    >>> event.oldParent is container
    1
    >>> event.oldName
    u'foo'
    >>> event.newParent
    >>> event.newName

    As well as a modification event for the container:

    >>> len(getEvents(IObjectModifiedEvent))
    1
    >>> getEvents(IObjectModifiedEvent)[-1].object is container
    1

    Now if we call uncontained again:

    >>> uncontained(item, container, u'foo')

    We won't get any new events, because __parent__ and __name__ are None:

    >>> len(getEvents(IObjectRemovedEvent))
    1
    >>> len(getEvents(IObjectModifiedEvent))
    1

    But, if either the name or parent are not ``None`` and they are not the
    container and the old name, we'll get a modified event but not a removed
    event.

    >>> item.__parent__, item.__name__ = container, None
    >>> uncontained(item, container, u'foo')
    >>> len(getEvents(IObjectRemovedEvent))
    1
    >>> len(getEvents(IObjectModifiedEvent))
    2

    >>> item.__parent__, item.__name__ = None, u'bar'
    >>> uncontained(item, container, u'foo')
    >>> len(getEvents(IObjectRemovedEvent))
    1
    >>> len(getEvents(IObjectModifiedEvent))
    3

    """
    try:
        oldparent = object.__parent__
        oldname = object.__name__
    except AttributeError:
        # The old object doesn't implements IContained
        # Maybe we're converting old data:
        if not fixing_up:
            raise
        oldparent = None
        oldname = None

    if oldparent is not container or oldname != name:
        if oldparent is not None or oldname is not None:
            notifyContainerModified(container)
        return

    event = ObjectRemovedEvent(object, oldparent, oldname)
    notify(event)

    if not IBroken.providedBy(object):
        object.__parent__ = None
        object.__name__ = None
    notifyContainerModified(container)

class NameChooser(object):

    zope.interface.implements(INameChooser)

    def __init__(self, context):
        self.context = context

    def checkName(self, name, object):
        """See zope.container.interfaces.INameChooser

        We create and populate a dummy container

        >>> from zope.container.sample import SampleContainer
        >>> container = SampleContainer()
        >>> container['foo'] = 'bar'
        >>> from zope.container.contained import NameChooser

        An invalid name raises a ValueError:

        >>> NameChooser(container).checkName('+foo', object())
        Traceback (most recent call last):
        ...
        ValueError: Names cannot begin with '+' or '@' or contain '/'

        A name that already exists raises a KeyError:

        >>> NameChooser(container).checkName('foo', object())
        Traceback (most recent call last):
        ...
        KeyError: u'The given name is already being used'

        A name must be a string or unicode string:

        >>> NameChooser(container).checkName(2, object())
        Traceback (most recent call last):
        ...
        TypeError: ('Invalid name type', <type 'int'>)

        A correct name returns True:

        >>> NameChooser(container).checkName('2', object())
        True

        We can reserve some names by providing a IReservedNames adapter
        to a container:

        >>> from zope.container.interfaces import IContainer
        >>> class ReservedNames(object):
        ...     zope.component.adapts(IContainer)
        ...     zope.interface.implements(IReservedNames)
        ...
        ...     def __init__(self, context):
        ...         self.reservedNames = set(('reserved', 'other'))

        >>> zope.component.getSiteManager().registerAdapter(ReservedNames)

        >>> NameChooser(container).checkName('reserved', None)
        Traceback (most recent call last):
        ...
        NameReserved: reserved
        """

        if isinstance(name, str):
            name = unicode(name)
        elif not isinstance(name, unicode):
            raise TypeError("Invalid name type", type(name))

        if not name:
            raise ValueError(
                _("An empty name was provided. Names cannot be empty.")
                )

        if name[:1] in '+@' or '/' in name:
            raise ValueError(
                _("Names cannot begin with '+' or '@' or contain '/'")
                )

        reserved = IReservedNames(self.context, None)
        if reserved is not None:
            if name in reserved.reservedNames:
                raise NameReserved(name)

        if name in self.context:
            raise KeyError(
                _("The given name is already being used")
                )

        return True


    def chooseName(self, name, object):
        """See zope.container.interfaces.INameChooser

        The name chooser is expected to choose a name without error

        We create and populate a dummy container

        >>> from zope.container.sample import SampleContainer
        >>> container = SampleContainer()
        >>> container['foobar.old'] = 'rst doc'

        >>> from zope.container.contained import NameChooser

        the suggested name is converted to unicode:

        >>> NameChooser(container).chooseName('foobar', object())
        u'foobar'

        If it already exists, a number is appended but keeps the same extension:

        >>> NameChooser(container).chooseName('foobar.old', object())
        u'foobar-2.old'

        Bad characters are turned into dashes:

        >>> NameChooser(container).chooseName('foo/foo', object())
        u'foo-foo'

        If no name is suggested, it is based on the object type:

        >>> NameChooser(container).chooseName('', [])
        u'list'

        """

        container = self.context

        # convert to unicode and remove characters that checkName does not allow
        try:
            name = unicode(name)
        except:
            name = u''
        name = name.replace('/', '-').lstrip('+@')

        if not name:
            name = unicode(object.__class__.__name__)

        # for an existing name, append a number.
        # We should keep client's os.path.extsep (not ours), we assume it's '.'
        dot = name.rfind('.')
        if dot >= 0:
            suffix = name[dot:]
            name = name[:dot]
        else:
            suffix = ''

        n = name + suffix
        i = 1
        while n in container:
            i += 1
            n = name + u'-' + unicode(i) + suffix

        # Make sure the name is valid.  We may have started with something bad.
        self.checkName(n, object)

        return n


class DecoratorSpecificationDescriptor(
    zope.interface.declarations.ObjectSpecificationDescriptor):
    """Support for interface declarations on decorators

    >>> from zope.interface import *
    >>> class I1(Interface):
    ...     pass
    >>> class I2(Interface):
    ...     pass
    >>> class I3(Interface):
    ...     pass
    >>> class I4(Interface):
    ...     pass

    >>> class D1(ContainedProxy):
    ...   implements(I1)


    >>> class D2(ContainedProxy):
    ...   implements(I2)

    >>> class X:
    ...   implements(I3)

    >>> x = X()
    >>> directlyProvides(x, I4)

    Interfaces of X are ordered with the directly-provided interfaces first

    >>> [interface.getName() for interface in list(providedBy(x))]
    ['I4', 'I3']

    When we decorate objects, what order should the interfaces come in? One
    could argue that decorators are less specific, so they should come last.

    >>> [interface.getName() for interface in list(providedBy(D1(x)))]
    ['I4', 'I3', 'I1', 'IContained', 'IPersistent']

    >>> [interface.getName() for interface in list(providedBy(D2(D1(x))))]
    ['I4', 'I3', 'I1', 'IContained', 'IPersistent', 'I2']
    """
    def __get__(self, inst, cls=None):
        if inst is None:
            return getObjectSpecification(cls)
        else:
            provided = providedBy(getProxiedObject(inst))

            # Use type rather than __class__ because inst is a proxy and
            # will return the proxied object's class.
            cls = type(inst)
            return ObjectSpecification(provided, cls)


class DecoratedSecurityCheckerDescriptor(object):
    """Descriptor for a Decorator that provides a decorated security checker.
    """
    def __get__(self, inst, cls=None):
        if inst is None:
            return self
        else:
            proxied_object = getProxiedObject(inst)
            checker = getattr(proxied_object, '__Security_checker__', None)
            if checker is None:
                checker = selectChecker(proxied_object)
            wrapper_checker = selectChecker(inst)
            if wrapper_checker is None:
                return checker
            elif checker is None:
                return wrapper_checker
            else:
                return CombinedChecker(wrapper_checker, checker)

class ContainedProxyClassProvides(zope.interface.declarations.ClassProvides):

    def __set__(self, inst, value):
        inst = getProxiedObject(inst)
        inst.__provides__ = value

    def __delete__(self, inst):
        inst = getProxiedObject(inst)
        del inst.__provides__

class ContainedProxy(ContainedProxyBase):

    # Prevent proxies from having their own instance dictionaries:
    __slots__ = ()

    __safe_for_unpickling__ = True

    zope.interface.implements(IContained)

    __providedBy__ = DecoratorSpecificationDescriptor()

    __Security_checker__ = DecoratedSecurityCheckerDescriptor()

ContainedProxy.__provides__ = ContainedProxyClassProvides(ContainedProxy, type)