[Zope3-checkins] SVN: Zope3/trunk/src/zope/interface/ merging
changes from branch tlotze: minor cleanups and optimizations
Thomas Lotze
tl at gocept.com
Mon Oct 31 08:57:36 EST 2005
Log message for revision 39768:
merging changes from branch tlotze: minor cleanups and optimizations
Changed:
U Zope3/trunk/src/zope/interface/document.py
U Zope3/trunk/src/zope/interface/interface.py
U Zope3/trunk/src/zope/interface/tests/test_advice.py
U Zope3/trunk/src/zope/interface/tests/test_element.py
-=-
Modified: Zope3/trunk/src/zope/interface/document.py
===================================================================
--- Zope3/trunk/src/zope/interface/document.py 2005-10-31 13:19:51 UTC (rev 39767)
+++ Zope3/trunk/src/zope/interface/document.py 2005-10-31 13:57:35 UTC (rev 39768)
@@ -18,104 +18,90 @@
$Id$
"""
-from string import maketrans
import zope.interface
def asStructuredText(I, munge=0):
- """ Output structured text format. Note, this will wack any existing
+ """ Output structured text format. Note, this will whack any existing
'structured' format of the text. """
-
- r = ["%s\n\n" % I.getName()]
+ r = [I.getName()]
outp = r.append
level = 1
if I.getDoc():
- outp(_justify_and_indent(_trim_doc_string(I.getDoc()), level)+ "\n\n")
+ outp(_justify_and_indent(_trim_doc_string(I.getDoc()), level))
bases = [base
for base in I.__bases__
if base is not zope.interface.Interface
]
if bases:
- outp((" " * level) + "This interface extends:\n\n")
- level = level + 1
+ outp(_justify_and_indent("This interface extends:", level, munge))
+ level += 1
for b in bases:
item = "o %s" % b.getName()
- outp(_justify_and_indent(_trim_doc_string(item), level, munge)
- + "\n\n")
+ outp(_justify_and_indent(_trim_doc_string(item), level, munge))
+ level -= 1
- level = level - 1
-
- outp(_justify_and_indent("Attributes:", level, munge)+'\n\n')
- level = level + 1
-
namesAndDescriptions = I.namesAndDescriptions()
namesAndDescriptions.sort()
+ outp(_justify_and_indent("Attributes:", level, munge))
+ level += 1
for name, desc in namesAndDescriptions:
if not hasattr(desc, 'getSignatureString'): # ugh...
item = "%s -- %s" % (desc.getName(),
desc.getDoc() or 'no documentation')
- outp(_justify_and_indent(_trim_doc_string(item), level, munge)
- + "\n\n")
- level = level - 1
+ outp(_justify_and_indent(_trim_doc_string(item), level, munge))
+ level -= 1
- outp(_justify_and_indent("Methods:", level, munge)+'\n\n')
- level = level + 1
+ outp(_justify_and_indent("Methods:", level, munge))
+ level += 1
for name, desc in namesAndDescriptions:
if hasattr(desc, 'getSignatureString'): # ugh...
item = "%s%s -- %s" % (desc.getName(),
desc.getSignatureString(),
desc.getDoc() or 'no documentation')
- outp(_justify_and_indent(_trim_doc_string(item), level, munge)
- + "\n\n")
+ outp(_justify_and_indent(_trim_doc_string(item), level, munge))
- return "".join(r)
+ return "\n\n".join(r) + "\n\n"
+
def _trim_doc_string(text):
- """
- Trims a doc string to make it format
- correctly with structured text.
- """
- text = text.strip().replace('\r\n', '\n')
- lines = text.split('\n')
- nlines = [lines[0]]
- if len(lines) > 1:
- min_indent=None
- for line in lines[1:]:
- indent=len(line) - len(line.lstrip())
- if indent < min_indent or min_indent is None:
- min_indent=indent
- for line in lines[1:]:
+ """ Trims a doc string to make it format
+ correctly with structured text. """
+
+ lines = text.replace('\r\n', '\n').split('\n')
+ nlines = [lines.pop(0)]
+ if lines:
+ min_indent = min([len(line) - len(line.lstrip())
+ for line in lines])
+ for line in lines:
nlines.append(line[min_indent:])
+
return '\n'.join(nlines)
-_trans = maketrans("\r\n", " ")
def _justify_and_indent(text, level, munge=0, width=72):
""" indent and justify text, rejustify (munge) if specified """
- lines = []
+ indent = " " * level
if munge:
- line = " " * level
- text = text.translate(text, _trans).strip().split()
+ lines = []
+ line = indent
+ text = text.split()
for word in text:
line = ' '.join([line, word])
if len(line) > width:
lines.append(line)
- line = " " * level
+ line = indent
else:
lines.append(line)
- return "\n".join(lines)
+ return '\n'.join(lines)
else:
- text = text.replace("\r\n", "\n").split("\n")
-
- for line in text:
- lines.append((" " * level) + line)
-
- return '\n'.join(lines)
+ return indent + \
+ text.strip().replace("\r\n", "\n") .replace("\n", "\n" + indent)
Modified: Zope3/trunk/src/zope/interface/interface.py
===================================================================
--- Zope3/trunk/src/zope/interface/interface.py 2005-10-31 13:19:51 UTC (rev 39767)
+++ Zope3/trunk/src/zope/interface/interface.py 2005-10-31 13:57:35 UTC (rev 39768)
@@ -33,12 +33,8 @@
def invariant(call):
f_locals = sys._getframe(1).f_locals
- tags = f_locals.get(TAGGED_DATA)
- if tags is None:
- tags = f_locals[TAGGED_DATA] = {}
- invariants = tags.get('invariants')
- if invariants is None:
- invariants = tags['invariants'] = []
+ tags = f_locals.setdefault(TAGGED_DATA, {})
+ invariants = tags.setdefault('invariants', [])
invariants.append(call)
return _decorator_non_return
@@ -357,12 +353,8 @@
)
def weakref(self, callback=None):
- if callback is None:
- return weakref.ref(self)
- else:
- return weakref.ref(self, callback)
+ return weakref.ref(self, callback)
-
def get(self, name, default=None):
"""Query for an attribute description
"""
@@ -394,15 +386,14 @@
def __init__(self, name, bases=(), attrs=None, __doc__=None,
__module__=None):
+ if attrs is None:
+ attrs = {}
+
if __module__ is None:
- if (attrs is not None and
- ('__module__' in attrs) and
- isinstance(attrs['__module__'], str)
- ):
- __module__ = attrs['__module__']
+ __module__ = attrs.get('__module__')
+ if isinstance(__module__, str):
del attrs['__module__']
else:
-
try:
# Figure out what module defined the interface.
# This is how cPython figures out the module of
@@ -413,9 +404,6 @@
self.__module__ = __module__
- if attrs is None:
- attrs = {}
-
d = attrs.get('__doc__')
if d is not None:
if not isinstance(d, Attribute):
@@ -428,11 +416,7 @@
Element.__init__(self, name, __doc__)
- if attrs.has_key(TAGGED_DATA):
- tagged_data = attrs[TAGGED_DATA]
- del attrs[TAGGED_DATA]
- else:
- tagged_data = None
+ tagged_data = attrs.pop(TAGGED_DATA, None)
if tagged_data is not None:
for key, val in tagged_data.items():
self.setTaggedValue(key, val)
@@ -455,7 +439,7 @@
elif attr is _decorator_non_return:
del attrs[name]
else:
- raise InvalidInterface("Concrete attribute, %s" %name)
+ raise InvalidInterface("Concrete attribute, " + name)
self.__attrs = attrs
@@ -478,28 +462,23 @@
"""
yield self
-
-
def getBases(self):
return self.__bases__
def isEqualOrExtendedBy(self, other):
"""Same interface or extends?"""
- if self == other:
- return True
- return other.extends(self)
+ return self == other or other.extends(self)
def names(self, all=False):
"""Return the attribute names defined by the interface."""
if not all:
return self.__attrs.keys()
- r = {}
- for name in self.__attrs.keys():
- r[name] = 1
+ r = self.__attrs.copy()
+
for base in self.__bases__:
- for name in base.names(all):
- r[name] = 1
+ r.update(dict.fromkeys(base.names(all)))
+
return r.keys()
def __iter__(self):
@@ -511,13 +490,10 @@
return self.__attrs.items()
r = {}
- for name, d in self.__attrs.items():
- r[name] = d
+ for base in self.__bases__[::-1]:
+ r.update(dict(base.namesAndDescriptions(all)))
- for base in self.__bases__:
- for name, d in base.namesAndDescriptions(all):
- if name not in r:
- r[name] = d
+ r.update(self.__attrs)
return r.items()
@@ -570,7 +546,6 @@
except Invalid:
if errors is None:
raise
- pass
if errors:
raise Invalid(errors)
@@ -584,31 +559,27 @@
if isinstance(v, Method) and not (k in dict):
dict[k]=v
- for b in self.__bases__: b.__d(dict)
+ for b in self.__bases__:
+ b.__d(dict)
def __repr__(self):
- r = getattr(self, '_v_repr', self)
- if r is self:
+ try:
+ return self._v_repr
+ except AttributeError:
name = self.__name__
m = self.__module__
if m:
name = '%s.%s' % (m, name)
r = "<%s %s>" % (self.__class__.__name__, name)
self._v_repr = r
- return r
+ return r
def __call__():
- # TRICK! Create the call method
+ # Mind the closure. It serves to keep a unique marker around to
+ # allow for an optional argument to __call__ without resorting
+ # to a global marker.
#
- # An embedded function is used to allow an optional argument to
- # __call__ without resorting to a global marker.
- #
- # The evility of this trick is a reflection of the underlying
- # evility of "optional" arguments, arguments whose presense or
- # absense changes the behavior of the methods.
- #
- # I think the evil is necessary, and perhaps desireable to
- # provide some consistencey with the PEP 246 adapt method.
+ # This provides some consistency with the PEP 246 adapt method.
marker = object()
@@ -697,17 +668,16 @@
adapter = self.__adapt__(obj)
- if adapter is None:
- if alternate is not marker:
- return alternate
-
+ if adapter is not None:
+ return adapter
+ elif alternate is not marker:
+ return alternate
+ else:
raise TypeError("Could not adapt", obj, self)
- return adapter
-
return __call__
- __call__ = __call__() # TRICK! Make the *real* __call__ method
+ __call__ = __call__() # Make the closure the *real* __call__ method.
def __adapt__(self, obj):
"""Adapt an object to the reciever
@@ -800,7 +770,6 @@
if o2 is None:
return -1
-
n1 = (getattr(o1, '__name__', ''),
getattr(getattr(o1, '__module__', None), '__name__', ''))
n2 = (getattr(o2, '__name__', ''),
@@ -859,25 +828,19 @@
}
def getSignatureString(self):
- sig = "("
+ sig = []
for v in self.positional:
- sig = sig + v
+ sig.append(v)
if v in self.optional.keys():
- sig = sig + "=%s" % `self.optional[v]`
- sig = sig + ", "
+ sig[-1] += "=" + `self.optional[v]`
if self.varargs:
- sig = sig + ("*%s, " % self.varargs)
+ sig.append("*" + self.varargs)
if self.kwargs:
- sig = sig + ("**%s, " % self.kwargs)
+ sig.append("**" + self.kwargs)
- # slice off the last comma and space
- if self.positional or self.varargs or self.kwargs:
- sig = sig[:-2]
+ return "(%s)" % ", ".join(sig)
- sig = sig + ")"
- return sig
-
def fromFunction(func, interface=None, imlevel=0, name=None):
name = name or func.__name__
method = Method(name, func.__doc__)
@@ -894,8 +857,7 @@
nr = 0
# Determine the optional arguments.
- for i in range(len(defaults)):
- opt[names[i+nr]] = defaults[i]
+ opt.update(dict(zip(names[nr:], defaults)))
method.positional = names[:na]
method.required = names[:nr]
Modified: Zope3/trunk/src/zope/interface/tests/test_advice.py
===================================================================
--- Zope3/trunk/src/zope/interface/tests/test_advice.py 2005-10-31 13:19:51 UTC (rev 39767)
+++ Zope3/trunk/src/zope/interface/tests/test_advice.py 2005-10-31 13:57:35 UTC (rev 39768)
@@ -28,6 +28,7 @@
$Id$
"""
+import unittest
from unittest import TestCase, makeSuite, TestSuite
from zope.interface.advice import *
from types import ClassType
@@ -174,4 +175,4 @@
return TestSuite([makeSuite(t,'check') for t in TestClasses])
if __name__ == '__main__':
- unittest.main(defaultTest=test_suite)
+ unittest.main(defaultTest='test_suite')
Modified: Zope3/trunk/src/zope/interface/tests/test_element.py
===================================================================
--- Zope3/trunk/src/zope/interface/tests/test_element.py 2005-10-31 13:19:51 UTC (rev 39767)
+++ Zope3/trunk/src/zope/interface/tests/test_element.py 2005-10-31 13:57:35 UTC (rev 39768)
@@ -31,7 +31,6 @@
e2.setTaggedValue("x", 2)
self.assertEqual(e1.getTaggedValue("x"), 1)
self.assertEqual(e2.getTaggedValue("x"), 2)
-
def test_suite():
@@ -41,4 +40,4 @@
if __name__ == '__main__':
- unittest.main(defaultTest=test_suite)
+ unittest.main(defaultTest='test_suite')
More information about the Zope3-Checkins
mailing list