[Zope-Checkins] CVS: Zope3/lib/python/Zope/App/Traversing - __init__.py:1.1.2.2
Steve Alexander
steve@cat-box.net
Wed, 20 Mar 2002 16:05:29 -0500
Update of /cvs-repository/Zope3/lib/python/Zope/App/Traversing
In directory cvs.zope.org:/tmp/cvs-serv12579
Modified Files:
Tag: Zope-3x-branch
__init__.py
Log Message:
Added a ZopeWrapper function that is responsible for wrapping
objects except None + primitive types in a ContextWrapper.Wrapper.
Also, hack __builtins__.isinstance to look at obj.__class__ for
types and new-style classes. This hack to remain until Python
impements this feature.
=== Zope3/lib/python/Zope/App/Traversing/__init__.py 1.1.2.1 => 1.1.2.2 ===
"""
+from Zope.ContextWrapper import Wrapper
+def ZopeWrapper(obj, context):
+ if obj is None or isinstance(obj,
+ (int, long, float, complex, unicode, str)):
+ return obj
+ return Wrapper(obj, context)
+
+del Wrapper
+
+
+# hack isinstance in __builtins__ to respect __class__ of new-style
+# classes and of types.
+# this hack to remain until this feature is present in Python 2.2
+#
+# do this lazily by only trying comparison on __class__ if standard
+# isinstance returns 0
+def isinstance(obj, class_or_type_or_tuple, isinstance=isinstance):
+ result = isinstance(obj, class_or_type_or_tuple)
+ if result:
+ return 1
+
+ # otherwise compare on __class__
+ cls = getattr(obj, '__class__', None)
+ if cls is None:
+ return 0
+
+ # talks advantage of cls in nested scope
+ def flatten(arg):
+ if isinstance(arg, tuple):
+ for t in arg:
+ if flatten(t):
+ return 1
+ return 0
+ else:
+ return issubclass(cls, arg)
+
+ return flatten(class_or_type_or_tuple)
+
+__builtins__.isinstance = isinstance
+del isinstance
+
+# borrow the Python tests, and add some to test our new behaviour
+
+from test.test_support import TestFailed
+
+class C:
+ pass
+class D(C):
+ pass
+class E:
+ pass
+c = C()
+d = D()
+e = E()
+if not isinstance(c, C): raise TestFailed, 'isinstance(c, C)'
+if not isinstance(d, C): raise TestFailed, 'isinstance(d, C)'
+if isinstance(e, C): raise TestFailed, 'isinstance(e, C)'
+if isinstance(c, D): raise TestFailed, 'isinstance(c, D)'
+if isinstance('foo', E): raise TestFailed, 'isinstance("Foo", E)'
+try:
+ isinstance(E, 'foo')
+ raise TestFailed, 'isinstance(E, "foo")'
+except TypeError:
+ pass
+
+from Zope.ContextWrapper import Wrapper
+class C:
+ pass
+class D(C):
+ pass
+class E:
+ pass
+c = Wrapper(C())
+d = Wrapper(D())
+e = Wrapper(E())
+if not isinstance(c, (C, int, int, (int, int, (int,)))):
+ raise TestFailed, 'isinstance(c, C)'
+if not isinstance(d, C): raise TestFailed, 'isinstance(d, C)'
+if isinstance(e, C): raise TestFailed, 'isinstance(e, C)'
+if isinstance(c, D): raise TestFailed, 'isinstance(c, D)'
+if isinstance('foo', E): raise TestFailed, 'isinstance("Foo", E)'
+try:
+ isinstance(E, 'foo')
+ raise TestFailed, 'isinstance(E, "foo")'
+except TypeError:
+ pass
+
+del TestFailed