pax_global_header 0000666 0000000 0000000 00000000064 13332627007 0014515 g ustar 00root root 0000000 0000000 52 comment=2cc8df6f8871c83c67a60f4b1b54f73702c87457
multipledispatch-0.6.0/ 0000775 0000000 0000000 00000000000 13332627007 0015073 5 ustar 00root root 0000000 0000000 multipledispatch-0.6.0/.binstar.yml 0000664 0000000 0000000 00000000364 13332627007 0017341 0 ustar 00root root 0000000 0000000 package: multipledispatch
platform:
- linux-64
- linux-32
- osx-64
- win-64
engine:
- python=2.6
- python=2.7
- python=3.3
- python=3.4
script:
- touch build.sh
- conda build .
build_targets:
files: conda
channels: main
multipledispatch-0.6.0/.gitignore 0000664 0000000 0000000 00000000051 13332627007 0017057 0 ustar 00root root 0000000 0000000 *.pyc
*.egg-info/
.cache/
.pytest_cache/
multipledispatch-0.6.0/.travis.yml 0000664 0000000 0000000 00000001227 13332627007 0017206 0 ustar 00root root 0000000 0000000 language: python
python:
- "2.7"
- "3.3"
- "3.4"
- "3.5"
- "3.6"
- "3.7-dev"
- "pypy"
- "pypy3"
install:
- pip install --upgrade pip
- pip install coverage
- pip install --upgrade pytest pytest-benchmark
script:
- |
if [[ $(bc <<< "$TRAVIS_PYTHON_VERSION >= 3.3") -eq 1 ]]; then
py.test --doctest-modules multipledispatch
else
py.test --doctest-modules --ignore=multipledispatch/tests/test_dispatcher_3only.py multipledispatch
fi
after_success:
- |
if [[ $TRAVIS_PYTHON_VERSION != 'pypy' ]]; then pip install coveralls; coveralls ; fi
notifications:
email: false
multipledispatch-0.6.0/LICENSE.txt 0000664 0000000 0000000 00000002737 13332627007 0016727 0 ustar 00root root 0000000 0000000 Copyright (c) 2014 Matthew Rocklin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
a. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
b. 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.
c. Neither the name of multipledispatch nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
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 REGENTS OR 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.
multipledispatch-0.6.0/README.rst 0000664 0000000 0000000 00000007226 13332627007 0016571 0 ustar 00root root 0000000 0000000 Multiple Dispatch
=================
|Build Status| |Coverage Status| |Version Status|
A relatively sane approach to multiple dispatch in Python.
This implementation of multiple dispatch is efficient, mostly complete,
performs static analysis to avoid conflicts, and provides optional namespace
support. It looks good too.
See the documentation at https://multiple-dispatch.readthedocs.io/
Example
-------
.. code-block:: python
>>> from multipledispatch import dispatch
>>> @dispatch(int, int)
... def add(x, y):
... return x + y
>>> @dispatch(object, object)
... def add(x, y):
... return "%s + %s" % (x, y)
>>> add(1, 2)
3
>>> add(1, 'hello')
'1 + hello'
What this does
--------------
- Dispatches on all non-keyword arguments
- Supports inheritance
- Supports instance methods
- Supports union types, e.g. ``(int, float)``
- Supports builtin abstract classes, e.g. ``Iterator, Number, ...``
- Caches for fast repeated lookup
- Identifies possible ambiguities at function definition time
- Provides hints to resolve ambiguities when they occur
- Supports namespaces with optional keyword arguments
- Supports variadic dispatch
What this doesn't do
--------------------
- Diagonal dispatch
.. code-block:: python
a = arbitrary_type()
@dispatch(a, a)
def are_same_type(x, y):
return True
- Efficient update: The addition of a new signature requires a full resolve of
the whole function. This becomes troublesome after you get to a few hundred
type signatures.
Installation and Dependencies
-----------------------------
``multipledispatch`` is on the Python Package Index (PyPI):
::
pip install multipledispatch
or
::
easy_install multipledispatch
``multipledispatch`` supports Python 2.6+ and Python 3.2+ with a common
codebase. It is pure Python and requires only the small `six
`_ library as a dependency.
It is, in short, a light weight dependency.
License
-------
New BSD. See `License file`_.
Links
-----
- `Five-minute Multimethods in Python by Guido`_
- `multimethods package on PyPI`_
- `singledispatch in Python 3.4's functools`_
- `Clojure Protocols`_
- `Julia methods docs`_
- `Karpinksi notebook: *The Design Impact of Multiple Dispatch*`_
- `Wikipedia article`_
- `PEP 3124 - *Overloading, Generic Functions, Interfaces, and Adaptation*`_
.. _`Five-minute Multimethods in Python by Guido`:
http://www.artima.com/weblogs/viewpost.jsp?thread=101605
.. _`multimethods package on PyPI`:
https://pypi.python.org/pypi/multimethods
.. _`singledispatch in Python 3.4's functools`:
http://docs.python.org/3.4/library/functools.html#functools.singledispatch
.. _`Clojure Protocols`:
http://clojure.org/protocols
.. _`Julia methods docs`:
https://julia.readthedocs.io/en/latest/manual/methods/
.. _`Karpinksi notebook: *The Design Impact of Multiple Dispatch*`:
http://nbviewer.ipython.org/gist/StefanKarpinski/b8fe9dbb36c1427b9f22
.. _`Wikipedia article`:
http://en.wikipedia.org/wiki/Multiple_dispatch
.. _`PEP 3124 - *Overloading, Generic Functions, Interfaces, and Adaptation*`:
http://legacy.python.org/dev/peps/pep-3124/
.. |Build Status| image:: https://travis-ci.org/mrocklin/multipledispatch.png
:target: https://travis-ci.org/mrocklin/multipledispatch
.. |Version Status| image:: https://pypip.in/v/multipledispatch/badge.png
:target: https://img.shields.io/pypi/v/multipledispatch.svg
.. |Coverage Status| image:: https://coveralls.io/repos/mrocklin/multipledispatch/badge.png
:target: https://coveralls.io/r/mrocklin/multipledispatch
.. _License file: https://github.com/mrocklin/multipledispatch/blob/master/LICENSE.txt
multipledispatch-0.6.0/bench/ 0000775 0000000 0000000 00000000000 13332627007 0016152 5 ustar 00root root 0000000 0000000 multipledispatch-0.6.0/bench/test_simple.py 0000664 0000000 0000000 00000000406 13332627007 0021054 0 ustar 00root root 0000000 0000000 import six
from multipledispatch import dispatch
@dispatch(int)
def isint(x):
return True
@dispatch(object)
def isint(x):
return False
def test_simple():
for i in six.moves.xrange(100000):
assert isint(5)
assert not isint('a')
multipledispatch-0.6.0/conda.yaml 0000664 0000000 0000000 00000000532 13332627007 0017043 0 ustar 00root root 0000000 0000000 package:
name: multipledispatch
version: "0.4.6"
build:
number: {{environ.get('BINSTAR_BUILD', 1)}}
script:
- cd $RECIPE_DIR
- $PYTHON setup.py install
requirements:
build:
- setuptools
- python
run:
- python
about:
home: https://multiple-dispatch.readthedocs.io/
license: BSD
multipledispatch-0.6.0/docs/ 0000775 0000000 0000000 00000000000 13332627007 0016023 5 ustar 00root root 0000000 0000000 multipledispatch-0.6.0/docs/Makefile 0000664 0000000 0000000 00000012755 13332627007 0017475 0 ustar 00root root 0000000 0000000 # Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make ' where is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/MultipleDispatch.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/MultipleDispatch.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/MultipleDispatch"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/MultipleDispatch"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
multipledispatch-0.6.0/docs/make.bat 0000664 0000000 0000000 00000012005 13332627007 0017426 0 ustar 00root root 0000000 0000000 @ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source
set I18NSPHINXOPTS=%SPHINXOPTS% source
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^` where ^ is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\MultipleDispatch.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\MultipleDispatch.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
:end
multipledispatch-0.6.0/docs/source/ 0000775 0000000 0000000 00000000000 13332627007 0017323 5 ustar 00root root 0000000 0000000 multipledispatch-0.6.0/docs/source/conf.py 0000664 0000000 0000000 00000022136 13332627007 0020626 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# Multiple Dispatch documentation build configuration file, created by
# sphinx-quickstart on Thu Mar 27 09:46:17 2014.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Multiple Dispatch'
copyright = u'2014, Matthew Rocklin'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.4.0'
# The full version, including alpha/beta/rc tags.
release = '0.4.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'MultipleDispatchdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'MultipleDispatch.tex', u'Multiple Dispatch Documentation',
u'Matthew Rocklin', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'multipledispatch', u'Multiple Dispatch Documentation',
[u'Matthew Rocklin'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'MultipleDispatch', u'Multiple Dispatch Documentation',
u'Matthew Rocklin', 'MultipleDispatch', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# -- Options for Epub output ---------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = u'Multiple Dispatch'
epub_author = u'Matthew Rocklin'
epub_publisher = u'Matthew Rocklin'
epub_copyright = u'2014, Matthew Rocklin'
# The language of the text. It defaults to the language option
# or en if the language is not set.
#epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []
# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []
# A list of files that should not be packed into the epub file.
#epub_exclude_files = []
# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3
# Allow duplicate toc entries.
#epub_tocdup = True
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}
multipledispatch-0.6.0/docs/source/design.rst 0000664 0000000 0000000 00000010757 13332627007 0021340 0 ustar 00root root 0000000 0000000 Design
======
Types
-----
::
signature :: [type]
a list of types
Dispatcher :: {signature: function}
A mapping of type signatures to function implementations
namespace :: {str: Dispatcher}
A mapping from function names, like 'add', to Dispatchers
Dispatchers
-----------
A ``Dispatcher`` object stores and selects between different
implementations of the same abstract operation. It selects the
appropriate implementation based on a signature, or list of types. We
build one dispatcher per abstract operation.
.. code::
f = Dispatcher('f')
At the lowest level we build normal Python functions and then add them
to the ``Dispatcher``.
.. code::
>>> def inc(x):
... return x + 1
>>> def dec(x):
... return x - 1
>>> f.add((int,), inc) # f increments integers
>>> f.add((float,), dec) # f decrements floats
>>> f(1)
2
>>> f(1.0)
0.0
Internally ``Dispatcher.dispatch`` selects the function implementation.
.. code::
>>> f.dispatch(int)
>>> f.dispatch(float)
For notational convenience dispatchers leverage Python's decorator
syntax to register functions as we define them.
.. code::
f = Dispatcher('f')
@f.register(int)
def inc(x):
return x + 1
@f.register(float)
def dec(x):
return x - 1
This is equivalent to the form above.
It adheres to the standard implemented by ``functools.singledispatch`` in
Python 3.4 (although the "functional form" of ``register`` is not supported).
As in ``singledispatch``, the ``register`` decorator returns the
undecorated function, which enables decorator stacking.
.. code::
@f.register(str)
@f.register(tuple)
def rev(x):
return x[::-1]
The Dispatcher creates a detailed docstring automatically.
To add a description of the multimethod itself,
provide it when creating the ``Dispatcher``.
.. code::
>>> f = Dispatcher('f', doc="Do something to the argument")
>>> @f.register(int)
... def inc(x):
... "Integers are incremented"
... return x + 1
>>> @f.register(float)
... def dec(x):
... "Floats are decremented"
... return x - 1
>>> @f.register(str)
... @f.register(tuple)
... def rev(x):
... # no docstring
... return x[::-1]
>>> print(f.__doc__)
Multiply dispatched method: f
Do something to the argument
Inputs:
----------------
Floats are decremented
Inputs:
--------------
Integers are incremented
Other signatures:
str
tuple
Namespaces and ``dispatch``
---------------------------
The ``dispatch`` decorator hides the creation and manipulation of
``Dispatcher`` objects from the user.
.. code::
# f = Dispatcher('f') # no need to create Dispatcher ahead of time
@dispatch(int)
def f(x):
return x + 1
@dispatch(float)
def f(x):
return x - 1
The ``dispatch`` decorator uses the name of the function to select the
appropriate ``Dispatcher`` object to which it adds the new
signature/function. When it encounters a new function name it creates a
new ``Dispatcher`` object and stores name/Dispatcher pair in a namespace
for future reference.
.. code::
# This creates and stores a new Dispatcher('g')
# namespace['g'] = Dispatcher('g')
# namespace['g'].add((int,), g)
@dispatch(int)
def g(x):
return x ** 2
We store this new ``Dispatcher`` in a *namespace*. A namespace is simply
a dictionary that maps function names like ``'g'`` to dispatcher objects
like ``Dispatcher('g')``.
By default ``dispatch`` uses the global namespace in
``multipledispatch.core.global_namespace``. If several projects use this
global namespace unwisely then conflicts may arise, causing difficult to
track down bugs. Users who desire additional security may establish
their own namespaces simply by creating a dictionary.
.. code::
my_namespace = dict()
@dispatch(int, namespace=my_namespace)
def f(x):
return x + 1
To establish a namespace for an entire project we suggest the use of
``functools.partial`` to bind the new namespace to the ``dispatch``
decorator.
.. code::
from multipledispatch import dispatch
from functools import partial
my_namespace = dict()
dispatch = partial(dispatch, namespace=my_namespace)
@dispatch(int) # Uses my_namespace rather than the global namespace
def f(x):
return x + 1
multipledispatch-0.6.0/docs/source/index.rst 0000664 0000000 0000000 00000000612 13332627007 0021163 0 ustar 00root root 0000000 0000000 .. Multiple Dispatch documentation master file, created by
sphinx-quickstart on Thu Mar 27 09:46:17 2014.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to Multiple Dispatch's documentation!
=============================================
Contents:
.. toctree::
:maxdepth: 2
design.rst
resolution.rst
multipledispatch-0.6.0/docs/source/resolution.rst 0000664 0000000 0000000 00000012307 13332627007 0022263 0 ustar 00root root 0000000 0000000 Method Resolution
=================
Multiple dispatch selects the function from the types of the inputs.
.. code::
@dispatch(int)
def f(x): # increment integers
return x + 1
@dispatch(float)
def f(x): # decrement floats
return x - 1
.. code::
>>> f(1) # 1 is an int, so increment
2
>>> f(1.0) # 1.0 is a float, so decrement
0.0
Union Types
-----------
Similarly to the builtin ``isinstance`` operation you specify multiple valid
types with a tuple.
.. code::
@dispatch((list, tuple))
def f(x):
""" Apply ``f`` to each element in a list or tuple """
return [f(y) for y in x]
.. code::
>>> f([1, 2, 3])
[2, 3, 4]
>>> f((1, 2, 3))
[2, 3, 4]
Abstract Types
--------------
You can also use abstract classes like ``Iterable`` and ``Number`` in
place of union types like ``(list, tuple)`` or ``(int, float)``.
.. code::
from collections import Iterable
# @dispatch((list, tuple))
@dispatch(Iterable)
def f(x):
""" Apply ``f`` to each element in an Iterable """
return [f(y) for y in x]
Selecting Specific Implementations
----------------------------------
If multiple valid implementations exist then we use the most specific
one. In the following example we build a function to flatten nested
iterables.
.. code::
@dispatch(Iterable)
def flatten(L):
return sum([flatten(x) for x in L], [])
@dispatch(object)
def flatten(x):
return [x]
.. code::
>>> flatten([1, 2, 3])
[1, 2, 3]
>>> flatten([1, [2], 3])
[1, 2, 3]
>>> flatten([1, 2, (3, 4), [[5]], [(6, 7), (8, 9)]])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Because strings are iterable they too will be flattened
.. code::
>>> flatten([1, 'hello', 3])
[1, 'h', 'e', 'l', 'l', 'o', 3]
We avoid this by specializing ``flatten`` to ``str``. Because ``str`` is
more specific than ``Iterable`` this function takes precedence for
strings.
.. code::
@dispatch(str)
def flatten(s):
return s
.. code::
>>> flatten([1, 'hello', 3])
[1, 'hello', 3]
The ``multipledispatch`` project depends on Python's ``issubclass``
mechanism to determine which types are more specific than others.
Multiple Inputs
---------------
All of these rules apply when we introduce multiple inputs.
.. code::
@dispatch(object, object)
def f(x, y):
return x + y
@dispatch(object, float)
def f(x, y):
""" Square the right hand side if it is a float """
return x + y**2
.. code::
>>> f(1, 10)
11
>>> f(1.0, 10.0)
101.0
Variadic Dispatch
-----------------
``multipledispatch`` supports variadic dispatch (including support for union
types) as the last set of arguments passed into the function.
Variadic signatures are specified with a single-element list containing the
type of the arguments the function takes.
For example, here's a function that takes a ``float`` followed by any number
(including 0) of either ``int`` or ``str``:
.. code::
@dispatch(float, [(int, str)])
def float_then_int_or_str(x, *args):
return x + sum(map(int, args))
.. code::
>>> f(1.0, '2', '3', 4)
10.0
>>> f(2.0, '4', 6, 8)
20.0
Ambiguities
-----------
However ambiguities arise when different implementations of a function
are equally valid
.. code::
@dispatch(float, object)
def f(x, y):
""" Square left hand side if it is a float """
return x**2 + y
.. code::
>>> f(2.0, 10.0)
?
Which result do we expect, ``2.0**2 + 10.0`` or ``2.0 + 10.0**2``? The
types of the inputs satisfy three different implementations, two of
which have equal validity
::
input types: float, float
Option 1: object, object
Option 2: object, float
Option 3: float, object
Option 1 is strictly less specific than either options 2 or 3 so we
discard it. Options 2 and 3 however are equally specific and so it is
unclear which to use.
To resolve issues like this ``multipledispatch`` inspects the type
signatures given to it and searches for ambiguities. It then raises a
warning like the following:
::
multipledispatch/dispatcher.py:74: AmbiguityWarning:
Ambiguities exist in dispatched function f
The following signatures may result in ambiguous behavior:
[object, float], [float, object]
Consider making the following additions:
@dispatch(float, float)
def f(...)
This warning occurs when you write the function and guides you to create
an implementation to break the ambiguity. In this case, a function with
signature ``(float, float)`` is more specific than either options 2 or 3
and so resolves the issue. To avoid this warning you should implement
this new function *before* the others.
.. code::
@dispatch(float, float)
def f(x, y):
...
@dispatch(float, object)
def f(x, y):
...
@dispatch(object, float)
def f(x, y):
...
If you do not resolve ambiguities by creating more specific functions
then one of the competing functions will be selected pseudo-randomly.
By default the selection is dependent on hash, so it will be consistent
during the interpreter session, but it might change from session to
session.
multipledispatch-0.6.0/multipledispatch/ 0000775 0000000 0000000 00000000000 13332627007 0020446 5 ustar 00root root 0000000 0000000 multipledispatch-0.6.0/multipledispatch/__init__.py 0000664 0000000 0000000 00000000223 13332627007 0022554 0 ustar 00root root 0000000 0000000 from .core import dispatch
from .dispatcher import (Dispatcher, halt_ordering, restart_ordering,
MDNotImplementedError)
__version__ = '0.6.0'
multipledispatch-0.6.0/multipledispatch/conflict.py 0000664 0000000 0000000 00000007510 13332627007 0022624 0 ustar 00root root 0000000 0000000 from .utils import _toposort, groupby
from .variadic import isvariadic
class AmbiguityWarning(Warning):
pass
def supercedes(a, b):
""" A is consistent and strictly more specific than B """
if len(a) < len(b):
# only case is if a is empty and b is variadic
return not a and len(b) == 1 and isvariadic(b[-1])
elif len(a) == len(b):
return all(map(issubclass, a, b))
else:
# len(a) > len(b)
p1 = 0
p2 = 0
while p1 < len(a) and p2 < len(b):
cur_a = a[p1]
cur_b = b[p2]
if not (isvariadic(cur_a) or isvariadic(cur_b)):
if not issubclass(cur_a, cur_b):
return False
p1 += 1
p2 += 1
elif isvariadic(cur_a):
assert p1 == len(a) - 1
return p2 == len(b) - 1 and issubclass(cur_a, cur_b)
elif isvariadic(cur_b):
assert p2 == len(b) - 1
if not issubclass(cur_a, cur_b):
return False
p1 += 1
return p2 == len(b) - 1 and p1 == len(a)
def consistent(a, b):
""" It is possible for an argument list to satisfy both A and B """
# Need to check for empty args
if not a:
return not b or isvariadic(b[0])
if not b:
return not a or isvariadic(a[0])
# Non-empty args check for mutual subclasses
if len(a) == len(b):
return all(issubclass(aa, bb) or issubclass(bb, aa)
for aa, bb in zip(a, b))
else:
p1 = 0
p2 = 0
while p1 < len(a) and p2 < len(b):
cur_a = a[p1]
cur_b = b[p2]
if not issubclass(cur_b, cur_a) and not issubclass(cur_a, cur_b):
return False
if not (isvariadic(cur_a) or isvariadic(cur_b)):
p1 += 1
p2 += 1
elif isvariadic(cur_a):
p2 += 1
elif isvariadic(cur_b):
p1 += 1
# We only need to check for variadic ends
# Variadic types are guaranteed to be the last element
return (isvariadic(cur_a) and p2 == len(b) or
isvariadic(cur_b) and p1 == len(a))
def ambiguous(a, b):
""" A is consistent with B but neither is strictly more specific """
return consistent(a, b) and not (supercedes(a, b) or supercedes(b, a))
def ambiguities(signatures):
""" All signature pairs such that A is ambiguous with B """
signatures = list(map(tuple, signatures))
return set((a, b) for a in signatures for b in signatures
if hash(a) < hash(b)
and ambiguous(a, b)
and not any(supercedes(c, a) and supercedes(c, b)
for c in signatures))
def super_signature(signatures):
""" A signature that would break ambiguities """
n = len(signatures[0])
assert all(len(s) == n for s in signatures)
return [max([type.mro(sig[i]) for sig in signatures], key=len)[0]
for i in range(n)]
def edge(a, b, tie_breaker=hash):
""" A should be checked before B
Tie broken by tie_breaker, defaults to ``hash``
"""
# A either supercedes B and B does not supercede A or if B does then call
# tie_breaker
return supercedes(a, b) and (
not supercedes(b, a) or tie_breaker(a) > tie_breaker(b)
)
def ordering(signatures):
""" A sane ordering of signatures to check, first to last
Topoological sort of edges as given by ``edge`` and ``supercedes``
"""
signatures = list(map(tuple, signatures))
edges = [(a, b) for a in signatures for b in signatures if edge(a, b)]
edges = groupby(lambda x: x[0], edges)
for s in signatures:
if s not in edges:
edges[s] = []
edges = dict((k, [b for a, b in v]) for k, v in edges.items())
return _toposort(edges)
multipledispatch-0.6.0/multipledispatch/core.py 0000664 0000000 0000000 00000004144 13332627007 0021753 0 ustar 00root root 0000000 0000000 import inspect
from .dispatcher import Dispatcher, MethodDispatcher, ambiguity_warn
global_namespace = dict()
def dispatch(*types, **kwargs):
""" Dispatch function on the types of the inputs
Supports dispatch on all non-keyword arguments.
Collects implementations based on the function name. Ignores namespaces.
If ambiguous type signatures occur a warning is raised when the function is
defined suggesting the additional method to break the ambiguity.
Examples
--------
>>> @dispatch(int)
... def f(x):
... return x + 1
>>> @dispatch(float)
... def f(x):
... return x - 1
>>> f(3)
4
>>> f(3.0)
2.0
Specify an isolated namespace with the namespace keyword argument
>>> my_namespace = dict()
>>> @dispatch(int, namespace=my_namespace)
... def foo(x):
... return x + 1
Dispatch on instance methods within classes
>>> class MyClass(object):
... @dispatch(list)
... def __init__(self, data):
... self.data = data
... @dispatch(int)
... def __init__(self, datum):
... self.data = [datum]
"""
namespace = kwargs.get('namespace', global_namespace)
types = tuple(types)
def _(func):
name = func.__name__
if ismethod(func):
dispatcher = inspect.currentframe().f_back.f_locals.get(
name,
MethodDispatcher(name),
)
else:
if name not in namespace:
namespace[name] = Dispatcher(name)
dispatcher = namespace[name]
dispatcher.add(types, func)
return dispatcher
return _
def ismethod(func):
""" Is func a method?
Note that this has to work as the method is defined but before the class is
defined. At this stage methods look like functions.
"""
if hasattr(inspect, "signature"):
signature = inspect.signature(func)
return signature.parameters.get('self', None) is not None
else:
spec = inspect.getargspec(func)
return spec and spec.args and spec.args[0] == 'self'
multipledispatch-0.6.0/multipledispatch/dispatcher.py 0000664 0000000 0000000 00000032372 13332627007 0023155 0 ustar 00root root 0000000 0000000 from warnings import warn
import inspect
from .conflict import ordering, ambiguities, super_signature, AmbiguityWarning
from .utils import expand_tuples
from .variadic import Variadic, isvariadic
import itertools as itl
class MDNotImplementedError(NotImplementedError):
""" A NotImplementedError for multiple dispatch """
def ambiguity_warn(dispatcher, ambiguities):
""" Raise warning when ambiguity is detected
Parameters
----------
dispatcher : Dispatcher
The dispatcher on which the ambiguity was detected
ambiguities : set
Set of type signature pairs that are ambiguous within this dispatcher
See Also:
Dispatcher.add
warning_text
"""
warn(warning_text(dispatcher.name, ambiguities), AmbiguityWarning)
def halt_ordering():
"""Deprecated interface to temporarily disable ordering.
"""
warn(
'halt_ordering is deprecated, you can safely remove this call.',
DeprecationWarning,
)
def restart_ordering(on_ambiguity=ambiguity_warn):
"""Deprecated interface to temporarily resume ordering.
"""
warn(
'restart_ordering is deprecated, if you would like to eagerly order'
'the dispatchers, you should call the ``reorder()`` method on each'
' dispatcher.',
DeprecationWarning,
)
def variadic_signature_matches_iter(types, full_signature):
"""Check if a set of input types matches a variadic signature.
Notes
-----
The algorithm is as follows:
Initialize the current signature to the first in the sequence
For each type in `types`:
If the current signature is variadic
If the type matches the signature
yield True
Else
Try to get the next signature
If no signatures are left we can't possibly have a match
so yield False
Else
yield True if the type matches the current signature
Get the next signature
"""
sigiter = iter(full_signature)
sig = next(sigiter)
for typ in types:
matches = issubclass(typ, sig)
yield matches
if not isvariadic(sig):
# we're not matching a variadic argument, so move to the next
# element in the signature
sig = next(sigiter)
else:
try:
sig = next(sigiter)
except StopIteration:
assert isvariadic(sig)
yield True
else:
# We have signature items left over, so all of our arguments
# haven't matched
yield False
def variadic_signature_matches(types, full_signature):
# No arguments always matches a variadic signature
assert full_signature
return all(variadic_signature_matches_iter(types, full_signature))
class Dispatcher(object):
""" Dispatch methods based on type signature
Use ``dispatch`` to add implementations
Examples
--------
>>> from multipledispatch import dispatch
>>> @dispatch(int)
... def f(x):
... return x + 1
>>> @dispatch(float)
... def f(x):
... return x - 1
>>> f(3)
4
>>> f(3.0)
2.0
"""
__slots__ = '__name__', 'name', 'funcs', '_ordering', '_cache', 'doc'
def __init__(self, name, doc=None):
self.name = self.__name__ = name
self.funcs = {}
self.doc = doc
self._cache = {}
def register(self, *types, **kwargs):
""" register dispatcher with new implementation
>>> f = Dispatcher('f')
>>> @f.register(int)
... def inc(x):
... return x + 1
>>> @f.register(float)
... def dec(x):
... return x - 1
>>> @f.register(list)
... @f.register(tuple)
... def reverse(x):
... return x[::-1]
>>> f(1)
2
>>> f(1.0)
0.0
>>> f([1, 2, 3])
[3, 2, 1]
"""
def _(func):
self.add(types, func, **kwargs)
return func
return _
@classmethod
def get_func_params(cls, func):
if hasattr(inspect, "signature"):
sig = inspect.signature(func)
return sig.parameters.values()
@classmethod
def get_func_annotations(cls, func):
""" get annotations of function positional parameters
"""
params = cls.get_func_params(func)
if params:
Parameter = inspect.Parameter
params = (param for param in params
if param.kind in
(Parameter.POSITIONAL_ONLY,
Parameter.POSITIONAL_OR_KEYWORD))
annotations = tuple(
param.annotation
for param in params)
if all(ann is not Parameter.empty for ann in annotations):
return annotations
def add(self, signature, func):
""" Add new types/method pair to dispatcher
>>> D = Dispatcher('add')
>>> D.add((int, int), lambda x, y: x + y)
>>> D.add((float, float), lambda x, y: x + y)
>>> D(1, 2)
3
>>> D(1, 2.0)
Traceback (most recent call last):
...
NotImplementedError: Could not find signature for add:
When ``add`` detects a warning it calls the ``on_ambiguity`` callback
with a dispatcher/itself, and a set of ambiguous type signature pairs
as inputs. See ``ambiguity_warn`` for an example.
"""
# Handle annotations
if not signature:
annotations = self.get_func_annotations(func)
if annotations:
signature = annotations
# Handle union types
if any(isinstance(typ, tuple) for typ in signature):
for typs in expand_tuples(signature):
self.add(typs, func)
return
new_signature = []
for index, typ in enumerate(signature, start=1):
if not isinstance(typ, (type, list)):
str_sig = ', '.join(c.__name__ if isinstance(c, type)
else str(c) for c in signature)
raise TypeError("Tried to dispatch on non-type: %s\n"
"In signature: <%s>\n"
"In function: %s" %
(typ, str_sig, self.name))
# handle variadic signatures
if isinstance(typ, list):
if index != len(signature):
raise TypeError(
'Variadic signature must be the last element'
)
if len(typ) != 1:
raise TypeError(
'Variadic signature must contain exactly one element. '
'To use a variadic union type place the desired types '
'inside of a tuple, e.g., [(int, str)]'
)
new_signature.append(Variadic[typ[0]])
else:
new_signature.append(typ)
self.funcs[tuple(new_signature)] = func
self._cache.clear()
try:
del self._ordering
except AttributeError:
pass
@property
def ordering(self):
try:
return self._ordering
except AttributeError:
return self.reorder()
def reorder(self, on_ambiguity=ambiguity_warn):
self._ordering = od = ordering(self.funcs)
amb = ambiguities(self.funcs)
if amb:
on_ambiguity(self, amb)
return od
def __call__(self, *args, **kwargs):
types = tuple([type(arg) for arg in args])
try:
func = self._cache[types]
except KeyError:
func = self.dispatch(*types)
if not func:
raise NotImplementedError(
'Could not find signature for %s: <%s>' %
(self.name, str_signature(types)))
self._cache[types] = func
try:
return func(*args, **kwargs)
except MDNotImplementedError:
funcs = self.dispatch_iter(*types)
next(funcs) # burn first
for func in funcs:
try:
return func(*args, **kwargs)
except MDNotImplementedError:
pass
raise NotImplementedError(
"Matching functions for "
"%s: <%s> found, but none completed successfully" % (
self.name, str_signature(types),
),
)
def __str__(self):
return "" % self.name
__repr__ = __str__
def dispatch(self, *types):
"""Deterimine appropriate implementation for this type signature
This method is internal. Users should call this object as a function.
Implementation resolution occurs within the ``__call__`` method.
>>> from multipledispatch import dispatch
>>> @dispatch(int)
... def inc(x):
... return x + 1
>>> implementation = inc.dispatch(int)
>>> implementation(3)
4
>>> print(inc.dispatch(float))
None
See Also:
``multipledispatch.conflict`` - module to determine resolution order
"""
if types in self.funcs:
return self.funcs[types]
try:
return next(self.dispatch_iter(*types))
except StopIteration:
return None
def dispatch_iter(self, *types):
n = len(types)
for signature in self.ordering:
if len(signature) == n and all(map(issubclass, types, signature)):
result = self.funcs[signature]
yield result
elif len(signature) and isvariadic(signature[-1]):
if variadic_signature_matches(types, signature):
result = self.funcs[signature]
yield result
def resolve(self, types):
""" Deterimine appropriate implementation for this type signature
.. deprecated:: 0.4.4
Use ``dispatch(*types)`` instead
"""
warn("resolve() is deprecated, use dispatch(*types)",
DeprecationWarning)
return self.dispatch(*types)
def __getstate__(self):
return {'name': self.name,
'funcs': self.funcs}
def __setstate__(self, d):
self.name = d['name']
self.funcs = d['funcs']
self._ordering = ordering(self.funcs)
self._cache = dict()
@property
def __doc__(self):
docs = ["Multiply dispatched method: %s" % self.name]
if self.doc:
docs.append(self.doc)
other = []
for sig in self.ordering[::-1]:
func = self.funcs[sig]
if func.__doc__:
s = 'Inputs: <%s>\n' % str_signature(sig)
s += '-' * len(s) + '\n'
s += func.__doc__.strip()
docs.append(s)
else:
other.append(str_signature(sig))
if other:
docs.append('Other signatures:\n ' + '\n '.join(other))
return '\n\n'.join(docs)
def _help(self, *args):
return self.dispatch(*map(type, args)).__doc__
def help(self, *args, **kwargs):
""" Print docstring for the function corresponding to inputs """
print(self._help(*args))
def _source(self, *args):
func = self.dispatch(*map(type, args))
if not func:
raise TypeError("No function found")
return source(func)
def source(self, *args, **kwargs):
""" Print source code for the function corresponding to inputs """
print(self._source(*args))
def source(func):
s = 'File: %s\n\n' % inspect.getsourcefile(func)
s = s + inspect.getsource(func)
return s
class MethodDispatcher(Dispatcher):
""" Dispatch methods based on type signature
See Also:
Dispatcher
"""
__slots__ = ('obj', 'cls')
@classmethod
def get_func_params(cls, func):
if hasattr(inspect, "signature"):
sig = inspect.signature(func)
return itl.islice(sig.parameters.values(), 1, None)
def __get__(self, instance, owner):
self.obj = instance
self.cls = owner
return self
def __call__(self, *args, **kwargs):
types = tuple([type(arg) for arg in args])
func = self.dispatch(*types)
if not func:
raise NotImplementedError('Could not find signature for %s: <%s>' %
(self.name, str_signature(types)))
return func(self.obj, *args, **kwargs)
def str_signature(sig):
""" String representation of type signature
>>> str_signature((int, float))
'int, float'
"""
return ', '.join(cls.__name__ for cls in sig)
def warning_text(name, amb):
""" The text for ambiguity warnings """
text = "\nAmbiguities exist in dispatched function %s\n\n" % (name)
text += "The following signatures may result in ambiguous behavior:\n"
for pair in amb:
text += "\t" + \
', '.join('[' + str_signature(s) + ']' for s in pair) + "\n"
text += "\n\nConsider making the following additions:\n\n"
text += '\n\n'.join(['@dispatch(' + str_signature(super_signature(s))
+ ')\ndef %s(...)' % name for s in amb])
return text
multipledispatch-0.6.0/multipledispatch/tests/ 0000775 0000000 0000000 00000000000 13332627007 0021610 5 ustar 00root root 0000000 0000000 multipledispatch-0.6.0/multipledispatch/tests/test_benchmark.py 0000664 0000000 0000000 00000002070 13332627007 0025152 0 ustar 00root root 0000000 0000000 from multipledispatch import dispatch
import pytest
@dispatch(int)
def isint(x):
return True
@dispatch(object)
def isint(x):
return False
@dispatch(object, object)
def isint(x, y):
return False
@pytest.mark.parametrize("val", [1, 'a'])
def test_benchmark_call_single_dispatch(benchmark, val):
benchmark(isint, val)
@pytest.mark.parametrize("val", [(1, 4)])
def test_benchmark_call_multiple_dispatch(benchmark, val):
benchmark(isint, *val)
def test_benchmark_add_and_use_instance(benchmark):
namespace = {}
@benchmark
def inner():
@dispatch(int, int, namespace=namespace)
def mul(x, y):
return x * y
@dispatch(str, int, namespace=namespace)
def mul(x, y):
return x * y
@dispatch(int, int, [float], namespace=namespace)
def mul(x, y, *args):
return x * y
@dispatch([int], namespace=namespace)
def mul(*args):
return sum(args)
mul(4, 5)
mul('x', 5)
mul(1, 2, 3., 4., 5.)
mul(1, 2, 3, 4, 5)
multipledispatch-0.6.0/multipledispatch/tests/test_conflict.py 0000664 0000000 0000000 00000006421 13332627007 0025025 0 ustar 00root root 0000000 0000000 from multipledispatch.conflict import (supercedes, ordering, ambiguities,
ambiguous, super_signature, consistent)
from multipledispatch.dispatcher import Variadic
class A(object): pass
class B(A): pass
class C(object): pass
def _test_supercedes(a, b):
assert supercedes(a, b)
assert not supercedes(b, a)
def test_supercedes():
_test_supercedes([B], [A])
_test_supercedes([B, A], [A, A])
def test_consistent():
assert consistent([A], [A])
assert consistent([B], [B])
assert not consistent([A], [C])
assert consistent([A, B], [A, B])
assert consistent([B, A], [A, B])
assert not consistent([B, A], [B])
assert not consistent([B, A], [B, C])
def test_super_signature():
assert super_signature([[A]]) == [A]
assert super_signature([[A], [B]]) == [B]
assert super_signature([[A, B], [B, A]]) == [B, B]
assert super_signature([[A, A, B], [A, B, A], [B, A, A]]) == [B, B, B]
def test_ambiguous():
assert not ambiguous([A], [A])
assert not ambiguous([A], [B])
assert not ambiguous([B], [B])
assert not ambiguous([A, B], [B, B])
assert ambiguous([A, B], [B, A])
def test_ambiguities():
signatures = [[A], [B], [A, B], [B, A], [A, C]]
expected = set([((A, B), (B, A))])
result = ambiguities(signatures)
assert set(map(frozenset, expected)) == set(map(frozenset, result))
signatures = [[A], [B], [A, B], [B, A], [A, C], [B, B]]
expected = set()
result = ambiguities(signatures)
assert set(map(frozenset, expected)) == set(map(frozenset, result))
def test_ordering():
signatures = [[A, A], [A, B], [B, A], [B, B], [A, C]]
ord = ordering(signatures)
assert ord[0] == (B, B) or ord[0] == (A, C)
assert ord[-1] == (A, A) or ord[-1] == (A, C)
def test_type_mro():
assert super_signature([[object], [type]]) == [type]
def test_supercedes_variadic():
_test_supercedes((Variadic[B],), (Variadic[A],))
_test_supercedes((B, Variadic[A]), (Variadic[A],))
_test_supercedes((Variadic[A],), (Variadic[(A, C)],))
_test_supercedes((A, B, Variadic[C]), (Variadic[object],))
_test_supercedes((A, Variadic[B]), (Variadic[A],))
_test_supercedes(tuple([]), (Variadic[A],))
_test_supercedes((A, A, A), (A, Variadic[A]))
def test_consistent_variadic():
# basic check
assert consistent((Variadic[A],), (Variadic[A],))
assert consistent((Variadic[B],), (Variadic[B],))
assert not consistent((Variadic[C],), (Variadic[A],))
# union types
assert consistent((Variadic[(A, C)],), (Variadic[A],))
assert consistent((Variadic[(A, C)],), (Variadic[(C, A)],))
assert consistent((Variadic[(A, B, C)],), (Variadic[(C, B, A)],))
assert consistent((A, B, C), (Variadic[(A, B, C)],))
assert consistent((A, B, C), (A, Variadic[(B, C)]))
# more complex examples
assert consistent(tuple([]), (Variadic[object],))
assert consistent((A, A, B), (A, A, Variadic[B]))
assert consistent((A, A, B), (A, A, Variadic[A]))
assert consistent((A, B, Variadic[C]), (B, A, Variadic[C]))
assert consistent((A, B, Variadic[C]), (B, A, Variadic[(C, B)]))
# not consistent
assert not consistent((C,), (Variadic[A],))
assert not consistent((A, A, Variadic[C]), (A, Variadic[C]))
assert not consistent((A, B, Variadic[C]), (C, B, Variadic[C]))
multipledispatch-0.6.0/multipledispatch/tests/test_core.py 0000664 0000000 0000000 00000006510 13332627007 0024153 0 ustar 00root root 0000000 0000000 from multipledispatch import dispatch
from multipledispatch.utils import raises
from functools import partial
test_namespace = dict()
orig_dispatch = dispatch
dispatch = partial(dispatch, namespace=test_namespace)
def test_singledispatch():
@dispatch(int)
def f(x):
return x + 1
@dispatch(int)
def g(x):
return x + 2
@dispatch(float)
def f(x):
return x - 1
assert f(1) == 2
assert g(1) == 3
assert f(1.0) == 0
assert raises(NotImplementedError, lambda: f('hello'))
def test_multipledispatch(benchmark):
@dispatch(int, int)
def f(x, y):
return x + y
@dispatch(float, float)
def f(x, y):
return x - y
assert f(1, 2) == 3
assert f(1.0, 2.0) == -1.0
class A(object): pass
class B(object): pass
class C(A): pass
class D(C): pass
class E(C): pass
def test_inheritance():
@dispatch(A)
def f(x):
return 'a'
@dispatch(B)
def f(x):
return 'b'
assert f(A()) == 'a'
assert f(B()) == 'b'
assert f(C()) == 'a'
def test_inheritance_and_multiple_dispatch():
@dispatch(A, A)
def f(x, y):
return type(x), type(y)
@dispatch(A, B)
def f(x, y):
return 0
assert f(A(), A()) == (A, A)
assert f(A(), C()) == (A, C)
assert f(A(), B()) == 0
assert f(C(), B()) == 0
assert raises(NotImplementedError, lambda: f(B(), B()))
def test_competing_solutions():
@dispatch(A)
def h(x):
return 1
@dispatch(C)
def h(x):
return 2
assert h(D()) == 2
def test_competing_multiple():
@dispatch(A, B)
def h(x, y):
return 1
@dispatch(C, B)
def h(x, y):
return 2
assert h(D(), B()) == 2
def test_competing_ambiguous():
@dispatch(A, C)
def f(x, y):
return 2
@dispatch(C, A)
def f(x, y):
return 2
assert f(A(), C()) == f(C(), A()) == 2
# assert raises(Warning, lambda : f(C(), C()))
def test_caching_correct_behavior():
@dispatch(A)
def f(x):
return 1
assert f(C()) == 1
@dispatch(C)
def f(x):
return 2
assert f(C()) == 2
def test_union_types():
@dispatch((A, C))
def f(x):
return 1
assert f(A()) == 1
assert f(C()) == 1
def test_namespaces():
ns1 = dict()
ns2 = dict()
def foo(x):
return 1
foo1 = orig_dispatch(int, namespace=ns1)(foo)
def foo(x):
return 2
foo2 = orig_dispatch(int, namespace=ns2)(foo)
assert foo1(0) == 1
assert foo2(0) == 2
"""
Fails
def test_dispatch_on_dispatch():
@dispatch(A)
@dispatch(C)
def q(x):
return 1
assert q(A()) == 1
assert q(C()) == 1
"""
def test_methods():
class Foo(object):
@dispatch(float)
def f(self, x):
return x - 1
@dispatch(int)
def f(self, x):
return x + 1
@dispatch(int)
def g(self, x):
return x + 3
foo = Foo()
assert foo.f(1) == 2
assert foo.f(1.0) == 0.0
assert foo.g(1) == 4
def test_methods_multiple_dispatch():
class Foo(object):
@dispatch(A, A)
def f(x, y):
return 1
@dispatch(A, C)
def f(x, y):
return 2
foo = Foo()
assert foo.f(A(), A()) == 1
assert foo.f(A(), C()) == 2
assert foo.f(C(), C()) == 2
multipledispatch-0.6.0/multipledispatch/tests/test_dispatcher.py 0000664 0000000 0000000 00000021036 13332627007 0025351 0 ustar 00root root 0000000 0000000
import warnings
from multipledispatch.dispatcher import (Dispatcher, MDNotImplementedError,
MethodDispatcher)
from multipledispatch.conflict import ambiguities
from multipledispatch.utils import raises
def identity(x):
return x
def inc(x):
return x + 1
def dec(x):
return x - 1
def test_dispatcher():
f = Dispatcher('f')
f.add((int,), inc)
f.add((float,), dec)
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
assert f.resolve((int,)) == inc
assert f.dispatch(int) is inc
assert f(1) == 2
assert f(1.0) == 0.0
def test_union_types():
f = Dispatcher('f')
f.register((int, float))(inc)
assert f(1) == 2
assert f(1.0) == 2.0
def test_dispatcher_as_decorator():
f = Dispatcher('f')
@f.register(int)
def inc(x):
return x + 1
@f.register(float)
def dec(x):
return x - 1
assert f(1) == 2
assert f(1.0) == 0.0
def test_register_instance_method():
class Test(object):
__init__ = MethodDispatcher('f')
@__init__.register(list)
def _init_list(self, data):
self.data = data
@__init__.register(object)
def _init_obj(self, datum):
self.data = [datum]
a = Test(3)
b = Test([3])
assert a.data == b.data
def test_on_ambiguity():
f = Dispatcher('f')
def identity(x):
return x
ambiguities = [False]
def on_ambiguity(dispatcher, amb):
ambiguities[0] = True
f.add((object, object), identity)
f.add((object, float), identity)
f.add((float, object), identity)
assert not ambiguities[0]
f.reorder(on_ambiguity=on_ambiguity)
assert ambiguities[0]
def test_serializable():
f = Dispatcher('f')
f.add((int,), inc)
f.add((float,), dec)
f.add((object,), identity)
import pickle
assert isinstance(pickle.dumps(f), (str, bytes))
g = pickle.loads(pickle.dumps(f))
assert g(1) == 2
assert g(1.0) == 0.0
assert g('hello') == 'hello'
def test_raise_error_on_non_class():
f = Dispatcher('f')
assert raises(TypeError, lambda: f.add((1,), inc))
def test_docstring():
def one(x, y):
""" Docstring number one """
return x + y
def two(x, y):
""" Docstring number two """
return x + y
def three(x, y):
return x + y
master_doc = 'Doc of the multimethod itself'
f = Dispatcher('f', doc=master_doc)
f.add((object, object), one)
f.add((int, int), two)
f.add((float, float), three)
assert one.__doc__.strip() in f.__doc__
assert two.__doc__.strip() in f.__doc__
assert (
f.__doc__.find(one.__doc__.strip()) <
f.__doc__.find(two.__doc__.strip())
)
assert 'object, object' in f.__doc__
assert master_doc in f.__doc__
def test_help():
def one(x, y):
""" Docstring number one """
return x + y
def two(x, y):
""" Docstring number two """
return x + y
def three(x, y):
""" Docstring number three """
return x + y
master_doc = 'Doc of the multimethod itself'
f = Dispatcher('f', doc=master_doc)
f.add((object, object), one)
f.add((int, int), two)
f.add((float, float), three)
assert f._help(1, 1) == two.__doc__
assert f._help(1.0, 2.0) == three.__doc__
def test_source():
def one(x, y):
""" Docstring number one """
return x + y
def two(x, y):
""" Docstring number two """
return x - y
master_doc = 'Doc of the multimethod itself'
f = Dispatcher('f', doc=master_doc)
f.add((int, int), one)
f.add((float, float), two)
assert 'x + y' in f._source(1, 1)
assert 'x - y' in f._source(1.0, 1.0)
def test_source_raises_on_missing_function():
f = Dispatcher('f')
assert raises(TypeError, lambda: f.source(1))
def test_no_implementations():
f = Dispatcher('f')
assert raises(NotImplementedError, lambda: f('hello'))
def test_register_stacking():
f = Dispatcher('f')
@f.register(list)
@f.register(tuple)
def rev(x):
return x[::-1]
assert f((1, 2, 3)) == (3, 2, 1)
assert f([1, 2, 3]) == [3, 2, 1]
assert raises(NotImplementedError, lambda: f('hello'))
assert rev('hello') == 'olleh'
def test_dispatch_method():
f = Dispatcher('f')
@f.register(list)
def rev(x):
return x[::-1]
@f.register(int, int)
def add(x, y):
return x + y
class MyList(list):
pass
assert f.dispatch(list) is rev
assert f.dispatch(MyList) is rev
assert f.dispatch(int, int) is add
def test_not_implemented():
f = Dispatcher('f')
@f.register(object)
def _1(x):
return 'default'
@f.register(int)
def _2(x):
if x % 2 == 0:
return 'even'
else:
raise MDNotImplementedError()
assert f('hello') == 'default' # default behavior
assert f(2) == 'even' # specialized behavior
assert f(3) == 'default' # fall back to default behavior
assert raises(NotImplementedError, lambda: f(1, 2))
def test_not_implemented_error():
f = Dispatcher('f')
@f.register(float)
def _(a):
raise MDNotImplementedError()
assert raises(NotImplementedError, lambda: f(1.0))
def test_vararg_not_last_element_of_signature():
f = Dispatcher('f')
assert raises(TypeError, lambda: f.register([float], str)(lambda: None))
def test_vararg_has_multiple_elements():
f = Dispatcher('f')
assert raises(TypeError, lambda: f.register([float, str])(lambda: None))
def test_vararg_dispatch_simple():
f = Dispatcher('f')
@f.register([float])
def _1(*args):
return args
assert f(1.0) == (1.0,)
assert f(1.0, 2.0, 3.0) == (1.0, 2.0, 3.0)
def test_vararg_dispatch_ambiguity():
f = Dispatcher('f')
@f.register(float, object, [int])
def _1(a, b, *args):
return 1
@f.register(object, float, [int])
def _2(a, b, *args):
return 2
assert ambiguities(f.funcs)
def test_vararg_dispatch_ambiguity_in_variadic():
f = Dispatcher('f')
@f.register(float, [object])
def _1(a, b, *args):
return 1
@f.register(object, [float])
def _2(a, b, *args):
return 2
assert ambiguities(f.funcs)
def test_vararg_dispatch_multiple_types_explicit_args():
f = Dispatcher('f')
@f.register(str, [float])
def _1(a, *b):
return (a, b)
result = f('a', 1.0, 2.0, 3.0)
assert result == ('a', (1.0, 2.0, 3.0))
def test_vararg_dispatch_multiple_implementations():
f = Dispatcher('f')
@f.register(str, [float])
def _1(a, *b):
return 'mixed_string_floats'
@f.register([float])
def _2(*b):
return 'floats'
@f.register([str])
def _3(*strings):
return 'strings'
assert f('a', 1.0, 2.0) == 'mixed_string_floats'
assert f(1.0, 2.0, 3.14) == 'floats'
assert f('a', 'b', 'c') == 'strings'
def test_vararg_dispatch_unions():
f = Dispatcher('f')
@f.register(str, [(int, float)])
def _1(a, *b):
return 'mixed_string_ints_floats'
@f.register([str])
def _2(*strings):
return 'strings'
@f.register([(str, int)])
def _3(*strings_ints):
return 'mixed_strings_ints'
@f.register([object])
def _4(*objects):
return 'objects'
assert f('a', 1.0, 7, 2.0, 11) == 'mixed_string_ints_floats'
assert f('a', 'b', 'c') == 'strings'
assert f('a', 1, 'b', 2) == 'mixed_strings_ints'
assert f([], (), {}) == 'objects'
def test_vararg_no_args():
f = Dispatcher('f')
@f.register([str])
def _1(*strings):
return 'strings'
assert f() == 'strings'
def test_vararg_no_args_failure():
f = Dispatcher('f')
@f.register(str, [str])
def _2(*strings):
return 'strings'
assert raises(NotImplementedError, f)
def test_vararg_no_args_failure():
f = Dispatcher('f')
@f.register([str])
def _2(*strings):
return 'strings'
assert raises(NotImplementedError, lambda: f('a', 'b', 1))
def test_vararg_ordering():
f = Dispatcher('f')
@f.register(str, int, [object])
def _1(string, integer, *objects):
return 1
@f.register(str, [object])
def _2(string, *objects):
return 2
@f.register([object])
def _3(*objects):
return 3
assert f('a', 1) == 1
assert f('a', 1, ['a']) == 1
assert f('a', 1, 'a') == 1
assert f('a', 'a') == 2
assert f('a') == 2
assert f('a', ['a']) == 2
assert f(1) == 3
assert f() == 3
multipledispatch-0.6.0/multipledispatch/tests/test_dispatcher_3only.py 0000664 0000000 0000000 00000003175 13332627007 0026501 0 ustar 00root root 0000000 0000000 # import sys
# from nose import SkipTest
from multipledispatch import dispatch
from multipledispatch.dispatcher import Dispatcher
def test_function_annotation_register():
f = Dispatcher('f')
@f.register()
def inc(x: int):
return x + 1
@f.register()
def inc(x: float):
return x - 1
assert f(1) == 2
assert f(1.0) == 0.0
def test_function_annotation_dispatch():
@dispatch()
def inc(x: int):
return x + 1
@dispatch()
def inc(x: float):
return x - 1
assert inc(1) == 2
assert inc(1.0) == 0.0
def test_function_annotation_dispatch_custom_namespace():
namespace = {}
@dispatch(namespace=namespace)
def inc(x: int):
return x + 2
@dispatch(namespace=namespace)
def inc(x: float):
return x - 2
assert inc(1) == 3
assert inc(1.0) == -1.0
assert namespace['inc'] == inc
assert set(inc.funcs.keys()) == set([(int,), (float,)])
def test_method_annotations():
class Foo():
@dispatch()
def f(self, x: int):
return x + 1
@dispatch()
def f(self, x: float):
return x - 1
foo = Foo()
assert foo.f(1) == 2
assert foo.f(1.0) == 0.0
def test_overlaps():
@dispatch(int)
def inc(x: int):
return x + 1
@dispatch(float)
def inc(x: float):
return x - 1
assert inc(1) == 2
assert inc(1.0) == 0.0
def test_overlaps_conflict_annotation():
@dispatch(int)
def inc(x: str):
return x + 1
@dispatch(float)
def inc(x: int):
return x - 1
assert inc(1) == 2
assert inc(1.0) == 0.0
multipledispatch-0.6.0/multipledispatch/tests/test_variadic.py 0000664 0000000 0000000 00000001237 13332627007 0025006 0 ustar 00root root 0000000 0000000 from multipledispatch.variadic import isvariadic, Variadic
class A(object): pass
class B(A): pass
class C(object): pass
def test_is_variadic():
assert isvariadic(Variadic[A])
assert not isvariadic(A)
def test_equals_simple():
type_a = Variadic[A]
type_b = Variadic[B]
other_type_a = Variadic[A]
assert type_a == other_type_a
assert not type_a == type_b
def test_equals_union():
union_a_b = Variadic[(A, B)]
union_b_a = Variadic[(B, A)]
union_a_b_c = Variadic[(A, B, C)]
union_c_b_a = Variadic[(C, B, A)]
assert union_a_b == union_b_a
assert union_a_b_c == union_c_b_a
assert not union_a_b == union_a_b_c
multipledispatch-0.6.0/multipledispatch/utils.py 0000664 0000000 0000000 00000007056 13332627007 0022170 0 ustar 00root root 0000000 0000000 from collections import OrderedDict
def raises(err, lamda):
try:
lamda()
return False
except err:
return True
def expand_tuples(L):
"""
>>> expand_tuples([1, (2, 3)])
[(1, 2), (1, 3)]
>>> expand_tuples([1, 2])
[(1, 2)]
"""
if not L:
return [()]
elif not isinstance(L[0], tuple):
rest = expand_tuples(L[1:])
return [(L[0],) + t for t in rest]
else:
rest = expand_tuples(L[1:])
return [(item,) + t for t in rest for item in L[0]]
# Taken from theano/theano/gof/sched.py
# Avoids licensing issues because this was written by Matthew Rocklin
def _toposort(edges):
""" Topological sort algorithm by Kahn [1] - O(nodes + vertices)
inputs:
edges - a dict of the form {a: {b, c}} where b and c depend on a
outputs:
L - an ordered list of nodes that satisfy the dependencies of edges
>>> _toposort({1: (2, 3), 2: (3, )})
[1, 2, 3]
Closely follows the wikipedia page [2]
[1] Kahn, Arthur B. (1962), "Topological sorting of large networks",
Communications of the ACM
[2] http://en.wikipedia.org/wiki/Toposort#Algorithms
"""
incoming_edges = reverse_dict(edges)
incoming_edges = OrderedDict((k, set(val))
for k, val in incoming_edges.items())
S = OrderedDict.fromkeys(v for v in edges if v not in incoming_edges)
L = []
while S:
n, _ = S.popitem()
L.append(n)
for m in edges.get(n, ()):
assert n in incoming_edges[m]
incoming_edges[m].remove(n)
if not incoming_edges[m]:
S[m] = None
if any(incoming_edges.get(v, None) for v in edges):
raise ValueError("Input has cycles")
return L
def reverse_dict(d):
"""Reverses direction of dependence dict
>>> d = {'a': (1, 2), 'b': (2, 3), 'c':()}
>>> reverse_dict(d) # doctest: +SKIP
{1: ('a',), 2: ('a', 'b'), 3: ('b',)}
:note: dict order are not deterministic. As we iterate on the
input dict, it make the output of this function depend on the
dict order. So this function output order should be considered
as undeterministic.
"""
result = OrderedDict()
for key in d:
for val in d[key]:
result[val] = result.get(val, tuple()) + (key, )
return result
# Taken from toolz
# Avoids licensing issues because this version was authored by Matthew Rocklin
def groupby(func, seq):
""" Group a collection by a key function
>>> names = ['Alice', 'Bob', 'Charlie', 'Dan', 'Edith', 'Frank']
>>> groupby(len, names) # doctest: +SKIP
{3: ['Bob', 'Dan'], 5: ['Alice', 'Edith', 'Frank'], 7: ['Charlie']}
>>> iseven = lambda x: x % 2 == 0
>>> groupby(iseven, [1, 2, 3, 4, 5, 6, 7, 8]) # doctest: +SKIP
{False: [1, 3, 5, 7], True: [2, 4, 6, 8]}
See Also:
``countby``
"""
d = OrderedDict()
for item in seq:
key = func(item)
if key not in d:
d[key] = list()
d[key].append(item)
return d
def typename(type):
"""Get the name of `type`.
Parameters
----------
type : Union[Type, Tuple[Type]]
Returns
-------
str
The name of `type` or a tuple of the names of the types in `type`.
Examples
--------
>>> typename(int)
'int'
>>> typename((int, float))
'(int, float)'
"""
try:
return type.__name__
except AttributeError:
if len(type) == 1:
return typename(*type)
return '(%s)' % ', '.join(map(typename, type))
multipledispatch-0.6.0/multipledispatch/variadic.py 0000664 0000000 0000000 00000005300 13332627007 0022600 0 ustar 00root root 0000000 0000000 import six
from .utils import typename
class VariadicSignatureType(type):
# checking if subclass is a subclass of self
def __subclasscheck__(self, subclass):
other_type = (subclass.variadic_type if isvariadic(subclass)
else (subclass,))
return subclass is self or all(
issubclass(other, self.variadic_type) for other in other_type
)
def __eq__(self, other):
"""
Return True if other has the same variadic type
Parameters
----------
other : object (type)
The object (type) to check
Returns
-------
bool
Whether or not `other` is equal to `self`
"""
return (isvariadic(other) and
set(self.variadic_type) == set(other.variadic_type))
def __hash__(self):
return hash((type(self), frozenset(self.variadic_type)))
def isvariadic(obj):
"""Check whether the type `obj` is variadic.
Parameters
----------
obj : type
The type to check
Returns
-------
bool
Whether or not `obj` is variadic
Examples
--------
>>> isvariadic(int)
False
>>> isvariadic(Variadic[int])
True
"""
return isinstance(obj, VariadicSignatureType)
class VariadicSignatureMeta(type):
"""A metaclass that overrides ``__getitem__`` on the class. This is used to
generate a new type for Variadic signatures. See the Variadic class for
examples of how this behaves.
"""
def __getitem__(self, variadic_type):
if not (isinstance(variadic_type, (type, tuple)) or type(variadic_type)):
raise ValueError("Variadic types must be type or tuple of types"
" (Variadic[int] or Variadic[(int, float)]")
if not isinstance(variadic_type, tuple):
variadic_type = variadic_type,
return VariadicSignatureType(
'Variadic[%s]' % typename(variadic_type),
(),
dict(variadic_type=variadic_type, __slots__=())
)
class Variadic(six.with_metaclass(VariadicSignatureMeta)):
"""A class whose getitem method can be used to generate a new type
representing a specific variadic signature.
Examples
--------
>>> Variadic[int] # any number of int arguments
>>> Variadic[(int, str)] # any number of one of int or str arguments
>>> issubclass(int, Variadic[int])
True
>>> issubclass(int, Variadic[(int, str)])
True
>>> issubclass(str, Variadic[(int, str)])
True
>>> issubclass(float, Variadic[(int, str)])
False
"""
multipledispatch-0.6.0/release-notes.txt 0000664 0000000 0000000 00000001642 13332627007 0020405 0 ustar 00root root 0000000 0000000 0.1.0 - first release
0.2.0 - static analysis
0.3.0 - dispatch on instance methods
0.4.0 - support for namespaces
register methods a la singledispatch
documentation
Faster caching performance
0.4.1 - expose ambiguity response via callback
Improve NotImplemented error messages to include missing signature
0.4.2 - Dispatcher is serializable
0.4.3 - Dispatcher.register handles union types
(previously only @dispatch covered this)
0.4.4 - Docstrings
Better error handling on bad type inputs
0.4.5 - halt_reordering function to stop reordering after each declaration
0.4.6 - Rename Dispatcher.resolve to Dispatcher.dispatch to adhere to
singledispatch api. Also change to variadic args
.dispatch returns None rather than raising an error on null result
0.4.7 - MDNotImplementedError allows Dispatchers to continue on to the
next-most-specific implementation
multipledispatch-0.6.0/setup.py 0000775 0000000 0000000 00000001124 13332627007 0016606 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
from os.path import exists
from setuptools import setup
import multipledispatch
setup(name='multipledispatch',
version=multipledispatch.__version__,
description='Multiple dispatch',
url='http://github.com/mrocklin/multipledispatch/',
author='Matthew Rocklin',
author_email='mrocklin@gmail.com',
install_requires=['six'],
license='BSD',
keywords='dispatch',
packages=['multipledispatch'],
long_description=(open('README.rst').read() if exists('README.rst')
else ''),
zip_safe=False)