Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
rfrowe committed Jun 12, 2020
0 parents commit 10f8b20
Show file tree
Hide file tree
Showing 15 changed files with 1,530 additions and 0 deletions.
27 changes: 27 additions & 0 deletions .github/workflows/publish.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: Publish Python Package

on:
release:
types: [published]

jobs:
deploy:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.8'
- name: Install dependencies
run: |
python -m pip install --upgrade pip setuptools pipenv
pipenv install --dev
- name: Build and publish
env:
TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}
TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
run: |
pipenv run python setup.py sdist
pipenv run twine upload dist/*
27 changes: 27 additions & 0 deletions .github/workflows/push.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: Push CI

on: [push, pull_request]

jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.7, 3.8]

steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install -U pip pipenv
pipenv install --dev
- name: Lint with flake8
uses: grantmcconnaughey/[email protected]
if: github.event_name == 'pull_request'
- name: Unit tests
run: |
pipenv run python -m unittest
133 changes: 133 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# IntelliJ
.DS_Store
.idea
13 changes: 13 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Copyright 2020 Xevo Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
10 changes: 10 additions & 0 deletions Pipfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[[source]]
name = 'pypi'
url = 'https://pypi.org/simple'
verify_ssl = true

[packages]
dynamic_dispatch = {editable = true, path = '.'}

[dev-packages]
dynamic_dispatch = {editable = true, path = '.', extras = ['dev']}
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Dynamic Dispatch

![Build status](https://img.shields.io/github/workflow/status/XevoInc/dynamic_dispatch/Push%20CI/master)
[![PyPI](https://img.shields.io/pypi/v/dynamic-dispatch)](https://pypi.org/project/dynamic-dispatch/)
![PyPI - License](https://img.shields.io/pypi/l/dynamic-dispatch)

A lightweight, dynamic dispatch implementation for classes and functions. This allows a class or function to delegate
its implementation conditioned on the value of its first argument. This is similar to `functools.singledispatch`,
however this library dispatches over value while the other dispatches over type.

## Install

You may install this via the [`dynamic-dispatch`](https://pypi.org/project/dynamic-dispatch/) package on [PyPi](https://pypi.org):

```bash
pip3 install dynamic-dispatch
```

## Usage


## Development

When developing, it is recommended to use Pipenv. To create your development environment:

```bash
pipenv install --dev
```

### Testing

This library uses the `unittest` framework. Tests may be run with the following:

```bash
python3 -m unittest
```
97 changes: 97 additions & 0 deletions dynamic_dispatch/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
""" Like functools.singledispatch, but dynamic, value-based dispatch. """

__all__ = ('dynamic_dispatch',)

import functools
import inspect

from typing import Union, Callable, Type, Hashable

from dynamic_dispatch._class import class_dispatch
from dynamic_dispatch._func import func_dispatch

from ._typeguard import typechecked


@typechecked(always=True)
def dynamic_dispatch(func: Union[Callable, Type, None] = None, *, default: bool = False):
"""
Value-based dynamic-dispatch class decorator.
Allows a class or function to have different implementations depending on the
value of func's first parameter. The decorated class or function can act as
the default implementation, if desired.
Additional implementations may be registered for dispatch using the register()
attribute of the dispatch class or function. If the implementation has a param
of the same name as the first of func, it will be passed along.
:Example:
>>> @dynamic_dispatch(default=True)
>>> def foo(bar: int):
>>> print(bar)
>>>
>>> @foo.dispatch(on=5)
>>> def _(bar: int, baz: int):
>>> print(bar * baz)
>>>
>>> @foo.dispatch(on=10)
>>> def _():
>>> print(-10)
>>>
>>> foo(1)
1
>>> foo(5, 10)
50
>>> foo(10)
-10
:Example:
>>> @dynamic_dispatch(default=True)
>>> class Foo:
>>> def __init__(self, foo: int):
>>> super().__init__()
>>> print(bar)
>>>
>>> @Foo.dispatch(foo=5)
>>> class Bar(Foo):
>>> def __init__(self, foo, bar):
>>> super().__init__(foo)
>>> print(foo * bar)
>>>
>>> Foo(1)
1
<__main__.Foo object at ...>
>>> Foo(5, 10)
50
<__main__.Bar object at ...>
:param func: class or function to add dynamic dispatch to.
:param default: whether or not to use func as the default implementation.
:returns: func with dynamic dispatch
"""
# Default was specified, wait until func is here too.
if func is None:
return functools.partial(dynamic_dispatch, default=default)

# Delegate depending on wrap type.
if inspect.isclass(func):
return class_dispatch(func, default)

func = func_dispatch(func, default=default)

# Alter register to hide implicit parameter.
dispatch = func.dispatch

def replacement(impl: Callable = None, *, on: Hashable):
if impl is None:
return functools.partial(replacement, on=on)

return dispatch(impl, arguments=inspect.signature(impl).parameters, on=on)

# Type checker complains if we assign directly.
setattr(func, 'dispatch', replacement)

return func
Loading

0 comments on commit 10f8b20

Please sign in to comment.