pymultimethods-commits Mailing List for PyMultimethods (Page 2)
Status: Beta
Brought to you by:
davisn
You can subscribe to this list here.
2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(1) |
Oct
|
Nov
(2) |
Dec
(1) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2008 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(5) |
Nov
|
Dec
|
2009 |
Jan
(4) |
Feb
(1) |
Mar
|
Apr
(1) |
May
(16) |
Jun
|
Jul
(5) |
Aug
(9) |
Sep
|
Oct
|
Nov
(2) |
Dec
(1) |
From: <da...@us...> - 2009-05-23 23:02:10
|
Revision: 23 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=23&view=rev Author: davisn Date: 2009-05-23 23:02:04 +0000 (Sat, 23 May 2009) Log Message: ----------- Add documentation for test suite Added Paths: ----------- branches/python3/test/README.txt Added: branches/python3/test/README.txt =================================================================== --- branches/python3/test/README.txt (rev 0) +++ branches/python3/test/README.txt 2009-05-23 23:02:04 UTC (rev 23) @@ -0,0 +1,27 @@ +PyMultimethods Test Suite Documentation +======================================= + +There are currently two test suites for PyMultimethods. One is for Python 2.x, and the other for Python 3. For now, the difference between the two is that the Python 3 suite removes all tests relating to old-style classes. The Python 3 suite should run on Python 2, but the Python 2 suite will fail on Python 3. + +In order to provide coverate information, a copy of coverage.py in included with the test suites. Please note that the version currently included does not run on Python 3. So, coverage information is not output for Python 3. + +Test Suite Files +---------------- + +Each test suite is contained in a single python script: +* Python 2.x -- manual1.py +* Python 3 -- py3manual1.py + +Running the Suite +----------------- + +Running a test suite is as simple as running its python script. To make things easier, however, a shell script is included (test.sh). The script does a few things that makes testing a little easier. + +1) Adds ../ to the PYTHONPATH (when run from the test directory, this ensures multidispatch.py is on the python path) +2) Runs the suite through coverage.py, so coverage information is generated during execution +3) Dispays summary coverage information after completion of the suite + +The script expects the name of the suite to run as a parameter. For example: + test.sh manual1.py + +When running on Python 3, test.sh will not work. You can use py3test.sh instead. This version of the script does not run through coverage.py. It uses python3.0 as the name of the python executable, so it will use Python 3 even if you have 2.x installed. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2009-05-23 22:37:46
|
Revision: 22 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=22&view=rev Author: davisn Date: 2009-05-23 22:37:38 +0000 (Sat, 23 May 2009) Log Message: ----------- Add testcases for Python 3 Added Paths: ----------- branches/python3/test/py3manual1.py branches/python3/test/py3test.sh Added: branches/python3/test/py3manual1.py =================================================================== --- branches/python3/test/py3manual1.py (rev 0) +++ branches/python3/test/py3manual1.py 2009-05-23 22:37:38 UTC (rev 22) @@ -0,0 +1,227 @@ +# Copyright 2007 Nathan Davis + +# This file is part of PyMultimethods +# +# PyMultimethods is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PyMultimethods is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with PyMultimethods. If not, see <http://www.gnu.org/licenses/>. + +import unittest + +from multidispatch import multimethod, ClassID, anything + +class Foo(object): + CLASS_ID = ClassID() + + @multimethod(CLASS_ID) + def classname(self): + return "Foo" + + @multimethod(CLASS_ID) + def m(self): + return "Foo" + + @multimethod(CLASS_ID, CLASS_ID) + def m(self, other): + return "Foo.m(2)" + +foo = Foo() + +class Bar(Foo): + CLASS_ID = ClassID() + + @Foo.classname.extend(CLASS_ID) + def classname(self): + return "Bar" + +bar = Bar() + +@multimethod(int, int) +@multimethod(float, float) +def add(a,b=1): + return a+b + +@multimethod(int, str) +def add(a,b): + return add(a, int(b)) + +@multimethod(int, "one-hundred") +def add(a,b): + return add(a, 100) + +@multimethod("one", "two") +def add(a,b="two"): + return 3 + +@multimethod("one", "one") +def add(a,b): + return 2 + +@multimethod(str, int) +def add(a,b): + return add(int(a), b) + +@add.extend(str, str) +@add.extend() +def add(a="0",b="0"): + return add(int(a), int(b)) + +@multimethod(int, float) +@multimethod(float, int) +def add(a,b): + return add(float(a), float(b)) + +@multimethod() +def add(): + return None + +#Why doesn't this work? +#@multimethod(list, object, object) +#def add(values, op=add, initial=0): + #acc = initial + #for i in values: + #acc = op(acc, i) + #return acc + +@multimethod(list, object, object) +def add(values, op=sum, start=0): + return op(values, start) + +@multimethod(object) +def add(obj): + return obj + +@multimethod(object, object, object) +def add(obj1, obj2, obj3=dict()): + return (obj1, obj2, obj3) + +#Note: The purpose of this rule is to work with the next one to provide +# coverage of test multidispatch.py@28:18. +@multimethod(Bar, Bar, object) +def add(bar1, bar2, obj3=bar): + #return (bar1, bar2, obj3) + return "bogus" + +@multimethod(Bar, Bar, object) +def add(bar1, bar2, obj3=bar): + return [bar1, bar2, obj3] + +@multimethod(Foo, str) +def add(bar1, bar2="foo"): + return str(bar1) + bar2 + +#@multimethod(float) +#@multimethod(int) +#def sum(a): + #return a + +#Note: This implementation doesn't work in conjunction with the one above it. +#@multimethod(float) +#@multimethod(int) +#def sum(a, *others): + #print "sum(", str(a), ",", str(others), ")" + #b = sum(*others) + #return add(a,b) + +#@multimethod() +#def sum(a, *others): + #b = sum(*others) + #return add(a,b) + +#@multimethod(int) +#@multimethod(float) +#def sum(a, *lst): + #print str(lst) + #a = lst[0] + #b = sum(lst[1:]) + #return add(a,b) + +@multimethod(int) +@multimethod(float) +def sum(a, *lst): + print(a, lst) + +@multimethod(anything) +def anything_test(obj): + return obj.__class__ + +class TestAdd(unittest.TestCase): + def testPositionalArgs(self): + self.assertEquals(add(0, 1), 1) + self.assertEquals(add(1, "1"), 2) + self.assertEquals(add("2", 1), 3) + self.assertEquals(add("2", "2"), 4) + self.assertEquals(add(2.5, 2.5), 5.0) + self.assertEquals(add(3.5, 3), 6.5) + self.assertEquals(add(4, 3.5), 7.5) + self.assertEquals(add(), None) + self.assertEquals(add(1), 2) + self.assertEquals(add(2.5), 3.5) + + def testKeywordArgs(self): + self.assertEquals(add(a=2, b=4), 6) + self.assertEquals(add([1,2,4]), 7) + self.assertEquals(add([1,2,4], start=1), 8) + self.assertEquals(add(dict()), dict()) + self.assertEquals(add(bar, dict(), bar), (bar, dict(), bar)) + self.assertEquals(add(bar, bar, bar), [bar, bar, bar]) + self.assertEquals(add(bar, obj2=list()), (bar, list(), dict())) + self.assertEquals(add(bar, bar), [bar, bar, bar]) + + def testDistpatchByValue(self): + """Dispatch by Value""" + self.assertEquals(add(bar, "teststr"), str(bar) + "teststr") + self.assertEquals(add(bar), str(bar) + "foo") + self.assertEquals(add(0, "one-hundred"), 100) + self.assertEquals(add(0, b="one-hundred"), 100) + self.assertEquals(add(b="one-hundred", a=0), 100) + self.assertEquals(add("one", "one"), 2) + self.assertEquals(add("one", "two"), 3) + + def testExceptionPropagation(self): + """Ensure exceptions are propagated properly""" + self.assertRaises(ValueError, add, "one") + #self.assertEquals(add(a="one"), 3) + + def testUnresolvableCall(self): + """Unresolvable Call""" + self.assertRaises(NotImplementedError, add, 1, 2, 3, 4) + self.assertRaises(NotImplementedError, add, abc="foo") + +class TestNewStyleClasses(unittest.TestCase): + def testClassnameMethod(self): + self.assertEquals(foo.classname(), "Foo") + self.assertEquals(bar.classname(), "Bar") + self.assertEquals(Foo.classname(foo), "Foo") + self.assertEquals(Bar.classname(foo), "Foo") + self.assertEquals(Foo.classname(bar), "Bar") + self.assertEquals(Bar.classname(bar), "Bar") + + def testMMethod(self): + self.assertEquals(foo.m(), "Foo") + self.assertEquals(bar.m(), "Foo") + self.assertEquals(Foo.m(foo), "Foo") + self.assertEquals(Bar.m(foo), "Foo") + self.assertEquals(Foo.m(bar), "Foo") + self.assertEquals(Bar.m(bar), "Foo") + +class FutureTests(unittest.TestCase): + """ + Tests that "should" work, but don't + """ + + def testKeywordSelf(self): + #self.assertEquals(Foo.m(other=old_bar, self=old_foo), "OldFooOldFoo") + pass + +if __name__ == "__main__": + unittest.main() Added: branches/python3/test/py3test.sh =================================================================== --- branches/python3/test/py3test.sh (rev 0) +++ branches/python3/test/py3test.sh 2009-05-23 22:37:38 UTC (rev 22) @@ -0,0 +1,8 @@ +export PYTHONPATH=../:$PYTHONPATH + +#The version of coverage we have doesn't work with Python 3 +#python3.0 coverage.py -e +#python3.0 coverage.py -x $* +#python3.0 coverage.py -r -m ../multidispatch.py + +python3.0 $* This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2009-05-23 22:34:41
|
Revision: 21 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=21&view=rev Author: davisn Date: 2009-05-23 22:34:36 +0000 (Sat, 23 May 2009) Log Message: ----------- Abstract Python 2.x/3 differences for _mro Modified Paths: -------------- branches/python3/multidispatch.py Modified: branches/python3/multidispatch.py =================================================================== --- branches/python3/multidispatch.py 2009-05-23 22:27:45 UTC (rev 20) +++ branches/python3/multidispatch.py 2009-05-23 22:34:36 UTC (rev 21) @@ -18,6 +18,8 @@ from types import FunctionType, MethodType try: + #Python 3 doesn't support old-style classes anymore (ClassType) + #so this will throw and ImportError from types import ClassType #Functions to abstract differences between Python 2.x and Python 3 @@ -26,6 +28,25 @@ def getFuncCode(func): return func.func_code + + def _mro(cls): + """ + A primitive "multimethod" for obtaining the mro of a class + + Returns an iterator over the mro of the input cls + """ + if isinstance(cls, type): + for base in cls.mro(): + yield base + else: + yield cls + for base in cls.__bases__: + for c in _mro(base): + yield c + + #Everything is anything, the ultimate catch-all + yield anything + except ImportError: #Python 3 doesn't have old-style types class ClassType(type): pass @@ -37,24 +58,18 @@ def getFuncCode(func): return func.__code__ -def _mro(cls): - """ - A primitive "multimethod" for obtaining the mro of a class - - Returns an iterator over the mro of the input cls - """ - if isinstance(cls, type): + def _mro(cls): + """ + A primitive "multimethod" for obtaining the mro of a class + + Returns an iterator over the mro of the input cls + """ for base in cls.mro(): yield base - else: - yield cls - for base in cls.__bases__: - for c in _mro(base): - yield c - - #Everything is anything, the ultimate catch-all - yield anything + #Everything is anything, the ultimate catch-all + yield anything + def _isinstance(obj, cls): """ A primitive "multimethod" for determining whether obj is an instance of cls. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2009-05-23 22:27:51
|
Revision: 20 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=20&view=rev Author: davisn Date: 2009-05-23 22:27:45 +0000 (Sat, 23 May 2009) Log Message: ----------- Replace occurences of TypeType with type Modified Paths: -------------- branches/python3/multidispatch.py Modified: branches/python3/multidispatch.py =================================================================== --- branches/python3/multidispatch.py 2009-05-23 22:25:00 UTC (rev 19) +++ branches/python3/multidispatch.py 2009-05-23 22:27:45 UTC (rev 20) @@ -17,8 +17,6 @@ from types import FunctionType, MethodType -TypeType = type - try: from types import ClassType @@ -45,7 +43,7 @@ Returns an iterator over the mro of the input cls """ - if isinstance(cls, TypeType): + if isinstance(cls, type): for base in cls.mro(): yield base else: @@ -141,7 +139,7 @@ new_defaults = defaults[1:] else: new_defaults = defaults - if isinstance(types[0], ClassType) or isinstance(types[0], TypeType) or isinstance(types[0], ClassID): + if isinstance(types[0], ClassType) or isinstance(types[0], type) or isinstance(types[0], ClassID): if types[0] not in self.rules: self.rules[types[0]] = Rule() self.rules[types[0]].next.addRule(types[1:], names[1:], new_defaults, method) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2009-05-23 22:25:06
|
Revision: 19 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=19&view=rev Author: davisn Date: 2009-05-23 22:25:00 +0000 (Sat, 23 May 2009) Log Message: ----------- Add Python 3 version of Python 2.x/3 abstraction functions Modified Paths: -------------- branches/python3/multidispatch.py Modified: branches/python3/multidispatch.py =================================================================== --- branches/python3/multidispatch.py 2009-05-23 22:17:59 UTC (rev 18) +++ branches/python3/multidispatch.py 2009-05-23 22:25:00 UTC (rev 19) @@ -32,6 +32,13 @@ #Python 3 doesn't have old-style types class ClassType(type): pass + #Functions to abstract differences between Python 3 and Python 2.x + def getFuncDefaults(func): + return func.__defaults__ + + def getFuncCode(func): + return func.__code__ + def _mro(cls): """ A primitive "multimethod" for obtaining the mro of a class This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2009-05-23 22:18:07
|
Revision: 18 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=18&view=rev Author: davisn Date: 2009-05-23 22:17:59 +0000 (Sat, 23 May 2009) Log Message: ----------- Add functions to abstract differences between Python 2.x and Python 3 Modified Paths: -------------- branches/python3/multidispatch.py Modified: branches/python3/multidispatch.py =================================================================== --- branches/python3/multidispatch.py 2009-05-23 19:18:41 UTC (rev 17) +++ branches/python3/multidispatch.py 2009-05-23 22:17:59 UTC (rev 18) @@ -21,7 +21,14 @@ try: from types import ClassType -except: + + #Functions to abstract differences between Python 2.x and Python 3 + def getFuncDefaults(func): + return func.func_defaults + + def getFuncCode(func): + return func.func_code +except ImportError: #Python 3 doesn't have old-style types class ClassType(type): pass @@ -99,9 +106,9 @@ assert func is self #Multimethods shouldn't be "mixed" like this, should they? func = func.last_registered_function defaults = [] - if func.__defaults__: - defaults = func.__defaults__ - self.addRule(types, func.__code__.co_varnames, defaults, func) + if getFuncDefaults(func): + defaults = getFuncDefaults(func) + self.addRule(types, getFuncCode(func).co_varnames, defaults, func) self.last_registered_function = func return self return register This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2009-05-23 19:18:42
|
Revision: 17 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=17&view=rev Author: davisn Date: 2009-05-23 19:18:41 +0000 (Sat, 23 May 2009) Log Message: ----------- Changes to make tests succeed on Python 3 Modified Paths: -------------- branches/python3/multidispatch.py Modified: branches/python3/multidispatch.py =================================================================== --- branches/python3/multidispatch.py 2009-05-23 18:50:59 UTC (rev 16) +++ branches/python3/multidispatch.py 2009-05-23 19:18:41 UTC (rev 17) @@ -15,8 +15,16 @@ # You should have received a copy of the GNU Affero General Public License # along with PyMultimethods. If not, see <http://www.gnu.org/licenses/>. -from types import FunctionType, ClassType, TypeType, MethodType +from types import FunctionType, MethodType +TypeType = type + +try: + from types import ClassType +except: + #Python 3 doesn't have old-style types + class ClassType(type): pass + def _mro(cls): """ A primitive "multimethod" for obtaining the mro of a class @@ -81,7 +89,7 @@ # MultiMethods appear as methods on new-style class instances. def __get__(self, instance, owner): if instance: - return MethodType(self, instance, owner) + return MethodType(self, instance) else: return self @@ -91,9 +99,9 @@ assert func is self #Multimethods shouldn't be "mixed" like this, should they? func = func.last_registered_function defaults = [] - if func.func_defaults: - defaults = func.func_defaults - self.addRule(types, func.func_code.co_varnames, defaults, func) + if func.__defaults__: + defaults = func.__defaults__ + self.addRule(types, func.__code__.co_varnames, defaults, func) self.last_registered_function = func return self return register @@ -260,7 +268,7 @@ def __registerFunction__(name, func, types): #print "%s -> %s" % (str(types), str(func)) - if __registry__.has_key(name): + if name in __registry__: mm = __registry__[name] else: mm = MultiMethod() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2009-05-23 18:51:04
|
Revision: 16 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=16&view=rev Author: davisn Date: 2009-05-23 18:50:59 +0000 (Sat, 23 May 2009) Log Message: ----------- Development branch for Python 3.0 compatibility Modified Paths: -------------- branches/python3/test/manual1.py Added Paths: ----------- branches/python3/ Property changes on: branches/python3 ___________________________________________________________________ Added: svn:mergeinfo + Modified: branches/python3/test/manual1.py =================================================================== --- trunk/test/manual1.py 2009-04-08 18:18:08 UTC (rev 15) +++ branches/python3/test/manual1.py 2009-05-23 18:50:59 UTC (rev 16) @@ -186,7 +186,7 @@ @multimethod(int) @multimethod(float) def sum(a, *lst): - print a, lst + print(a, lst) @multimethod(anything) def anything_test(obj): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2009-04-08 18:18:27
|
Revision: 15 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=15&view=rev Author: davisn Date: 2009-04-08 18:18:08 +0000 (Wed, 08 Apr 2009) Log Message: ----------- Add README.txt and add PyPI metadata to setup.py Modified Paths: -------------- trunk/setup.py Added Paths: ----------- trunk/README.txt Added: trunk/README.txt =================================================================== --- trunk/README.txt (rev 0) +++ trunk/README.txt 2009-04-08 18:18:08 UTC (rev 15) @@ -0,0 +1,20 @@ +Introduction +------------ + +Welcome to PyMultimethods - the multimethods library for python, version 0.1. This release may be considered alpha. The API should remain backwards-compatible, but this is not an absolute guarantee. + +PyMultimethods major goals are to be robust and pythonic. To this end (being pythonic), PyMultimethods provides a decorator interface for the creation of multimethods. + +Installation +------------ + +PyMultimethods makes use of the distutil package for installation. To install from source, simply run + + python setup.py install + +from the source root directory. + +Using +----- + +Please see the documentation at http://pymultimethods.wiki.sourceforge.net Modified: trunk/setup.py =================================================================== --- trunk/setup.py 2009-02-20 00:57:35 UTC (rev 14) +++ trunk/setup.py 2009-04-08 18:18:08 UTC (rev 15) @@ -1,9 +1,31 @@ +"""PyMultimethods: Multimethods for Python + +PyMultimethods provides a pythonic library for implementing multimethods. Multimethods are functions that exhibit polymorphic behaviour. However, all of the function arguments are considered during dispatch. +""" + from distutils.core import setup +doclines = __doc__.split('\n') +summary = doclines[0] +description = '\n'.join(doclines[2:]) + +classifiers = ['Development Status :: 4 - Beta', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: GNU Affero General Public License v3', + #'Operating System :: Os Independent', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Topic :: Software Development :: Libraries :: Python Modules', + ] + setup(name='PyMultimethods', version='0.1', - description='Multimethods for Python', + description=summary, + long_description=description, author='Nathan Davis', author_email='dav...@gm...', + license='GNU AGPL, version 3', url='http://launchpad.net/pymultimethods', + platforms=['any'], + classifiers=classifiers, py_modules=['multidispatch']) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2009-02-20 00:57:40
|
Revision: 14 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=14&view=rev Author: davisn Date: 2009-02-20 00:57:35 +0000 (Fri, 20 Feb 2009) Log Message: ----------- Clone 0.1 release Added Paths: ----------- releases/0.1/ Property changes on: releases/0.1 ___________________________________________________________________ Added: svn:mergeinfo + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2009-01-14 01:22:14
|
Revision: 13 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=13&view=rev Author: davisn Date: 2009-01-14 01:22:04 +0000 (Wed, 14 Jan 2009) Log Message: ----------- Added distutils setup script Added Paths: ----------- trunk/setup.py Added: trunk/setup.py =================================================================== --- trunk/setup.py (rev 0) +++ trunk/setup.py 2009-01-14 01:22:04 UTC (rev 13) @@ -0,0 +1,9 @@ +from distutils.core import setup + +setup(name='PyMultimethods', + version='0.1', + description='Multimethods for Python', + author='Nathan Davis', + author_email='dav...@gm...', + url='http://launchpad.net/pymultimethods', + py_modules=['multidispatch']) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2009-01-13 21:07:36
|
Revision: 12 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=12&view=rev Author: davisn Date: 2009-01-13 21:07:26 +0000 (Tue, 13 Jan 2009) Log Message: ----------- * Added "anything", the catch-all type-specifier that matches all types, and associated testcases Modified Paths: -------------- trunk/multidispatch.py trunk/test/manual1.py Modified: trunk/multidispatch.py =================================================================== --- trunk/multidispatch.py 2009-01-13 20:45:42 UTC (rev 11) +++ trunk/multidispatch.py 2009-01-13 21:07:26 UTC (rev 12) @@ -31,6 +31,9 @@ for base in cls.__bases__: for c in _mro(base): yield c + + #Everything is anything, the ultimate catch-all + yield anything def _isinstance(obj, cls): """ @@ -51,6 +54,10 @@ return False class ClassID(object): pass +class anything: + """ + catch-all type-specifier that matches all types (including all old-style classes) + """ class Rule(object): def __init__(self): Modified: trunk/test/manual1.py =================================================================== --- trunk/test/manual1.py 2009-01-13 20:45:42 UTC (rev 11) +++ trunk/test/manual1.py 2009-01-13 21:07:26 UTC (rev 12) @@ -17,7 +17,7 @@ import unittest -from multidispatch import multimethod, ClassID +from multidispatch import multimethod, ClassID, anything class Foo(object): CLASS_ID = ClassID() @@ -188,6 +188,10 @@ def sum(a, *lst): print a, lst +@multimethod(anything) +def anything_test(obj): + return obj.__class__ + class TestOldNewMix(unittest.TestCase): def testOldStyle(self): self.assertEquals(oldnew_mix(old_foo, old_bar), ("OldFoo", "OldBar")) @@ -201,6 +205,10 @@ self.assertEquals(oldnew_mix(bar, arg2=old_foo), ("Foo", "OldFoo")) self.assertEquals(oldnew_mix(old_bar, arg2=bar), ("OldFoo", "Foo")) + def testAnything(self): + self.assertEquals(anything_test(foo), Foo) + self.assertEquals(anything_test(old_foo), OldFoo) + class TestAdd(unittest.TestCase): def testPositionalArgs(self): self.assertEquals(add(0, 1), 1) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2009-01-13 20:45:50
|
Revision: 11 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=11&view=rev Author: davisn Date: 2009-01-13 20:45:42 +0000 (Tue, 13 Jan 2009) Log Message: ----------- * Update copyright to include 2009 Modified Paths: -------------- trunk/multidispatch.py Modified: trunk/multidispatch.py =================================================================== --- trunk/multidispatch.py 2009-01-13 20:44:20 UTC (rev 10) +++ trunk/multidispatch.py 2009-01-13 20:45:42 UTC (rev 11) @@ -1,4 +1,4 @@ -# Copyright 2007, 2008 Nathan Davis +# Copyright 2007-2009 Nathan Davis # This file is part of PyMultimethods # This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2009-01-13 20:44:26
|
Revision: 10 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=10&view=rev Author: davisn Date: 2009-01-13 20:44:20 +0000 (Tue, 13 Jan 2009) Log Message: ----------- * Fix typo in docstring Modified Paths: -------------- trunk/multidispatch.py Modified: trunk/multidispatch.py =================================================================== --- trunk/multidispatch.py 2008-10-02 18:19:14 UTC (rev 9) +++ trunk/multidispatch.py 2009-01-13 20:44:20 UTC (rev 10) @@ -99,7 +99,7 @@ types: List containing the match criteria names: List of the parameters names. Necessary for supporing keyword arguments - defaules: Default values for the last len(defaults) parameters. + defaults: Default values for the last len(defaults) parameters. This list is used to provide default parameter matching. method: The function that gets called on a match. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2008-10-02 18:19:24
|
Revision: 9 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=9&view=rev Author: davisn Date: 2008-10-02 18:19:14 +0000 (Thu, 02 Oct 2008) Log Message: ----------- Fix for LaunchPad bug #277199, "Old-style keyword arguments don't work", and associated test-cases. See bug at https://bugs.launchpad.net/pymultimethods/+bug/277199 for more information. Modified Paths: -------------- trunk/multidispatch.py trunk/test/manual1.py Modified: trunk/multidispatch.py =================================================================== --- trunk/multidispatch.py 2008-10-02 17:58:31 UTC (rev 8) +++ trunk/multidispatch.py 2008-10-02 18:19:14 UTC (rev 9) @@ -39,7 +39,7 @@ Returns True iff obj is an instance of cls """ - if isinstance(cls, type): + if isinstance(cls, type) or isinstance(cls, ClassType): return isinstance(obj, cls) else: if hasattr(obj, "CLASS_ID"): Modified: trunk/test/manual1.py =================================================================== --- trunk/test/manual1.py 2008-10-02 17:58:31 UTC (rev 8) +++ trunk/test/manual1.py 2008-10-02 18:19:14 UTC (rev 9) @@ -71,6 +71,18 @@ old_bar = OldBar() +@multimethod(OldFoo, OldBar) +def oldnew_mix(arg1, arg2): + return ("OldFoo", "OldBar") + +@oldnew_mix.extend(Foo, OldFoo) +def oldnew_mix(arg1, arg2=old_bar): + return ("Foo", "OldFoo") + +@oldnew_mix.extend(OldFoo, Foo) +def oldnew_mix(arg1, arg2=bar): + return ("OldFoo", "Foo") + @multimethod(int, int) @multimethod(float, float) def add(a,b=1): @@ -96,8 +108,6 @@ def add(a,b): return add(int(a), b) -#@multimethod(str, str) -#@multimethod() @add.extend(str, str) @add.extend() def add(a="0",b="0"): @@ -178,6 +188,19 @@ def sum(a, *lst): print a, lst +class TestOldNewMix(unittest.TestCase): + def testOldStyle(self): + self.assertEquals(oldnew_mix(old_foo, old_bar), ("OldFoo", "OldBar")) + self.assertEquals(oldnew_mix(old_bar, old_bar), ("OldFoo", "OldBar")) + + def testOldNewMix(self): + self.assertEquals(oldnew_mix(foo, old_foo), ("Foo", "OldFoo")) + self.assertEquals(oldnew_mix(bar, old_bar), ("Foo", "OldFoo")) + self.assertEquals(oldnew_mix(bar), ("Foo", "OldFoo")) + self.assertEquals(oldnew_mix(old_bar), ("OldFoo", "Foo")) + self.assertEquals(oldnew_mix(bar, arg2=old_foo), ("Foo", "OldFoo")) + self.assertEquals(oldnew_mix(old_bar, arg2=bar), ("OldFoo", "Foo")) + class TestAdd(unittest.TestCase): def testPositionalArgs(self): self.assertEquals(add(0, 1), 1) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2008-10-02 17:58:42
|
Revision: 8 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=8&view=rev Author: davisn Date: 2008-10-02 17:58:31 +0000 (Thu, 02 Oct 2008) Log Message: ----------- Refactoring: Unified resolveOldStyleBaseClasses and resolveNewStyleBaseClasses methods Now that we have the _mro() function in place to return the MRO of an arbitrary object (regardless of heritage), there is no longer any need to resolve old-style classes any differently than new-style classes. Modified Paths: -------------- trunk/multidispatch.py Modified: trunk/multidispatch.py =================================================================== --- trunk/multidispatch.py 2008-10-01 18:54:44 UTC (rev 7) +++ trunk/multidispatch.py 2008-10-02 17:58:31 UTC (rev 8) @@ -184,18 +184,10 @@ function = self.rules[type.CLASS_ID].next.resolve(args, named) if function: return function - if isinstance(type, ClassType): - return self.resolveOldStyleBaseClasses(type, args, named) - return self.resolveNewStyleBaseClasses(type, args, named) + return self.resolveBaseClasses(type, args, named) - def resolveOldStyleBaseClasses(self, type, args, named): - for x in type.__bases__: - value = self.resolveByType(x, args, named) - if value is not None: - return value - - def resolveNewStyleBaseClasses(self, type, args, named): - for t in type.mro(): + def resolveBaseClasses(self, type, args, named): + for t in _mro(type): if t in self.rules: function = self.rules[t].next.resolve(args, named) if function: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2008-10-01 18:54:52
|
Revision: 7 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=7&view=rev Author: davisn Date: 2008-10-01 18:54:44 +0000 (Wed, 01 Oct 2008) Log Message: ----------- Adding coverage.py (by Gareth Rees and Ned Batchelder) and test.sh to determine line coverage of test cases. Added Paths: ----------- trunk/test/coverage.py trunk/test/test.sh Added: trunk/test/coverage.py =================================================================== --- trunk/test/coverage.py (rev 0) +++ trunk/test/coverage.py 2008-10-01 18:54:44 UTC (rev 7) @@ -0,0 +1,952 @@ +#!/usr/bin/python +# +# Perforce Defect Tracking Integration Project +# <http://www.ravenbrook.com/project/p4dti/> +# +# COVERAGE.PY -- COVERAGE TESTING +# +# Gareth Rees, Ravenbrook Limited, 2001-12-04 +# Ned Batchelder, 2004-12-12 +# http://nedbatchelder.com/code/modules/coverage.html +# +# +# 1. INTRODUCTION +# +# This module provides coverage testing for Python code. +# +# The intended readership is all Python developers. +# +# This document is not confidential. +# +# See [GDR 2001-12-04a] for the command-line interface, programmatic +# interface and limitations. See [GDR 2001-12-04b] for requirements and +# design. + +r"""Usage: + +coverage.py -x [-p] MODULE.py [ARG1 ARG2 ...] + Execute module, passing the given command-line arguments, collecting + coverage data. With the -p option, write to a temporary file containing + the machine name and process ID. + +coverage.py -e + Erase collected coverage data. + +coverage.py -c + Collect data from multiple coverage files (as created by -p option above) + and store it into a single file representing the union of the coverage. + +coverage.py -r [-m] [-o dir1,dir2,...] FILE1 FILE2 ... + Report on the statement coverage for the given files. With the -m + option, show line numbers of the statements that weren't executed. + +coverage.py -a [-d dir] [-o dir1,dir2,...] FILE1 FILE2 ... + Make annotated copies of the given files, marking statements that + are executed with > and statements that are missed with !. With + the -d option, make the copies in that directory. Without the -d + option, make each copy in the same directory as the original. + +-o dir,dir2,... + Omit reporting or annotating files when their filename path starts with + a directory listed in the omit list. + e.g. python coverage.py -i -r -o c:\python23,lib\enthought\traits + +Coverage data is saved in the file .coverage by default. Set the +COVERAGE_FILE environment variable to save it somewhere else.""" + +__version__ = "2.6.20060823" # see detailed history at the end of this file. + +import compiler +import compiler.visitor +import os +import re +import string +import sys +import threading +import types +from socket import gethostname + +# 2. IMPLEMENTATION +# +# This uses the "singleton" pattern. +# +# The word "morf" means a module object (from which the source file can +# be deduced by suitable manipulation of the __file__ attribute) or a +# filename. +# +# When we generate a coverage report we have to canonicalize every +# filename in the coverage dictionary just in case it refers to the +# module we are reporting on. It seems a shame to throw away this +# information so the data in the coverage dictionary is transferred to +# the 'cexecuted' dictionary under the canonical filenames. +# +# The coverage dictionary is called "c" and the trace function "t". The +# reason for these short names is that Python looks up variables by name +# at runtime and so execution time depends on the length of variables! +# In the bottleneck of this application it's appropriate to abbreviate +# names to increase speed. + +class StatementFindingAstVisitor(compiler.visitor.ASTVisitor): + def __init__(self, statements, excluded, suite_spots): + compiler.visitor.ASTVisitor.__init__(self) + self.statements = statements + self.excluded = excluded + self.suite_spots = suite_spots + self.excluding_suite = 0 + + def doRecursive(self, node): + self.recordNodeLine(node) + for n in node.getChildNodes(): + self.dispatch(n) + + visitStmt = visitModule = doRecursive + + def doCode(self, node): + if hasattr(node, 'decorators') and node.decorators: + self.dispatch(node.decorators) + self.recordAndDispatch(node.code) + else: + self.doSuite(node, node.code) + + visitFunction = visitClass = doCode + + def getFirstLine(self, node): + # Find the first line in the tree node. + lineno = node.lineno + for n in node.getChildNodes(): + f = self.getFirstLine(n) + if lineno and f: + lineno = min(lineno, f) + else: + lineno = lineno or f + return lineno + + def getLastLine(self, node): + # Find the first line in the tree node. + lineno = node.lineno + for n in node.getChildNodes(): + lineno = max(lineno, self.getLastLine(n)) + return lineno + + def doStatement(self, node): + self.recordLine(self.getFirstLine(node)) + + visitAssert = visitAssign = visitAssTuple = visitDiscard = visitPrint = \ + visitPrintnl = visitRaise = visitSubscript = visitDecorators = \ + doStatement + + def recordNodeLine(self, node): + return self.recordLine(node.lineno) + + def recordLine(self, lineno): + # Returns a bool, whether the line is included or excluded. + if lineno: + # Multi-line tests introducing suites have to get charged to their + # keyword. + if lineno in self.suite_spots: + lineno = self.suite_spots[lineno][0] + # If we're inside an exluded suite, record that this line was + # excluded. + if self.excluding_suite: + self.excluded[lineno] = 1 + return 0 + # If this line is excluded, or suite_spots maps this line to + # another line that is exlcuded, then we're excluded. + elif self.excluded.has_key(lineno) or \ + self.suite_spots.has_key(lineno) and \ + self.excluded.has_key(self.suite_spots[lineno][1]): + return 0 + # Otherwise, this is an executable line. + else: + self.statements[lineno] = 1 + return 1 + return 0 + + default = recordNodeLine + + def recordAndDispatch(self, node): + self.recordNodeLine(node) + self.dispatch(node) + + def doSuite(self, intro, body, exclude=0): + exsuite = self.excluding_suite + if exclude or (intro and not self.recordNodeLine(intro)): + self.excluding_suite = 1 + self.recordAndDispatch(body) + self.excluding_suite = exsuite + + def doPlainWordSuite(self, prevsuite, suite): + # Finding the exclude lines for else's is tricky, because they aren't + # present in the compiler parse tree. Look at the previous suite, + # and find its last line. If any line between there and the else's + # first line are excluded, then we exclude the else. + lastprev = self.getLastLine(prevsuite) + firstelse = self.getFirstLine(suite) + for l in range(lastprev+1, firstelse): + if self.suite_spots.has_key(l): + self.doSuite(None, suite, exclude=self.excluded.has_key(l)) + break + else: + self.doSuite(None, suite) + + def doElse(self, prevsuite, node): + if node.else_: + self.doPlainWordSuite(prevsuite, node.else_) + + def visitFor(self, node): + self.doSuite(node, node.body) + self.doElse(node.body, node) + + def visitIf(self, node): + # The first test has to be handled separately from the rest. + # The first test is credited to the line with the "if", but the others + # are credited to the line with the test for the elif. + self.doSuite(node, node.tests[0][1]) + for t, n in node.tests[1:]: + self.doSuite(t, n) + self.doElse(node.tests[-1][1], node) + + def visitWhile(self, node): + self.doSuite(node, node.body) + self.doElse(node.body, node) + + def visitTryExcept(self, node): + self.doSuite(node, node.body) + for i in range(len(node.handlers)): + a, b, h = node.handlers[i] + if not a: + # It's a plain "except:". Find the previous suite. + if i > 0: + prev = node.handlers[i-1][2] + else: + prev = node.body + self.doPlainWordSuite(prev, h) + else: + self.doSuite(a, h) + self.doElse(node.handlers[-1][2], node) + + def visitTryFinally(self, node): + self.doSuite(node, node.body) + self.doPlainWordSuite(node.body, node.final) + + def visitGlobal(self, node): + # "global" statements don't execute like others (they don't call the + # trace function), so don't record their line numbers. + pass + +the_coverage = None + +class CoverageException(Exception): pass + +class coverage: + # Name of the cache file (unless environment variable is set). + cache_default = ".coverage" + + # Environment variable naming the cache file. + cache_env = "COVERAGE_FILE" + + # A dictionary with an entry for (Python source file name, line number + # in that file) if that line has been executed. + c = {} + + # A map from canonical Python source file name to a dictionary in + # which there's an entry for each line number that has been + # executed. + cexecuted = {} + + # Cache of results of calling the analysis2() method, so that you can + # specify both -r and -a without doing double work. + analysis_cache = {} + + # Cache of results of calling the canonical_filename() method, to + # avoid duplicating work. + canonical_filename_cache = {} + + def __init__(self): + global the_coverage + if the_coverage: + raise CoverageException, "Only one coverage object allowed." + self.usecache = 1 + self.cache = None + self.exclude_re = '' + self.nesting = 0 + self.cstack = [] + self.xstack = [] + self.relative_dir = os.path.normcase(os.path.abspath(os.curdir)+os.path.sep) + + # t(f, x, y). This method is passed to sys.settrace as a trace function. + # See [van Rossum 2001-07-20b, 9.2] for an explanation of sys.settrace and + # the arguments and return value of the trace function. + # See [van Rossum 2001-07-20a, 3.2] for a description of frame and code + # objects. + + def t(self, f, w, a): #pragma: no cover + if w == 'line': + self.c[(f.f_code.co_filename, f.f_lineno)] = 1 + for c in self.cstack: + c[(f.f_code.co_filename, f.f_lineno)] = 1 + return self.t + + def help(self, error=None): + if error: + print error + print + print __doc__ + sys.exit(1) + + def command_line(self, argv, help=None): + import getopt + help = help or self.help + settings = {} + optmap = { + '-a': 'annotate', + '-c': 'collect', + '-d:': 'directory=', + '-e': 'erase', + '-h': 'help', + '-i': 'ignore-errors', + '-m': 'show-missing', + '-p': 'parallel-mode', + '-r': 'report', + '-x': 'execute', + '-o:': 'omit=', + } + short_opts = string.join(map(lambda o: o[1:], optmap.keys()), '') + long_opts = optmap.values() + options, args = getopt.getopt(argv, short_opts, long_opts) + for o, a in options: + if optmap.has_key(o): + settings[optmap[o]] = 1 + elif optmap.has_key(o + ':'): + settings[optmap[o + ':']] = a + elif o[2:] in long_opts: + settings[o[2:]] = 1 + elif o[2:] + '=' in long_opts: + settings[o[2:]+'='] = a + else: #pragma: no cover + pass # Can't get here, because getopt won't return anything unknown. + + if settings.get('help'): + help() + + for i in ['erase', 'execute']: + for j in ['annotate', 'report', 'collect']: + if settings.get(i) and settings.get(j): + help("You can't specify the '%s' and '%s' " + "options at the same time." % (i, j)) + + args_needed = (settings.get('execute') + or settings.get('annotate') + or settings.get('report')) + action = (settings.get('erase') + or settings.get('collect') + or args_needed) + if not action: + help("You must specify at least one of -e, -x, -c, -r, or -a.") + if not args_needed and args: + help("Unexpected arguments: %s" % " ".join(args)) + + self.get_ready(settings.get('parallel-mode')) + self.exclude('#pragma[: ]+[nN][oO] [cC][oO][vV][eE][rR]') + + if settings.get('erase'): + self.erase() + if settings.get('execute'): + if not args: + help("Nothing to do.") + sys.argv = args + self.start() + import __main__ + sys.path[0] = os.path.dirname(sys.argv[0]) + execfile(sys.argv[0], __main__.__dict__) + if settings.get('collect'): + self.collect() + if not args: + args = self.cexecuted.keys() + + ignore_errors = settings.get('ignore-errors') + show_missing = settings.get('show-missing') + directory = settings.get('directory=') + + omit = settings.get('omit=') + if omit is not None: + omit = omit.split(',') + else: + omit = [] + + if settings.get('report'): + self.report(args, show_missing, ignore_errors, omit_prefixes=omit) + if settings.get('annotate'): + self.annotate(args, directory, ignore_errors, omit_prefixes=omit) + + def use_cache(self, usecache, cache_file=None): + self.usecache = usecache + if cache_file and not self.cache: + self.cache_default = cache_file + + def get_ready(self, parallel_mode=False): + if self.usecache and not self.cache: + self.cache = os.environ.get(self.cache_env, self.cache_default) + if parallel_mode: + self.cache += "." + gethostname() + "." + str(os.getpid()) + self.restore() + self.analysis_cache = {} + + def start(self, parallel_mode=False): + self.get_ready(parallel_mode) + if self.nesting == 0: #pragma: no cover + sys.settrace(self.t) + if hasattr(threading, 'settrace'): + threading.settrace(self.t) + self.nesting += 1 + + def stop(self): + self.nesting -= 1 + if self.nesting == 0: #pragma: no cover + sys.settrace(None) + if hasattr(threading, 'settrace'): + threading.settrace(None) + + def erase(self): + self.c = {} + self.analysis_cache = {} + self.cexecuted = {} + if self.cache and os.path.exists(self.cache): + os.remove(self.cache) + self.exclude_re = "" + + def exclude(self, re): + if self.exclude_re: + self.exclude_re += "|" + self.exclude_re += "(" + re + ")" + + def begin_recursive(self): + self.cstack.append(self.c) + self.xstack.append(self.exclude_re) + + def end_recursive(self): + self.c = self.cstack.pop() + self.exclude_re = self.xstack.pop() + + # save(). Save coverage data to the coverage cache. + + def save(self): + if self.usecache and self.cache: + self.canonicalize_filenames() + cache = open(self.cache, 'wb') + import marshal + marshal.dump(self.cexecuted, cache) + cache.close() + + # restore(). Restore coverage data from the coverage cache (if it exists). + + def restore(self): + self.c = {} + self.cexecuted = {} + assert self.usecache + if os.path.exists(self.cache): + self.cexecuted = self.restore_file(self.cache) + + def restore_file(self, file_name): + try: + cache = open(file_name, 'rb') + import marshal + cexecuted = marshal.load(cache) + cache.close() + if isinstance(cexecuted, types.DictType): + return cexecuted + else: + return {} + except: + return {} + + # collect(). Collect data in multiple files produced by parallel mode + + def collect(self): + cache_dir, local = os.path.split(self.cache) + for file in os.listdir(cache_dir): + if not file.startswith(local): + continue + + full_path = os.path.join(cache_dir, file) + cexecuted = self.restore_file(full_path) + self.merge_data(cexecuted) + + def merge_data(self, new_data): + for file_name, file_data in new_data.items(): + if self.cexecuted.has_key(file_name): + self.merge_file_data(self.cexecuted[file_name], file_data) + else: + self.cexecuted[file_name] = file_data + + def merge_file_data(self, cache_data, new_data): + for line_number in new_data.keys(): + if not cache_data.has_key(line_number): + cache_data[line_number] = new_data[line_number] + + # canonical_filename(filename). Return a canonical filename for the + # file (that is, an absolute path with no redundant components and + # normalized case). See [GDR 2001-12-04b, 3.3]. + + def canonical_filename(self, filename): + if not self.canonical_filename_cache.has_key(filename): + f = filename + if os.path.isabs(f) and not os.path.exists(f): + f = os.path.basename(f) + if not os.path.isabs(f): + for path in [os.curdir] + sys.path: + g = os.path.join(path, f) + if os.path.exists(g): + f = g + break + cf = os.path.normcase(os.path.abspath(f)) + self.canonical_filename_cache[filename] = cf + return self.canonical_filename_cache[filename] + + # canonicalize_filenames(). Copy results from "c" to "cexecuted", + # canonicalizing filenames on the way. Clear the "c" map. + + def canonicalize_filenames(self): + for filename, lineno in self.c.keys(): + f = self.canonical_filename(filename) + if not self.cexecuted.has_key(f): + self.cexecuted[f] = {} + self.cexecuted[f][lineno] = 1 + self.c = {} + + # morf_filename(morf). Return the filename for a module or file. + + def morf_filename(self, morf): + if isinstance(morf, types.ModuleType): + if not hasattr(morf, '__file__'): + raise CoverageException, "Module has no __file__ attribute." + file = morf.__file__ + else: + file = morf + return self.canonical_filename(file) + + # analyze_morf(morf). Analyze the module or filename passed as + # the argument. If the source code can't be found, raise an error. + # Otherwise, return a tuple of (1) the canonical filename of the + # source code for the module, (2) a list of lines of statements + # in the source code, and (3) a list of lines of excluded statements. + + def analyze_morf(self, morf): + if self.analysis_cache.has_key(morf): + return self.analysis_cache[morf] + filename = self.morf_filename(morf) + ext = os.path.splitext(filename)[1] + if ext == '.pyc': + if not os.path.exists(filename[0:-1]): + raise CoverageException, ("No source for compiled code '%s'." + % filename) + filename = filename[0:-1] + elif ext != '.py': + raise CoverageException, "File '%s' not Python source." % filename + source = open(filename, 'r') + lines, excluded_lines = self.find_executable_statements( + source.read(), exclude=self.exclude_re + ) + source.close() + result = filename, lines, excluded_lines + self.analysis_cache[morf] = result + return result + + def get_suite_spots(self, tree, spots): + import symbol, token + for i in range(1, len(tree)): + if type(tree[i]) == type(()): + if tree[i][0] == symbol.suite: + # Found a suite, look back for the colon and keyword. + lineno_colon = lineno_word = None + for j in range(i-1, 0, -1): + if tree[j][0] == token.COLON: + lineno_colon = tree[j][2] + elif tree[j][0] == token.NAME: + if tree[j][1] == 'elif': + # Find the line number of the first non-terminal + # after the keyword. + t = tree[j+1] + while t and token.ISNONTERMINAL(t[0]): + t = t[1] + if t: + lineno_word = t[2] + else: + lineno_word = tree[j][2] + break + elif tree[j][0] == symbol.except_clause: + # "except" clauses look like: + # ('except_clause', ('NAME', 'except', lineno), ...) + if tree[j][1][0] == token.NAME: + lineno_word = tree[j][1][2] + break + if lineno_colon and lineno_word: + # Found colon and keyword, mark all the lines + # between the two with the two line numbers. + for l in range(lineno_word, lineno_colon+1): + spots[l] = (lineno_word, lineno_colon) + self.get_suite_spots(tree[i], spots) + + def find_executable_statements(self, text, exclude=None): + # Find lines which match an exclusion pattern. + excluded = {} + suite_spots = {} + if exclude: + reExclude = re.compile(exclude) + lines = text.split('\n') + for i in range(len(lines)): + if reExclude.search(lines[i]): + excluded[i+1] = 1 + + import parser + tree = parser.suite(text+'\n\n').totuple(1) + self.get_suite_spots(tree, suite_spots) + + # Use the compiler module to parse the text and find the executable + # statements. We add newlines to be impervious to final partial lines. + statements = {} + ast = compiler.parse(text+'\n\n') + visitor = StatementFindingAstVisitor(statements, excluded, suite_spots) + compiler.walk(ast, visitor, walker=visitor) + + lines = statements.keys() + lines.sort() + excluded_lines = excluded.keys() + excluded_lines.sort() + return lines, excluded_lines + + # format_lines(statements, lines). Format a list of line numbers + # for printing by coalescing groups of lines as long as the lines + # represent consecutive statements. This will coalesce even if + # there are gaps between statements, so if statements = + # [1,2,3,4,5,10,11,12,13,14] and lines = [1,2,5,10,11,13,14] then + # format_lines will return "1-2, 5-11, 13-14". + + def format_lines(self, statements, lines): + pairs = [] + i = 0 + j = 0 + start = None + pairs = [] + while i < len(statements) and j < len(lines): + if statements[i] == lines[j]: + if start == None: + start = lines[j] + end = lines[j] + j = j + 1 + elif start: + pairs.append((start, end)) + start = None + i = i + 1 + if start: + pairs.append((start, end)) + def stringify(pair): + start, end = pair + if start == end: + return "%d" % start + else: + return "%d-%d" % (start, end) + return string.join(map(stringify, pairs), ", ") + + # Backward compatibility with version 1. + def analysis(self, morf): + f, s, _, m, mf = self.analysis2(morf) + return f, s, m, mf + + def analysis2(self, morf): + filename, statements, excluded = self.analyze_morf(morf) + self.canonicalize_filenames() + if not self.cexecuted.has_key(filename): + self.cexecuted[filename] = {} + missing = [] + for line in statements: + if not self.cexecuted[filename].has_key(line): + missing.append(line) + return (filename, statements, excluded, missing, + self.format_lines(statements, missing)) + + def relative_filename(self, filename): + """ Convert filename to relative filename from self.relative_dir. + """ + return filename.replace(self.relative_dir, "") + + def morf_name(self, morf): + """ Return the name of morf as used in report. + """ + if isinstance(morf, types.ModuleType): + return morf.__name__ + else: + return self.relative_filename(os.path.splitext(morf)[0]) + + def filter_by_prefix(self, morfs, omit_prefixes): + """ Return list of morfs where the morf name does not begin + with any one of the omit_prefixes. + """ + filtered_morfs = [] + for morf in morfs: + for prefix in omit_prefixes: + if self.morf_name(morf).startswith(prefix): + break + else: + filtered_morfs.append(morf) + + return filtered_morfs + + def morf_name_compare(self, x, y): + return cmp(self.morf_name(x), self.morf_name(y)) + + def report(self, morfs, show_missing=1, ignore_errors=0, file=None, omit_prefixes=[]): + if not isinstance(morfs, types.ListType): + morfs = [morfs] + morfs = self.filter_by_prefix(morfs, omit_prefixes) + morfs.sort(self.morf_name_compare) + + max_name = max([5,] + map(len, map(self.morf_name, morfs))) + fmt_name = "%%- %ds " % max_name + fmt_err = fmt_name + "%s: %s" + header = fmt_name % "Name" + " Stmts Exec Cover" + fmt_coverage = fmt_name + "% 6d % 6d % 5d%%" + if show_missing: + header = header + " Missing" + fmt_coverage = fmt_coverage + " %s" + if not file: + file = sys.stdout + print >>file, header + print >>file, "-" * len(header) + total_statements = 0 + total_executed = 0 + for morf in morfs: + name = self.morf_name(morf) + try: + _, statements, _, missing, readable = self.analysis2(morf) + n = len(statements) + m = n - len(missing) + if n > 0: + pc = 100.0 * m / n + else: + pc = 100.0 + args = (name, n, m, pc) + if show_missing: + args = args + (readable,) + print >>file, fmt_coverage % args + total_statements = total_statements + n + total_executed = total_executed + m + except KeyboardInterrupt: #pragma: no cover + raise + except: + if not ignore_errors: + type, msg = sys.exc_info()[0:2] + print >>file, fmt_err % (name, type, msg) + if len(morfs) > 1: + print >>file, "-" * len(header) + if total_statements > 0: + pc = 100.0 * total_executed / total_statements + else: + pc = 100.0 + args = ("TOTAL", total_statements, total_executed, pc) + if show_missing: + args = args + ("",) + print >>file, fmt_coverage % args + + # annotate(morfs, ignore_errors). + + blank_re = re.compile(r"\s*(#|$)") + else_re = re.compile(r"\s*else\s*:\s*(#|$)") + + def annotate(self, morfs, directory=None, ignore_errors=0, omit_prefixes=[]): + morfs = self.filter_by_prefix(morfs, omit_prefixes) + for morf in morfs: + try: + filename, statements, excluded, missing, _ = self.analysis2(morf) + self.annotate_file(filename, statements, excluded, missing, directory) + except KeyboardInterrupt: + raise + except: + if not ignore_errors: + raise + + def annotate_file(self, filename, statements, excluded, missing, directory=None): + source = open(filename, 'r') + if directory: + dest_file = os.path.join(directory, + os.path.basename(filename) + + ',cover') + else: + dest_file = filename + ',cover' + dest = open(dest_file, 'w') + lineno = 0 + i = 0 + j = 0 + covered = 1 + while 1: + line = source.readline() + if line == '': + break + lineno = lineno + 1 + while i < len(statements) and statements[i] < lineno: + i = i + 1 + while j < len(missing) and missing[j] < lineno: + j = j + 1 + if i < len(statements) and statements[i] == lineno: + covered = j >= len(missing) or missing[j] > lineno + if self.blank_re.match(line): + dest.write(' ') + elif self.else_re.match(line): + # Special logic for lines containing only 'else:'. + # See [GDR 2001-12-04b, 3.2]. + if i >= len(statements) and j >= len(missing): + dest.write('! ') + elif i >= len(statements) or j >= len(missing): + dest.write('> ') + elif statements[i] == missing[j]: + dest.write('! ') + else: + dest.write('> ') + elif lineno in excluded: + dest.write('- ') + elif covered: + dest.write('> ') + else: + dest.write('! ') + dest.write(line) + source.close() + dest.close() + +# Singleton object. +the_coverage = coverage() + +# Module functions call methods in the singleton object. +def use_cache(*args, **kw): return the_coverage.use_cache(*args, **kw) +def start(*args, **kw): return the_coverage.start(*args, **kw) +def stop(*args, **kw): return the_coverage.stop(*args, **kw) +def erase(*args, **kw): return the_coverage.erase(*args, **kw) +def begin_recursive(*args, **kw): return the_coverage.begin_recursive(*args, **kw) +def end_recursive(*args, **kw): return the_coverage.end_recursive(*args, **kw) +def exclude(*args, **kw): return the_coverage.exclude(*args, **kw) +def analysis(*args, **kw): return the_coverage.analysis(*args, **kw) +def analysis2(*args, **kw): return the_coverage.analysis2(*args, **kw) +def report(*args, **kw): return the_coverage.report(*args, **kw) +def annotate(*args, **kw): return the_coverage.annotate(*args, **kw) +def annotate_file(*args, **kw): return the_coverage.annotate_file(*args, **kw) + +# Save coverage data when Python exits. (The atexit module wasn't +# introduced until Python 2.0, so use sys.exitfunc when it's not +# available.) +try: + import atexit + atexit.register(the_coverage.save) +except ImportError: + sys.exitfunc = the_coverage.save + +# Command-line interface. +if __name__ == '__main__': + the_coverage.command_line(sys.argv[1:]) + + +# A. REFERENCES +# +# [GDR 2001-12-04a] "Statement coverage for Python"; Gareth Rees; +# Ravenbrook Limited; 2001-12-04; +# <http://www.nedbatchelder.com/code/modules/rees-coverage.html>. +# +# [GDR 2001-12-04b] "Statement coverage for Python: design and +# analysis"; Gareth Rees; Ravenbrook Limited; 2001-12-04; +# <http://www.nedbatchelder.com/code/modules/rees-design.html>. +# +# [van Rossum 2001-07-20a] "Python Reference Manual (releae 2.1.1)"; +# Guide van Rossum; 2001-07-20; +# <http://www.python.org/doc/2.1.1/ref/ref.html>. +# +# [van Rossum 2001-07-20b] "Python Library Reference"; Guido van Rossum; +# 2001-07-20; <http://www.python.org/doc/2.1.1/lib/lib.html>. +# +# +# B. DOCUMENT HISTORY +# +# 2001-12-04 GDR Created. +# +# 2001-12-06 GDR Added command-line interface and source code +# annotation. +# +# 2001-12-09 GDR Moved design and interface to separate documents. +# +# 2001-12-10 GDR Open cache file as binary on Windows. Allow +# simultaneous -e and -x, or -a and -r. +# +# 2001-12-12 GDR Added command-line help. Cache analysis so that it +# only needs to be done once when you specify -a and -r. +# +# 2001-12-13 GDR Improved speed while recording. Portable between +# Python 1.5.2 and 2.1.1. +# +# 2002-01-03 GDR Module-level functions work correctly. +# +# 2002-01-07 GDR Update sys.path when running a file with the -x option, +# so that it matches the value the program would get if it were run on +# its own. +# +# 2004-12-12 NMB Significant code changes. +# - Finding executable statements has been rewritten so that docstrings and +# other quirks of Python execution aren't mistakenly identified as missing +# lines. +# - Lines can be excluded from consideration, even entire suites of lines. +# - The filesystem cache of covered lines can be disabled programmatically. +# - Modernized the code. +# +# 2004-12-14 NMB Minor tweaks. Return 'analysis' to its original behavior +# and add 'analysis2'. Add a global for 'annotate', and factor it, adding +# 'annotate_file'. +# +# 2004-12-31 NMB Allow for keyword arguments in the module global functions. +# Thanks, Allen. +# +# 2005-12-02 NMB Call threading.settrace so that all threads are measured. +# Thanks Martin Fuzzey. Add a file argument to report so that reports can be +# captured to a different destination. +# +# 2005-12-03 NMB coverage.py can now measure itself. +# +# 2005-12-04 NMB Adapted Greg Rogers' patch for using relative filenames, +# and sorting and omitting files to report on. +# +# 2006-07-23 NMB Applied Joseph Tate's patch for function decorators. +# +# 2006-08-21 NMB Applied Sigve Tjora and Mark van der Wal's fixes for argument +# handling. +# +# 2006-08-22 NMB Applied Geoff Bache's parallel mode patch. +# +# 2006-08-23 NMB Refactorings to improve testability. Fixes to command-line +# logic for parallel mode and collect. + +# C. COPYRIGHT AND LICENCE +# +# Copyright 2001 Gareth Rees. All rights reserved. +# Copyright 2004-2006 Ned Batchelder. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the +# distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +# DAMAGE. +# +# $Id: coverage.py 47 2006-08-24 01:08:48Z Ned $ Added: trunk/test/test.sh =================================================================== --- trunk/test/test.sh (rev 0) +++ trunk/test/test.sh 2008-10-01 18:54:44 UTC (rev 7) @@ -0,0 +1,5 @@ +export PYTHONPATH=../:$PYTHONPATH + +python coverage.py -e +python coverage.py -x $* +python coverage.py -r -m ../multidispatch.py This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2008-10-01 18:47:13
|
Revision: 6 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=6&view=rev Author: davisn Date: 2008-10-01 18:46:59 +0000 (Wed, 01 Oct 2008) Log Message: ----------- __registerFunction__ now uses MultiMEthod.extend() instead of calling addRule itself Modified Paths: -------------- trunk/multidispatch.py Modified: trunk/multidispatch.py =================================================================== --- trunk/multidispatch.py 2008-10-01 18:39:20 UTC (rev 5) +++ trunk/multidispatch.py 2008-10-01 18:46:59 UTC (rev 6) @@ -266,12 +266,7 @@ else: mm = MultiMethod() __registry__[name] = mm - defaults = [] - if func.func_defaults: - defaults = func.func_defaults - mm.addRule(types, func.func_code.co_varnames, defaults, func) - mm.last_registered_function = func - return mm + return mm.extend(*types)(func) registerMultiMethod.addRule((str, FunctionType, list), ["name", "func", "types"], [], __registerFunction__) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2008-10-01 18:39:29
|
Revision: 5 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=5&view=rev Author: davisn Date: 2008-10-01 18:39:20 +0000 (Wed, 01 Oct 2008) Log Message: ----------- Added extend() method to MultiMethod class Rules can now be added to explicitly specified MultiMethod objects by calling using mm.extend(*type_criteria) as a function decorator. In this case, it doesn't matter what the underlying function is called -- it is bound to the specified MultiMethod (in this case, mm) and the function name is entirely ignored. Also: o added test cases to test extend() o fixed a test case o fixed a minor typo in the licensing terms in the headers of multidispatch.py and test/manual1.py Modified Paths: -------------- trunk/multidispatch.py trunk/test/manual1.py Modified: trunk/multidispatch.py =================================================================== --- trunk/multidispatch.py 2007-12-28 23:19:38 UTC (rev 4) +++ trunk/multidispatch.py 2008-10-01 18:39:20 UTC (rev 5) @@ -1,4 +1,4 @@ -# Copyright 2007 Nathan Davis +# Copyright 2007, 2008 Nathan Davis # This file is part of PyMultimethods # @@ -13,7 +13,7 @@ # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License -# along with Foobar. If not, see <http://www.gnu.org/licenses/>. +# along with PyMultimethods. If not, see <http://www.gnu.org/licenses/>. from types import FunctionType, ClassType, TypeType, MethodType @@ -78,6 +78,19 @@ else: return self + def extend(self, *types): + def register(func): + if isinstance(func, MultiMethod): + assert func is self #Multimethods shouldn't be "mixed" like this, should they? + func = func.last_registered_function + defaults = [] + if func.func_defaults: + defaults = func.func_defaults + self.addRule(types, func.func_code.co_varnames, defaults, func) + self.last_registered_function = func + return self + return register + def addRule(self, types, names, defaults, method): """ Adds a new rule to the MultiMethod. @@ -260,13 +273,13 @@ mm.last_registered_function = func return mm -registerMultiMethod.addRule((FunctionType,), ["name", "func", "types"], [], __registerFunction__) +registerMultiMethod.addRule((str, FunctionType, list), ["name", "func", "types"], [], __registerFunction__) def __registerMultiMethod__(name, func, types): func = __last_registered__[(name)] return registerMultiMethod(name, func, types) -registerMultiMethod.addRule((MultiMethod,), ["name", "func", "types"], [], __registerFunction__) +registerMultiMethod.addRule((str, MultiMethod, list), ["name", "func", "types"], [], __registerMultiMethod__) def multimethod(*types): def register(func): Modified: trunk/test/manual1.py =================================================================== --- trunk/test/manual1.py 2007-12-28 23:19:38 UTC (rev 4) +++ trunk/test/manual1.py 2008-10-01 18:39:20 UTC (rev 5) @@ -13,7 +13,7 @@ # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License -# along with Foobar. If not, see <http://www.gnu.org/licenses/>. +# along with PyMultimethods. If not, see <http://www.gnu.org/licenses/>. import unittest @@ -39,7 +39,7 @@ class Bar(Foo): CLASS_ID = ClassID() - @multimethod(CLASS_ID) + @Foo.classname.extend(CLASS_ID) def classname(self): return "Bar" @@ -96,8 +96,10 @@ def add(a,b): return add(int(a), b) -@multimethod(str, str) -@multimethod() +#@multimethod(str, str) +#@multimethod() +@add.extend(str, str) +@add.extend() def add(a="0",b="0"): return add(int(a), int(b)) @@ -134,7 +136,8 @@ # coverage of test multidispatch.py@28:18. @multimethod(Bar, Bar, object) def add(bar1, bar2, obj3=bar): - return (bar1, bar2, obj3) + #return (bar1, bar2, obj3) + return "bogus" @multimethod(Bar, Bar, object) def add(bar1, bar2, obj3=bar): @@ -215,7 +218,7 @@ def testUnresolvableCall(self): """Unresolvable Call""" - self.assertRaises(NotImplementedError, add, 1, 2, 3) + self.assertRaises(NotImplementedError, add, 1, 2, 3, 4) self.assertRaises(NotImplementedError, add, abc="foo") class TestNewStyleClasses(unittest.TestCase): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2007-12-28 23:19:37
|
Revision: 4 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=4&view=rev Author: davisn Date: 2007-12-28 15:19:38 -0800 (Fri, 28 Dec 2007) Log Message: ----------- Add test suite Added Paths: ----------- trunk/test/ trunk/test/manual1.py Added: trunk/test/manual1.py =================================================================== --- trunk/test/manual1.py (rev 0) +++ trunk/test/manual1.py 2007-12-28 23:19:38 UTC (rev 4) @@ -0,0 +1,263 @@ +# Copyright 2007 Nathan Davis + +# This file is part of PyMultimethods +# +# PyMultimethods is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PyMultimethods is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with Foobar. If not, see <http://www.gnu.org/licenses/>. + +import unittest + +from multidispatch import multimethod, ClassID + +class Foo(object): + CLASS_ID = ClassID() + + @multimethod(CLASS_ID) + def classname(self): + return "Foo" + + @multimethod(CLASS_ID) + def m(self): + return "Foo" + + @multimethod(CLASS_ID, CLASS_ID) + def m(self, other): + return "Foo.m(2)" + +foo = Foo() + +class Bar(Foo): + CLASS_ID = ClassID() + + @multimethod(CLASS_ID) + def classname(self): + return "Bar" + +bar = Bar() + +class OldFoo: + CLASS_ID = ClassID() + + @multimethod(CLASS_ID) + def classname(self): + return "OldFoo" + + @multimethod(CLASS_ID) + def m(self): + return "OldFoo" + + @multimethod(CLASS_ID, CLASS_ID) + def m(self, other): + return self.m() + other.m() + +old_foo = OldFoo() + +class OldBar(OldFoo): + CLASS_ID = ClassID() + + @multimethod(CLASS_ID) + def classname(self): + return "OldBar" + +old_bar = OldBar() + +@multimethod(int, int) +@multimethod(float, float) +def add(a,b=1): + return a+b + +@multimethod(int, str) +def add(a,b): + return add(a, int(b)) + +@multimethod(int, "one-hundred") +def add(a,b): + return add(a, 100) + +@multimethod("one", "two") +def add(a,b="two"): + return 3 + +@multimethod("one", "one") +def add(a,b): + return 2 + +@multimethod(str, int) +def add(a,b): + return add(int(a), b) + +@multimethod(str, str) +@multimethod() +def add(a="0",b="0"): + return add(int(a), int(b)) + +@multimethod(int, float) +@multimethod(float, int) +def add(a,b): + return add(float(a), float(b)) + +@multimethod() +def add(): + return None + +#Why doesn't this work? +#@multimethod(list, object, object) +#def add(values, op=add, initial=0): + #acc = initial + #for i in values: + #acc = op(acc, i) + #return acc + +@multimethod(list, object, object) +def add(values, op=sum, start=0): + return op(values, start) + +@multimethod(object) +def add(obj): + return obj + +@multimethod(object, object, object) +def add(obj1, obj2, obj3=dict()): + return (obj1, obj2, obj3) + +#Note: The purpose of this rule is to work with the next one to provide +# coverage of test multidispatch.py@28:18. +@multimethod(Bar, Bar, object) +def add(bar1, bar2, obj3=bar): + return (bar1, bar2, obj3) + +@multimethod(Bar, Bar, object) +def add(bar1, bar2, obj3=bar): + return [bar1, bar2, obj3] + +@multimethod(Foo, str) +def add(bar1, bar2="foo"): + return str(bar1) + bar2 + +#@multimethod(float) +#@multimethod(int) +#def sum(a): + #return a + +#Note: This implementation doesn't work in conjunction with the one above it. +#@multimethod(float) +#@multimethod(int) +#def sum(a, *others): + #print "sum(", str(a), ",", str(others), ")" + #b = sum(*others) + #return add(a,b) + +#@multimethod() +#def sum(a, *others): + #b = sum(*others) + #return add(a,b) + +#@multimethod(int) +#@multimethod(float) +#def sum(a, *lst): + #print str(lst) + #a = lst[0] + #b = sum(lst[1:]) + #return add(a,b) + +@multimethod(int) +@multimethod(float) +def sum(a, *lst): + print a, lst + +class TestAdd(unittest.TestCase): + def testPositionalArgs(self): + self.assertEquals(add(0, 1), 1) + self.assertEquals(add(1, "1"), 2) + self.assertEquals(add("2", 1), 3) + self.assertEquals(add("2", "2"), 4) + self.assertEquals(add(2.5, 2.5), 5.0) + self.assertEquals(add(3.5, 3), 6.5) + self.assertEquals(add(4, 3.5), 7.5) + self.assertEquals(add(), None) + self.assertEquals(add(1), 2) + self.assertEquals(add(2.5), 3.5) + + def testKeywordArgs(self): + self.assertEquals(add(a=2, b=4), 6) + self.assertEquals(add([1,2,4]), 7) + self.assertEquals(add([1,2,4], start=1), 8) + self.assertEquals(add(dict()), dict()) + self.assertEquals(add(bar, dict(), bar), (bar, dict(), bar)) + self.assertEquals(add(bar, bar, bar), [bar, bar, bar]) + self.assertEquals(add(bar, obj2=list()), (bar, list(), dict())) + self.assertEquals(add(bar, bar), [bar, bar, bar]) + + def testDistpatchByValue(self): + """Dispatch by Value""" + self.assertEquals(add(bar, "teststr"), str(bar) + "teststr") + self.assertEquals(add(bar), str(bar) + "foo") + self.assertEquals(add(0, "one-hundred"), 100) + self.assertEquals(add(0, b="one-hundred"), 100) + self.assertEquals(add(b="one-hundred", a=0), 100) + self.assertEquals(add("one", "one"), 2) + self.assertEquals(add("one", "two"), 3) + + def testExceptionPropagation(self): + """Ensure exceptions are propagated properly""" + self.assertRaises(ValueError, add, "one") + #self.assertEquals(add(a="one"), 3) + + def testUnresolvableCall(self): + """Unresolvable Call""" + self.assertRaises(NotImplementedError, add, 1, 2, 3) + self.assertRaises(NotImplementedError, add, abc="foo") + +class TestNewStyleClasses(unittest.TestCase): + def testClassnameMethod(self): + self.assertEquals(foo.classname(), "Foo") + self.assertEquals(bar.classname(), "Bar") + self.assertEquals(Foo.classname(foo), "Foo") + self.assertEquals(Bar.classname(foo), "Foo") + self.assertEquals(Foo.classname(bar), "Bar") + self.assertEquals(Bar.classname(bar), "Bar") + + def testMMethod(self): + self.assertEquals(foo.m(), "Foo") + self.assertEquals(bar.m(), "Foo") + self.assertEquals(Foo.m(foo), "Foo") + self.assertEquals(Bar.m(foo), "Foo") + self.assertEquals(Foo.m(bar), "Foo") + self.assertEquals(Bar.m(bar), "Foo") + +class TestOldStyleClasses(unittest.TestCase): + def test(self): + self.assertEquals(old_foo.classname(), "OldFoo") + self.assertEquals(old_bar.classname(), "OldBar") + self.assertEquals(old_foo.m(), "OldFoo") + self.assertEquals(old_bar.m(), "OldFoo") + self.assertEquals(Foo.m(old_foo, other=old_bar), "OldFooOldFoo") + + self.assertEquals(Foo.m(foo, other=bar), "Foo.m(2)") + + #actual.append(sum(1)) + #actual.append(sum(1.1)) + #actual.append(sum(1,1,1,1,1)) + #actual.append(sum(1,1,2,1,.5)) + +class FutureTests(unittest.TestCase): + """ + Tests that "should" work, but don't + """ + + def testKeywordSelf(self): + #self.assertEquals(Foo.m(other=old_bar, self=old_foo), "OldFooOldFoo") + pass + +if __name__ == "__main__": + unittest.main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2007-11-28 04:06:20
|
Revision: 3 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=3&view=rev Author: davisn Date: 2007-11-27 20:06:25 -0800 (Tue, 27 Nov 2007) Log Message: ----------- Raise NotImplementedError instead of string Modified Paths: -------------- trunk/multidispatch.py Modified: trunk/multidispatch.py =================================================================== --- trunk/multidispatch.py 2007-11-27 22:42:25 UTC (rev 2) +++ trunk/multidispatch.py 2007-11-28 04:06:25 UTC (rev 3) @@ -138,7 +138,7 @@ method = self.resolve(args, named) #print "(%s, %s) -> %s)" % (str(args), str(named), str(method)) if not method: - raise "Operation not supported with given parameters", (args,named) + raise NotImplementedError("Operation not supported with given parameters", args,named) return method(*args, **named) def resolve(self, args, kwargs): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2007-11-27 22:42:23
|
Revision: 2 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=2&view=rev Author: davisn Date: 2007-11-27 14:42:25 -0800 (Tue, 27 Nov 2007) Log Message: ----------- Initial import of project code Added Paths: ----------- trunk/COPYING trunk/multidispatch.py Added: trunk/COPYING =================================================================== --- trunk/COPYING (rev 0) +++ trunk/COPYING 2007-11-27 22:42:25 UTC (rev 2) @@ -0,0 +1,662 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license +for software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are +designed to take away your freedom to share and change the works. By +contrast, our General Public Licenses are intended to guarantee your +freedom to share and change all versions of a program--to make sure it +remains free software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public +License. + + "Copyright" also means copyright-like laws that apply to other kinds +of works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further restriction, +you may remove that term. If a license document contains a further +restriction but permits relicensing or conveying under this License, you +may add to a covered work material governed by the terms of that license +document, provided that the further restriction does not survive such +relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have permission +to link or combine any covered work with a work licensed under version 3 +of the GNU General Public License into a single combined work, and to +convey the resulting work. The terms of this License will continue to +apply to the part which is the covered work, but the work with which it is +combined will remain governed by version 3 of the GNU General Public +License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may differ +in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero +General Public License "or any later version" applies to it, you have +the option of following the terms and conditions either of that +numbered version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number +of the GNU Affero General Public License, you may choose any version +ever published by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that +proxy's public statement of acceptance of a version permanently +authorizes you to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +<http://www.gnu.org/licenses/>. Added: trunk/multidispatch.py =================================================================== --- trunk/multidispatch.py (rev 0) +++ trunk/multidispatch.py 2007-11-27 22:42:25 UTC (rev 2) @@ -0,0 +1,276 @@ +# Copyright 2007 Nathan Davis + +# This file is part of PyMultimethods +# +# PyMultimethods is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PyMultimethods is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with Foobar. If not, see <http://www.gnu.org/licenses/>. + +from types import FunctionType, ClassType, TypeType, MethodType + +def _mro(cls): + """ + A primitive "multimethod" for obtaining the mro of a class + + Returns an iterator over the mro of the input cls + """ + if isinstance(cls, TypeType): + for base in cls.mro(): + yield base + else: + yield cls + for base in cls.__bases__: + for c in _mro(base): + yield c + +def _isinstance(obj, cls): + """ + A primitive "multimethod" for determining whether obj is an instance of cls. + This differs from the built-in implemention in it handles the case where cls is a not a type (i.e., it's a ClassID instance). + + Returns True iff obj is an instance of cls + """ + if isinstance(cls, type): + return isinstance(obj, cls) + else: + if hasattr(obj, "CLASS_ID"): + if obj.CLASS_ID == cls: + return True + for c in _mro(obj.__class__): + if hasattr(c, "CLASS_ID") and c.CLASS_ID == cls: + return True + return False + +class ClassID(object): pass + +class Rule(object): + def __init__(self): + self.next = MultiMethod() + self.defaultable = False + + #You can uncomment this function if you need to do debugging. + #def __repr__(self): + #return str((self.next, self.defaultable)) + +class MultiMethod(object): + def __init__(self): + """Creates a MultiMethod object. initially with no rules.""" + self.by_value = dict() #value -> Rule + self.rules = dict() #type -> Rule + self.named_by_value = dict() + self.named_rules = dict() #(param_name, type) -> Rule + self.implementation = None + + # We implement the __get__ attribute descriptor protocol in order to make + # MultiMethods appear as methods on new-style class instances. + def __get__(self, instance, owner): + if instance: + return MethodType(self, instance, owner) + else: + return self + + def addRule(self, types, names, defaults, method): + """ + Adds a new rule to the MultiMethod. + + Parameters: + types: List containing the match criteria + names: List of the parameters names. Necessary for supporing + keyword arguments + defaules: Default values for the last len(defaults) parameters. + This list is used to provide default parameter matching. + method: The function that gets called on a match. + + If a matching rule already exists, it is overwritten. + """ + if not types: + self.implementation = method + else: + if len(names) == len(defaults): + new_defaults = defaults[1:] + else: + new_defaults = defaults + if isinstance(types[0], ClassType) or isinstance(types[0], TypeType) or isinstance(types[0], ClassID): + if types[0] not in self.rules: + self.rules[types[0]] = Rule() + self.rules[types[0]].next.addRule(types[1:], names[1:], new_defaults, method) + + rule = Rule() + if (names[0], types[0]) in self.named_rules: + rule = self.named_rules[(names[0], types[0])] + rule.next.addRule(types[1:], names[1:], new_defaults, method) + if len(defaults) == len(names): + rule.defaultable = True + self.named_rules[(names[0], types[0])] = rule + else: + if types[0] not in self.by_value: + self.by_value[types[0]] = Rule() + self.by_value[types[0]].next.addRule(types[1:], names[1:], new_defaults, method) + + rule = Rule() + if (names[0], types[0]) in self.named_by_value: + rule = self.named_by_value[(names[0], types[0])] + rule.next.addRule(types[1:], names[1:], new_defaults, method) + self.named_by_value[(names[0], types[0])] = rule + + def __call__(self, *args, **named): + return self.invoke(args, named) + + def invoke(self, args, named): + """ + Invoke the MultiMethod + + Note: The preferred way of invoking a MultiMethod is through __call__ + + Parameters: + args: list of values for positional arguments + named: dictionary of name->value mappings for keyword arguments + """ + method = self.resolve(args, named) + #print "(%s, %s) -> %s)" % (str(args), str(named), str(method)) + if not method: + raise "Operation not supported with given parameters", (args,named) + return method(*args, **named) + + def resolve(self, args, kwargs): + #print "resolve(%s, %s)" % (str(args), str(kwargs)) + if not args: + if not kwargs: + if self.implementation: + return self.implementation + return self.resolveDefaults() + else: + return self.resolveKeywords(kwargs) + + function = self.resolveByValue(args[0], args[1:], kwargs) + if function: + return function + return self.resolveByType(args[0].__class__, args[1:], kwargs) + + def resolveByValue(self, value, args, kwargs): + try: #Necessary, for now at least, in case value is not hashable + if value in self.by_value: + return self.by_value[value].next.resolve(args, kwargs) + except: pass + return None + + def resolveByType(self, type, args, named): + function = None + if type in self.rules: + function = self.rules[type].next.resolve(args, named) + elif hasattr(type, "CLASS_ID") and type.CLASS_ID in self.rules: + function = self.rules[type.CLASS_ID].next.resolve(args, named) + if function: + return function + if isinstance(type, ClassType): + return self.resolveOldStyleBaseClasses(type, args, named) + return self.resolveNewStyleBaseClasses(type, args, named) + + def resolveOldStyleBaseClasses(self, type, args, named): + for x in type.__bases__: + value = self.resolveByType(x, args, named) + if value is not None: + return value + + def resolveNewStyleBaseClasses(self, type, args, named): + for t in type.mro(): + if t in self.rules: + function = self.rules[t].next.resolve(args, named) + if function: + return function + elif hasattr(t, "CLASS_ID") and t.CLASS_ID in self.rules: + function = self.rules[t.CLASS_ID].next.resolve(args, named) + if function: + return function + return None + + def resolveDefaults(self): + for key in self.named_rules: + rule = self.named_rules[key] + if rule.defaultable: + if rule.next.implementation: + return rule.next.implementation + else: + value = rule.next.resolveDefaults() + if value: + return value + return None + + def resolveKeywords(self, named): + defaultable = [] + for name in named: + value = named[name] + if not isinstance(value, list): + #print "Trying (%s, %s)" % (str(name), str(value)) + if (name, value) in self.named_by_value: + #print "Potential match found!" + names = named.copy() + del names[name] + function = self.named_by_value[(name, value)].next.resolve([], names) + if function: + #print "Match Found!" + return function + for key in self.named_rules: + rule = self.named_rules[key] + for name in named: + value = named[name] + #print "testing", (name, value), "against", key + if name==key[0] and _isinstance(value, key[1]): + names = named.copy() + del names[name] + method = None + if not names and rule.next.implementation: + method = rule.next.implementation + elif rule.next: + method = rule.next.resolve([], names) + if method: + return method + elif name!=key[0] and rule.defaultable and rule.next: + defaultable.append(rule) + for rule in defaultable: + method = rule.next.resolve([], named) + if method: + return method + +__registry__ = dict() +__last_registered__ = dict() + +registerMultiMethod = MultiMethod() + +def __registerFunction__(name, func, types): + #print "%s -> %s" % (str(types), str(func)) + if __registry__.has_key(name): + mm = __registry__[name] + else: + mm = MultiMethod() + __registry__[name] = mm + defaults = [] + if func.func_defaults: + defaults = func.func_defaults + mm.addRule(types, func.func_code.co_varnames, defaults, func) + mm.last_registered_function = func + return mm + +registerMultiMethod.addRule((FunctionType,), ["name", "func", "types"], [], __registerFunction__) + +def __registerMultiMethod__(name, func, types): + func = __last_registered__[(name)] + return registerMultiMethod(name, func, types) + +registerMultiMethod.addRule((MultiMethod,), ["name", "func", "types"], [], __registerFunction__) + +def multimethod(*types): + def register(func): + if isinstance(func, MultiMethod): + func = func.last_registered_function + return __registerFunction__(func.__name__, func, types) + return register This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <da...@us...> - 2007-09-08 04:06:43
|
Revision: 1 http://pymultimethods.svn.sourceforge.net/pymultimethods/?rev=1&view=rev Author: davisn Date: 2007-09-07 21:06:46 -0700 (Fri, 07 Sep 2007) Log Message: ----------- Created base directory structure Added Paths: ----------- branches/ releases/ trunk/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |