├── .editorconfig ├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── docs ├── Makefile ├── authors.rst ├── conf.py ├── contributing.rst ├── history.rst ├── index.rst ├── installation.rst ├── make.bat ├── readme.rst └── usage.rst ├── pymaybe └── __init__.py ├── requirements.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py └── test_pymaybe.py └── tox.ini /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | indent_size = 4 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | charset = utf-8 11 | end_of_line = lf 12 | 13 | [*.bat] 14 | indent_style = tab 15 | end_of_line = crlf 16 | 17 | [LICENSE] 18 | insert_final_newline = false 19 | 20 | [Makefile] 21 | indent_style = tab 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | 21 | # Installer logs 22 | pip-log.txt 23 | 24 | # Unit test / coverage reports 25 | .coverage 26 | .tox 27 | nosetests.xml 28 | htmlcov 29 | 30 | # Translations 31 | *.mo 32 | 33 | # Mr Developer 34 | .mr.developer.cfg 35 | .project 36 | .pydevproject 37 | 38 | # Complexity 39 | output/*.html 40 | output/*/index.html 41 | 42 | # Sphinx 43 | docs/_build 44 | 45 | # PyCharm 46 | .idea 47 | 48 | # Virtualenv 49 | .venv 50 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Config file for automatic testing at travis-ci.org 2 | 3 | language: python 4 | 5 | python: 6 | - "3.4" 7 | - "3.3" 8 | - "2.7" 9 | - "2.6" 10 | - "pypy" 11 | - "pypy3" 12 | 13 | cache: 14 | pip: true 15 | 16 | # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors 17 | install: 18 | - pip install -U pip 19 | - pip install coveralls 20 | - pip install -r requirements.txt 21 | 22 | # command to run tests, e.g. python setup.py test 23 | script: coverage run --source pymaybe setup.py test 24 | 25 | after_success: coveralls 26 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | * Eran Kampf - http://www.developerzen.com 6 | 7 | Contributors 8 | ------------ 9 | 10 | None yet. Why not be the first? 11 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Contributing 3 | ============ 4 | 5 | Contributions are welcome, and they are greatly appreciated! Every 6 | little bit helps, and credit will always be given. 7 | 8 | You can contribute in many ways: 9 | 10 | Types of Contributions 11 | ---------------------- 12 | 13 | Report Bugs 14 | ~~~~~~~~~~~ 15 | 16 | Report bugs at https://github.com/ekampf/pymaybe/issues. 17 | 18 | If you are reporting a bug, please include: 19 | 20 | * Your operating system name and version. 21 | * Any details about your local setup that might be helpful in troubleshooting. 22 | * Detailed steps to reproduce the bug. 23 | 24 | Fix Bugs 25 | ~~~~~~~~ 26 | 27 | Look through the GitHub issues for bugs. Anything tagged with "bug" 28 | is open to whoever wants to implement it. 29 | 30 | Implement Features 31 | ~~~~~~~~~~~~~~~~~~ 32 | 33 | Look through the GitHub issues for features. Anything tagged with "feature" 34 | is open to whoever wants to implement it. 35 | 36 | Write Documentation 37 | ~~~~~~~~~~~~~~~~~~~ 38 | 39 | PyMaybe could always use more documentation, whether as part of the 40 | official PyMaybe docs, in docstrings, or even on the web in blog posts, 41 | articles, and such. 42 | 43 | Submit Feedback 44 | ~~~~~~~~~~~~~~~ 45 | 46 | The best way to send feedback is to file an issue at https://github.com/ekampf/pymaybe/issues. 47 | 48 | If you are proposing a feature: 49 | 50 | * Explain in detail how it would work. 51 | * Keep the scope as narrow as possible, to make it easier to implement. 52 | * Remember that this is a volunteer-driven project, and that contributions 53 | are welcome :) 54 | 55 | Get Started! 56 | ------------ 57 | 58 | Ready to contribute? Here's how to set up `pymaybe` for local development. 59 | 60 | 1. Fork the `pymaybe` repo on GitHub. 61 | 2. Clone your fork locally:: 62 | 63 | $ git clone git@github.com:your_name_here/pymaybe.git 64 | 65 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 66 | 67 | $ mkvirtualenv pymaybe 68 | $ cd pymaybe/ 69 | $ python setup.py develop 70 | 71 | 4. Create a branch for local development:: 72 | 73 | $ git checkout -b name-of-your-bugfix-or-feature 74 | 75 | Now you can make your changes locally. 76 | 77 | 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: 78 | 79 | $ flake8 pymaybe tests 80 | $ python setup.py test 81 | $ tox 82 | 83 | To get flake8 and tox, just pip install them into your virtualenv. 84 | 85 | 6. Commit your changes and push your branch to GitHub:: 86 | 87 | $ git add . 88 | $ git commit -m "Your detailed description of your changes." 89 | $ git push origin name-of-your-bugfix-or-feature 90 | 91 | 7. Submit a pull request through the GitHub website. 92 | 93 | Pull Request Guidelines 94 | ----------------------- 95 | 96 | Before you submit a pull request, check that it meets these guidelines: 97 | 98 | 1. The pull request should include tests. 99 | 2. If the pull request adds functionality, the docs should be updated. Put 100 | your new functionality into a function with a docstring, and add the 101 | feature to the list in README.rst. 102 | 3. The pull request should work for Python 2.6, 2.7, 3.3, and 3.4, and for PyPy. Check 103 | https://travis-ci.org/ekampf/pymaybe/pull_requests 104 | and make sure that the tests pass for all supported Python versions. 105 | 106 | Tips 107 | ---- 108 | 109 | To run a subset of tests:: 110 | 111 | $ python -m unittest tests.test_pymaybe 112 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | History 4 | ------- 5 | 6 | 0.1.0 (2015-01-11) 7 | --------------------- 8 | 9 | * First release on PyPI. 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015, Eran Kampf 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 5 | 6 | * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 7 | 8 | * 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. 9 | 10 | * Neither the name of PyMaybe nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 | 12 | 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 HOLDER 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. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CONTRIBUTING.rst 3 | include HISTORY.rst 4 | include LICENSE 5 | include README.rst 6 | 7 | recursive-include tests * 8 | recursive-exclude * __pycache__ 9 | recursive-exclude * *.py[co] 10 | 11 | recursive-include docs *.rst conf.py Makefile make.bat 12 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean-pyc clean-build docs clean 2 | 3 | help: 4 | @echo "clean - remove all build, test, coverage and Python artifacts" 5 | @echo "clean-build - remove build artifacts" 6 | @echo "clean-pyc - remove Python file artifacts" 7 | @echo "clean-test - remove test and coverage artifacts" 8 | @echo "lint - check style with flake8" 9 | @echo "test - run tests quickly with the default Python" 10 | @echo "test-all - run tests on every Python version with tox" 11 | @echo "coverage - check code coverage quickly with the default Python" 12 | @echo "docs - generate Sphinx HTML documentation, including API docs" 13 | @echo "release - package and upload a release" 14 | @echo "dist - package" 15 | @echo "install - install the package to the active Python's site-packages" 16 | 17 | .venv: 18 | if [ ! -e ".venv/bin/activate_this.py" ] ; then virtualenv --clear .venv ; fi 19 | 20 | deps: .venv 21 | PYTHONPATH=.venv ; . .venv/bin/activate && .venv/bin/pip install -U -r requirements.txt 22 | 23 | clean: clean-build clean-pyc clean-test 24 | 25 | clean-build: 26 | rm -fr build/ 27 | rm -fr dist/ 28 | rm -fr .eggs/ 29 | find . -name '*.egg-info' -exec rm -fr {} + 30 | find . -name '*.egg' -exec rm -f {} + 31 | 32 | clean-pyc: 33 | find . -name '*.pyc' -exec rm -f {} + 34 | find . -name '*.pyo' -exec rm -f {} + 35 | find . -name '*~' -exec rm -f {} + 36 | find . -name '__pycache__' -exec rm -fr {} + 37 | 38 | clean-test: 39 | rm -fr .tox/ 40 | rm -f .coverage 41 | rm -fr htmlcov/ 42 | 43 | lint: 44 | PYTHONPATH=$PYTHONPATH:.venv:. ; . .venv/bin/activate && flake8 pymaybe tests 45 | 46 | test: 47 | PYTHONPATH=$PYTHONPATH:.venv:. . .venv/bin/activate && python setup.py test 48 | 49 | test-all: 50 | PYTHONPATH=$PYTHONPATH:.venv:. . .venv/bin/activate && tox 51 | 52 | coverage: 53 | PYTHONPATH=$PYTHONPATH:.venv:. ; . .venv/bin/activate && coverage run --source pymaybe setup.py test 54 | PYTHONPATH=$PYTHONPATH:.venv:. ; . .venv/bin/activate && coverage report -m 55 | PYTHONPATH=$PYTHONPATH:.venv:. ; . .venv/bin/activate && coverage html 56 | PYTHONPATH=$PYTHONPATH:.venv:. ; . .venv/bin/activate && open htmlcov/index.html 57 | 58 | docs: 59 | rm -f docs/pymaybe.rst 60 | rm -f docs/modules.rst 61 | sphinx-apidoc -o docs/ pymaybe 62 | $(MAKE) -C docs clean 63 | $(MAKE) -C docs html 64 | open docs/_build/html/index.html 65 | 66 | release: clean 67 | PYTHONPATH=$PYTHONPATH:.venv:. ; . .venv/bin/activate && python setup.py sdist upload 68 | PYTHONPATH=$PYTHONPATH:.venv:. ; . .venv/bin/activate && python setup.py bdist_wheel upload 69 | 70 | dist: clean 71 | PYTHONPATH=$PYTHONPATH:.venv:. ; . .venv/bin/activate && python setup.py sdist 72 | PYTHONPATH=$PYTHONPATH:.venv:. ; . .venv/bin/activate && python setup.py bdist_wheel 73 | ls -l dist 74 | 75 | install: clean 76 | PYTHONPATH=$PYTHONPATH:.venv:. ; . .venv/bin/activate && python setup.py install 77 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | =============================== 2 | PyMaybe 3 | =============================== 4 | 5 | .. image:: https://travis-ci.org/ekampf/pymaybe.svg?branch=master 6 | :target: https://travis-ci.org/ekampf/pymaybe 7 | 8 | .. image:: https://coveralls.io/repos/ekampf/pymaybe/badge.svg?branch=master&service=github 9 | :target: https://coveralls.io/github/ekampf/pymaybe?branch=master 10 | 11 | .. image:: https://img.shields.io/pypi/v/pymaybe.svg 12 | :target: https://pypi.python.org/pypi/pymaybe 13 | 14 | .. image:: https://img.shields.io/pypi/dm/pymaybe.svg 15 | :target: https://pypi.python.org/pypi/pymaybe 16 | 17 | A Python implementation of the Maybe pattern. 18 | 19 | Installation 20 | ------------ 21 | 22 | .. code:: 23 | 24 | pip install pymaybe 25 | 26 | Getting Started 27 | --------------- 28 | 29 | .. code:: 30 | 31 | from pymaybe import maybe 32 | first_name = maybe(deep_hash)['account']['user_profile']['first_name'].or_else("") 33 | 34 | Documentation 35 | ------------- 36 | Maybe monad is a programming pattern that allows to treat None values that same way as non-none values. 37 | This is done by wrapping the value, which may or may not be None to, a wrapper class. 38 | 39 | The implementation includes two classes: *Maybe* and *Something*. 40 | *Something* represents a value while *Nothing* represents a None value. 41 | There's also a method *maybe* which wraps a regular value and and returns *Something* or *Nothing* instance. 42 | 43 | .. code:: 44 | 45 | >>> maybe("I'm a value") 46 | "I'm a value" 47 | 48 | >>> maybe(None); 49 | None 50 | 51 | Both *Something* and *Nothing* implement 4 methods allowing you to test their real value: *is_some*, *is_none*, *get* and *or_else* 52 | 53 | .. code:: 54 | 55 | >>> maybe("I'm a value").is_some() 56 | True 57 | 58 | >>> maybe("I'm a value").is_none() 59 | False 60 | 61 | >>> maybe(None).is_some() 62 | False 63 | 64 | >>> maybe(None).is_none() 65 | True 66 | 67 | >>> maybe("I'm a value").get() 68 | "I'm a value" 69 | 70 | >>> maybe("I'm a value").or_else(lambda: "No value") 71 | "I'm a value" 72 | 73 | >>> maybe(None).get() 74 | Traceback (most recent call last): 75 | ... 76 | Exception: No such element 77 | 78 | >>> maybe(None).or_else(lambda: "value") 79 | 'value' 80 | 81 | >>> maybe(None).or_else("value") 82 | 'value' 83 | 84 | In addition, *Something* and *Nothing* implement the Python magic methods allowing you to treat them as dictionaries: 85 | 86 | .. code:: 87 | 88 | >>> nested_dict = maybe(nested_dict) 89 | >>> nested_dict['store']['name'] 90 | 'MyStore' 91 | 92 | >>> nested_dict['store']['address'] 93 | None 94 | 95 | >>> nested_dict['store']['address']['street'].or_else('No Address Specified') 96 | 'No Address Specified' 97 | 98 | All other method calls on *Something* are forwarded to its real *value*: 99 | 100 | .. code:: 101 | 102 | >>> maybe('VALUE').lower() 103 | 'value' 104 | 105 | >>> maybe(None).invalid().method().or_else('unknwon') 106 | 'unknwon' 107 | 108 | Examples & Use Cases 109 | -------------------- 110 | 111 | The Maybe pattern helps you avoid nasty try..except blocks. 112 | Consider the following code: 113 | 114 | .. code:: 115 | 116 | try: 117 | url = rss.load_feeds()[0].url.domain 118 | except (TypeError, IndexError, KeyError, AttributeError): 119 | url = "planetpython.org" 120 | 121 | With Maybe you could simply do: 122 | 123 | .. code:: 124 | 125 | url = maybe(rss).load_feeds()[0]['url'].domain.or_else("planetpython.org") 126 | 127 | Getting the current logged in user's name. 128 | Without maybe: 129 | 130 | .. code:: 131 | 132 | def get_user_zipcode(): 133 | address = getattr(request.user, 'address', None) 134 | if address: 135 | return getattr(address, 'zipcode', '') 136 | 137 | return '' 138 | 139 | With maybe: 140 | 141 | .. code:: 142 | 143 | def get_user_zipcode(): 144 | return maybe(request.user).address.zipcode.or_else('') 145 | 146 | Further Reading 147 | --------------- 148 | 149 | * `Option (Scala) `_ 150 | * `Maybe (Java) `_ 151 | * `Maybe pattern (Python recipe) `_ 152 | * `Data.Maybe (Haskell) `_ 153 | * `Maybe (Ruby) `_ 154 | 155 | Copyright and License 156 | --------------------- 157 | Copyright 2015 - `Eran Kampf `_ 158 | 159 | * Free software: BSD license 160 | * Documentation: https://pymaybe.readthedocs.org. 161 | * Code is hosted on `GitHub `_ 162 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pymaybe.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pymaybe.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/pymaybe" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pymaybe" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst 2 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # pymaybe documentation build configuration file, created by 5 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | import sys 17 | import os 18 | 19 | # If extensions (or modules to document with autodoc) are in another 20 | # directory, add these directories to sys.path here. If the directory is 21 | # relative to the documentation root, use os.path.abspath to make it 22 | # absolute, like shown here. 23 | #sys.path.insert(0, os.path.abspath('.')) 24 | 25 | # Get the project root dir, which is the parent dir of this 26 | cwd = os.getcwd() 27 | project_root = os.path.dirname(cwd) 28 | 29 | # Insert the project root dir as the first element in the PYTHONPATH. 30 | # This lets us ensure that the source package is imported, and that its 31 | # version is used. 32 | sys.path.insert(0, project_root) 33 | 34 | import pymaybe 35 | 36 | # -- General configuration --------------------------------------------- 37 | 38 | # If your documentation needs a minimal Sphinx version, state it here. 39 | #needs_sphinx = '1.0' 40 | 41 | # Add any Sphinx extension module names here, as strings. They can be 42 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 43 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 44 | 45 | # Add any paths that contain templates here, relative to this directory. 46 | templates_path = ['_templates'] 47 | 48 | # The suffix of source filenames. 49 | source_suffix = '.rst' 50 | 51 | # The encoding of source files. 52 | #source_encoding = 'utf-8-sig' 53 | 54 | # The master toctree document. 55 | master_doc = 'index' 56 | 57 | # General information about the project. 58 | project = u'PyMaybe' 59 | copyright = u'2015, Eran Kampf' 60 | 61 | # The version info for the project you're documenting, acts as replacement 62 | # for |version| and |release|, also used in various other places throughout 63 | # the built documents. 64 | # 65 | # The short X.Y version. 66 | version = pymaybe.__version__ 67 | # The full version, including alpha/beta/rc tags. 68 | release = pymaybe.__version__ 69 | 70 | # The language for content autogenerated by Sphinx. Refer to documentation 71 | # for a list of supported languages. 72 | #language = None 73 | 74 | # There are two options for replacing |today|: either, you set today to 75 | # some non-false value, then it is used: 76 | #today = '' 77 | # Else, today_fmt is used as the format for a strftime call. 78 | #today_fmt = '%B %d, %Y' 79 | 80 | # List of patterns, relative to source directory, that match files and 81 | # directories to ignore when looking for source files. 82 | exclude_patterns = ['_build'] 83 | 84 | # The reST default role (used for this markup: `text`) to use for all 85 | # documents. 86 | #default_role = None 87 | 88 | # If true, '()' will be appended to :func: etc. cross-reference text. 89 | #add_function_parentheses = True 90 | 91 | # If true, the current module name will be prepended to all description 92 | # unit titles (such as .. function::). 93 | #add_module_names = True 94 | 95 | # If true, sectionauthor and moduleauthor directives will be shown in the 96 | # output. They are ignored by default. 97 | #show_authors = False 98 | 99 | # The name of the Pygments (syntax highlighting) style to use. 100 | pygments_style = 'sphinx' 101 | 102 | # A list of ignored prefixes for module index sorting. 103 | #modindex_common_prefix = [] 104 | 105 | # If true, keep warnings as "system message" paragraphs in the built 106 | # documents. 107 | #keep_warnings = False 108 | 109 | 110 | # -- Options for HTML output ------------------------------------------- 111 | 112 | # The theme to use for HTML and HTML Help pages. See the documentation for 113 | # a list of builtin themes. 114 | html_theme = 'default' 115 | 116 | # Theme options are theme-specific and customize the look and feel of a 117 | # theme further. For a list of options available for each theme, see the 118 | # documentation. 119 | #html_theme_options = {} 120 | 121 | # Add any paths that contain custom themes here, relative to this directory. 122 | #html_theme_path = [] 123 | 124 | # The name for this set of Sphinx documents. If None, it defaults to 125 | # " v documentation". 126 | #html_title = None 127 | 128 | # A shorter title for the navigation bar. Default is the same as 129 | # html_title. 130 | #html_short_title = None 131 | 132 | # The name of an image file (relative to this directory) to place at the 133 | # top of the sidebar. 134 | #html_logo = None 135 | 136 | # The name of an image file (within the static path) to use as favicon 137 | # of the docs. This file should be a Windows icon file (.ico) being 138 | # 16x16 or 32x32 pixels large. 139 | #html_favicon = None 140 | 141 | # Add any paths that contain custom static files (such as style sheets) 142 | # here, relative to this directory. They are copied after the builtin 143 | # static files, so a file named "default.css" will overwrite the builtin 144 | # "default.css". 145 | html_static_path = ['_static'] 146 | 147 | # If not '', a 'Last updated on:' timestamp is inserted at every page 148 | # bottom, using the given strftime format. 149 | #html_last_updated_fmt = '%b %d, %Y' 150 | 151 | # If true, SmartyPants will be used to convert quotes and dashes to 152 | # typographically correct entities. 153 | #html_use_smartypants = True 154 | 155 | # Custom sidebar templates, maps document names to template names. 156 | #html_sidebars = {} 157 | 158 | # Additional templates that should be rendered to pages, maps page names 159 | # to template names. 160 | #html_additional_pages = {} 161 | 162 | # If false, no module index is generated. 163 | #html_domain_indices = True 164 | 165 | # If false, no index is generated. 166 | #html_use_index = True 167 | 168 | # If true, the index is split into individual pages for each letter. 169 | #html_split_index = False 170 | 171 | # If true, links to the reST sources are added to the pages. 172 | #html_show_sourcelink = True 173 | 174 | # If true, "Created using Sphinx" is shown in the HTML footer. 175 | # Default is True. 176 | #html_show_sphinx = True 177 | 178 | # If true, "(C) Copyright ..." is shown in the HTML footer. 179 | # Default is True. 180 | #html_show_copyright = True 181 | 182 | # If true, an OpenSearch description file will be output, and all pages 183 | # will contain a tag referring to it. The value of this option 184 | # must be the base URL from which the finished HTML is served. 185 | #html_use_opensearch = '' 186 | 187 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 188 | #html_file_suffix = None 189 | 190 | # Output file base name for HTML help builder. 191 | htmlhelp_basename = 'pymaybedoc' 192 | 193 | 194 | # -- Options for LaTeX output ------------------------------------------ 195 | 196 | latex_elements = { 197 | # The paper size ('letterpaper' or 'a4paper'). 198 | #'papersize': 'letterpaper', 199 | 200 | # The font size ('10pt', '11pt' or '12pt'). 201 | #'pointsize': '10pt', 202 | 203 | # Additional stuff for the LaTeX preamble. 204 | #'preamble': '', 205 | } 206 | 207 | # Grouping the document tree into LaTeX files. List of tuples 208 | # (source start file, target name, title, author, documentclass 209 | # [howto/manual]). 210 | latex_documents = [ 211 | ('index', 'pymaybe.tex', 212 | u'PyMaybe Documentation', 213 | u'Eran Kampf', 'manual'), 214 | ] 215 | 216 | # The name of an image file (relative to this directory) to place at 217 | # the top of the title page. 218 | #latex_logo = None 219 | 220 | # For "manual" documents, if this is true, then toplevel headings 221 | # are parts, not chapters. 222 | #latex_use_parts = False 223 | 224 | # If true, show page references after internal links. 225 | #latex_show_pagerefs = False 226 | 227 | # If true, show URL addresses after external links. 228 | #latex_show_urls = False 229 | 230 | # Documents to append as an appendix to all manuals. 231 | #latex_appendices = [] 232 | 233 | # If false, no module index is generated. 234 | #latex_domain_indices = True 235 | 236 | 237 | # -- Options for manual page output ------------------------------------ 238 | 239 | # One entry per manual page. List of tuples 240 | # (source start file, name, description, authors, manual section). 241 | man_pages = [ 242 | ('index', 'pymaybe', 243 | u'PyMaybe Documentation', 244 | [u'Eran Kampf'], 1) 245 | ] 246 | 247 | # If true, show URL addresses after external links. 248 | #man_show_urls = False 249 | 250 | 251 | # -- Options for Texinfo output ---------------------------------------- 252 | 253 | # Grouping the document tree into Texinfo files. List of tuples 254 | # (source start file, target name, title, author, 255 | # dir menu entry, description, category) 256 | texinfo_documents = [ 257 | ('index', 'pymaybe', 258 | u'PyMaybe Documentation', 259 | u'Eran Kampf', 260 | 'pymaybe', 261 | 'One line description of project.', 262 | 'Miscellaneous'), 263 | ] 264 | 265 | # Documents to append as an appendix to all manuals. 266 | #texinfo_appendices = [] 267 | 268 | # If false, no module index is generated. 269 | #texinfo_domain_indices = True 270 | 271 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 272 | #texinfo_show_urls = 'footnote' 273 | 274 | # If true, do not generate a @detailmenu in the "Top" node's menu. 275 | #texinfo_no_detailmenu = False 276 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst 2 | -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../HISTORY.rst 2 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. pymaybe documentation master file, created by 2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to PyMaybe's documentation! 7 | ====================================== 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | readme 15 | installation 16 | usage 17 | contributing 18 | authors 19 | history 20 | 21 | Indices and tables 22 | ================== 23 | 24 | * :ref:`genindex` 25 | * :ref:`modindex` 26 | * :ref:`search` 27 | 28 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Installation 3 | ============ 4 | 5 | At the command line:: 6 | 7 | $ easy_install pymaybe 8 | 9 | Or, if you have virtualenvwrapper installed:: 10 | 11 | $ mkvirtualenv pymaybe 12 | $ pip install pymaybe 13 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\pymaybe.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\pymaybe.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ======== 2 | Usage 3 | ======== 4 | 5 | To use PyMaybe in a project:: 6 | 7 | import pymaybe 8 | -------------------------------------------------------------------------------- /pymaybe/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | __author__ = 'Eran Kampf' 4 | __email__ = 'eran@ekampf.com' 5 | __version__ = '0.2.0' 6 | 7 | from sys import getsizeof 8 | 9 | class NothingValueError(ValueError): 10 | pass 11 | 12 | class Maybe(object): 13 | pass 14 | 15 | 16 | class Nothing(Maybe): 17 | def is_some(self): 18 | return False 19 | 20 | def is_none(self): 21 | return True 22 | 23 | def get(self): 24 | raise NothingValueError('No such element') 25 | 26 | def or_else(self, els=None): 27 | if callable(els): 28 | return els() 29 | 30 | return els 31 | 32 | def or_none(self): 33 | return self.or_else() 34 | 35 | def or_empty_list(self): 36 | return self.or_else([]) 37 | 38 | def __call__(self, *args, **kwargs): 39 | return Nothing() 40 | 41 | # region Comparison 42 | 43 | def __cmp__(self, other): 44 | if other.__class__ == Nothing: 45 | return 0 46 | 47 | return -1 48 | 49 | def __eq__(self, other): 50 | if other.__class__ == Nothing: 51 | return True 52 | 53 | if other is None: 54 | return True 55 | 56 | return False 57 | 58 | def __ne__(self, other): 59 | return not self.__eq__(other) 60 | 61 | def __lt__(self, other): 62 | if other.__class__ == Nothing: 63 | return False 64 | 65 | if other.__class__ == Something: 66 | return True 67 | 68 | return True if other else False 69 | 70 | def __gt__(self, other): 71 | return False 72 | 73 | def __le__(self, other): 74 | return True 75 | 76 | def __ge__(self, other): 77 | if other.__class__ == Nothing: 78 | return True 79 | 80 | if other is None: 81 | return True 82 | 83 | return False 84 | 85 | # endregion 86 | 87 | def __getattr__(self, name): 88 | return Nothing() 89 | 90 | # region Dict 91 | def __len__(self): 92 | return 0 93 | 94 | def __getitem__(self, key): 95 | return Nothing() 96 | 97 | def __setitem__(self, key, value): 98 | pass 99 | 100 | def __delitem__(self, key): 101 | pass 102 | 103 | # endregion 104 | 105 | # region Custom representation 106 | def __repr__(self): 107 | return 'Nothing' 108 | 109 | def __str__(self): 110 | return 'Nothing' 111 | 112 | def __unicode__(self): 113 | return unicode(None) 114 | 115 | def __nonzero__(self): 116 | return False 117 | 118 | # endregion 119 | 120 | 121 | class Something(Maybe): 122 | def __init__(self, value): 123 | self.__value = value 124 | 125 | def __call__(self, *args, **kwargs): 126 | return maybe(self.__value(*args, **kwargs)) 127 | 128 | # region Comparison 129 | def __cmp__(self, other): 130 | if other.__class__ == Nothing: 131 | return 1 132 | 133 | if other.__class__ == Something: 134 | return cmp(self.get(), other.get()) 135 | else: 136 | return cmp(self.get(), other) 137 | 138 | def __eq__(self, other): 139 | if other.__class__ == Nothing: 140 | return False 141 | 142 | if other.__class__ == Something: 143 | return self.get() == other.get() 144 | 145 | return self.get() == other 146 | 147 | def __ne__(self, other): 148 | return not self.__eq__(other) 149 | 150 | def __lt__(self, other): 151 | if other.__class__ == Nothing: 152 | return False 153 | 154 | if other.__class__ == Something: 155 | return self.get() < other.get() 156 | 157 | return self.get() < other 158 | 159 | def __gt__(self, other): 160 | if other.__class__ == Nothing: 161 | return True 162 | 163 | if other.__class__ == Something: 164 | return self.get() > other.get() 165 | 166 | return self.get() > other 167 | 168 | def __le__(self, other): 169 | if other.__class__ == Nothing: 170 | return False 171 | 172 | if other.__class__ == Something: 173 | return self.get() <= other.get() 174 | 175 | return self.get() <= other 176 | 177 | def __ge__(self, other): 178 | if other.__class__ == Nothing: 179 | return True 180 | 181 | if other.__class__ == Something: 182 | return self.get() >= other.get() 183 | 184 | return self.get() >= other 185 | # endregion 186 | 187 | def is_some(self): 188 | return True 189 | 190 | def is_none(self): 191 | return False 192 | 193 | def get(self): 194 | return self.__value 195 | 196 | # pylint: disable=W0613 197 | def or_else(self, els=None): 198 | return self.__value 199 | 200 | def or_none(self): 201 | return self.or_else() 202 | 203 | def or_empty_list(self): 204 | return self.or_else([]) 205 | 206 | def __getattr__(self, name): 207 | try: 208 | return maybe(getattr(self.__value, name)) 209 | except Exception: 210 | return Nothing() 211 | 212 | def __setattr__(self, name, v): 213 | if name == "_Something__value": 214 | return super(Something, self).__setattr__(name, v) 215 | 216 | return setattr(self.__value, name, v) 217 | 218 | # region Containers Methods 219 | 220 | def __len__(self): 221 | return len(self.__value) 222 | 223 | def __getitem__(self, key): 224 | try: 225 | return maybe(self.__value[key]) 226 | except (KeyError, TypeError, IndexError): 227 | return Nothing() 228 | 229 | def __setitem__(self, key, value): 230 | self.__value[key] = value 231 | 232 | def __delitem__(self, key): 233 | del self.__value[key] 234 | 235 | def __iter__(self): 236 | try: 237 | iterator = iter(self.__value) 238 | except TypeError: 239 | iterator = iter([self.__value]) 240 | 241 | return iterator 242 | 243 | def __reversed__(self): 244 | return maybe(reversed(self.__value)) 245 | 246 | def __missing__(self, key): 247 | klass = self.__value.__class__ 248 | if hasattr(klass, '__missing__') and \ 249 | callable(getattr(klass, '__missing__')): 250 | return maybe(self.__value.__missing__(key)) 251 | 252 | return Nothing() 253 | 254 | # endregion 255 | 256 | # region Custom representation 257 | 258 | def __repr__(self): 259 | return 'Something(%s)' % repr(self.__value) 260 | 261 | def __str__(self): 262 | return 'Something(%s)' % str(self.__value) 263 | 264 | def __int__(self): 265 | return int(self.__value) 266 | 267 | def __long__(self): 268 | return long(self.__value) 269 | 270 | def __float__(self): 271 | return float(self.__value) 272 | 273 | def __complex__(self): 274 | return complex(self.__value) 275 | 276 | def __oct__(self): 277 | return oct(self.__value) 278 | 279 | def __hex__(self): 280 | return hex(self.__value) 281 | 282 | def __index__(self): 283 | return self.__value.__index__() 284 | 285 | def __trunc__(self): 286 | return self.__value.__trunc__() 287 | 288 | def __coerce__(self, other): 289 | return coerce(self.__value, other) 290 | 291 | def __unicode__(self): 292 | return unicode(self.__value) 293 | 294 | def __nonzero__(self): 295 | return True 296 | 297 | def __dir__(self): 298 | return dir(self.__value) 299 | 300 | def __sizeof__(self): 301 | return getsizeof(self.__value) 302 | 303 | # endregion 304 | 305 | # region Arithmetics 306 | 307 | def __add__(self, other): 308 | return maybe(self.__value + other) 309 | 310 | def __sub__(self, other): 311 | return maybe(self.__value - other) 312 | 313 | def __mul__(self, other): 314 | return maybe(self.__value * other) 315 | 316 | def __floordiv__(self, other): 317 | return maybe(self.__value // other) 318 | 319 | def __div__(self, other): 320 | return maybe(self.__value / other) 321 | 322 | def __mod__(self, other): 323 | return maybe(self.__value % other) 324 | 325 | def __divmod__(self, other): 326 | """Implements behavior for long division using the divmod() built in function.""" 327 | return maybe(divmod(self.__value, other)) 328 | 329 | def __pow__(self, other): 330 | """Implements behavior for exponents using the ** operator.""" 331 | return maybe(self.__value ** other) 332 | 333 | def __lshift__(self, other): 334 | """Implements left bitwise shift using the << operator.""" 335 | return maybe(self.__value << other) 336 | 337 | def __rshift__(self, other): 338 | """Implements right bitwise shift using the >> operator.""" 339 | return maybe(self.__value >> other) 340 | 341 | def __and__(self, other): 342 | """Implements bitwise and using the & operator.""" 343 | return maybe(self.__value & other) 344 | 345 | def __or__(self, other): 346 | """Implements bitwise or using the | operator.""" 347 | return maybe(self.__value | other) 348 | 349 | def __xor__(self, other): 350 | """Implements bitwise xor using the ^ operator.""" 351 | return maybe(self.__value ^ other) 352 | 353 | def __radd__(self, other): 354 | """Implements reflected addition.""" 355 | return maybe(other + self.__value) 356 | 357 | def __rsub__(self, other): 358 | """Implements reflected subtraction.""" 359 | return maybe(other - self.__value) 360 | 361 | def __rmul__(self, other): 362 | """Implements reflected multiplication.""" 363 | return maybe(other * self.__value) 364 | 365 | def __rfloordiv__(self, other): 366 | """Implements reflected integer division using the // operator.""" 367 | return maybe(other // self.__value) 368 | 369 | def __rdiv__(self, other): 370 | """Implements reflected division using the / operator.""" 371 | return maybe(other / self.__value) 372 | 373 | def __rmod__(self, other): 374 | """Implements reflected modulo using the % operator.""" 375 | return maybe(other % self.__value) 376 | 377 | def __rdivmod__(self, other): 378 | """Implements behavior for long division using the divmod() built in function, when divmod(other, self) is called.""" 379 | return maybe(divmod(other, self.__value)) 380 | 381 | def __rpow__(self, other): 382 | """Implements behavior for reflected exponents using the ** operator.""" 383 | return maybe(other ** self.__value) 384 | 385 | def __rlshift__(self, other): 386 | """Implements reflected left bitwise shift using the << operator.""" 387 | return maybe(other << self.__value) 388 | 389 | def __rrshift__(self, other): 390 | """Implements reflected right bitwise shift using the >> operator.""" 391 | return maybe(other >> self.__value) 392 | 393 | def __rand__(self, other): 394 | """Implements reflected bitwise and using the & operator.""" 395 | return maybe(other & self.__value) 396 | 397 | def __ror__(self, other): 398 | """Implements reflected bitwise or using the | operator.""" 399 | return maybe(other | self.__value) 400 | 401 | def __rxor__(self, other): 402 | """Implements reflected bitwise xor using the ^ operator.""" 403 | return maybe(other ^ self.__value) 404 | 405 | # endregion 406 | 407 | # region Augmented assignment 408 | 409 | def __iadd__(self, other): 410 | """Implements addition with assignment.""" 411 | self.__value += other 412 | return self 413 | 414 | def __isub__(self, other): 415 | """Implements subtraction with assignment.""" 416 | self.__value -= other 417 | return self 418 | 419 | def __imul__(self, other): 420 | """Implements multiplication with assignment.""" 421 | self.__value *= other 422 | return self 423 | 424 | def __ifloordiv__(self, other): 425 | """Implements integer division with assignment using the //= operator.""" 426 | self.__value //= other 427 | return self 428 | 429 | def __idiv__(self, other): 430 | """Implements division with assignment using the /= operator.""" 431 | self.__value /= other 432 | return self 433 | 434 | def __imod__(self, other): 435 | """Implements modulo with assignment using the %= operator.""" 436 | self.__value %= other 437 | return self 438 | 439 | def __ipow__(self, other): 440 | """Implements behavior for exponents with assignment using the **= operator.""" 441 | self.__value **= other 442 | return self 443 | 444 | def __ilshift__(self, other): 445 | """Implements left bitwise shift with assignment using the <<= operator.""" 446 | self.__value <<= other 447 | return self 448 | 449 | def __irshift__(self, other): 450 | """Implements right bitwise shift with assignment using the >>= operator.""" 451 | self.__value >>= other 452 | return self 453 | 454 | def __iand__(self, other): 455 | """Implements bitwise and with assignment using the &= operator.""" 456 | self.__value &= other 457 | return self 458 | 459 | def __ior__(self, other): 460 | """Implements bitwise or with assignment using the |= operator.""" 461 | self.__value |= other 462 | return self 463 | 464 | def __ixor__(self, other): 465 | """Implements bitwise xor with assignment using the ^= operator.""" 466 | self.__value ^= other 467 | return self 468 | 469 | # endregion 470 | 471 | 472 | def maybe(value): 473 | """Wraps an object with a Maybe instance. 474 | 475 | >>> maybe("I'm a value") 476 | Something("I'm a value") 477 | 478 | >>> maybe(None); 479 | Nothing 480 | 481 | Testing for value: 482 | 483 | >>> maybe("I'm a value").is_some() 484 | True 485 | >>> maybe("I'm a value").is_none() 486 | False 487 | >>> maybe(None).is_some() 488 | False 489 | >>> maybe(None).is_none() 490 | True 491 | 492 | Simplifying IF statements: 493 | 494 | >>> maybe("I'm a value").get() 495 | "I'm a value" 496 | 497 | >>> maybe("I'm a value").or_else(lambda: "No value") 498 | "I'm a value" 499 | 500 | >>> maybe(None).get() 501 | Traceback (most recent call last): 502 | ... 503 | NothingValueError: No such element 504 | 505 | >>> maybe(None).or_else(lambda: "value") 506 | 'value' 507 | 508 | >>> maybe(None).or_else("value") 509 | 'value' 510 | 511 | Wrap around values from object's attributes: 512 | 513 | class Person(object): 514 | def __init__(name): 515 | self.eran = name 516 | 517 | eran = maybe(Person('eran')) 518 | 519 | >>> eran.name 520 | Something('eran') 521 | >>> eran.phone_number 522 | Nothing 523 | >>> eran.phone_number.or_else('no phone number') 524 | 'no phone number' 525 | 526 | >>> maybe(4) + 8 527 | Something(12) 528 | >>> maybe(4) - 2 529 | Something(2) 530 | >>> maybe(4) * 2 531 | Something(8) 532 | 533 | And methods: 534 | 535 | >>> maybe('VALUE').lower().get() 536 | 'value' 537 | >>> maybe(None).invalid().method().or_else('unknwon') 538 | 'unknwon' 539 | 540 | Enabled easily using NestedDictionaries without having to worry 541 | if a value is missing. 542 | For example lets assume we want to load some value from the 543 | following dictionary: 544 | nested_dict = maybe({ 545 | 'store': { 546 | 'name': 'MyStore', 547 | 'departments': { 548 | 'sales': { 'head_count': '10' } 549 | } 550 | } 551 | }) 552 | 553 | >>> nested_dict['store']['name'].get() 554 | 'MyStore' 555 | >>> nested_dict['store']['address'] 556 | Nothing 557 | >>> nested_dict['store']['address']['street'].or_else('No Address Specified') 558 | 'No Address Specified' 559 | >>> nested_dict['store']['address']['street'].or_none() is None 560 | True 561 | >>> nested_dict['store']['address']['street'].or_empty_list() 562 | [] 563 | >>> nested_dict['store']['departments']['sales']['head_count'].or_else('0') 564 | '10' 565 | >>> nested_dict['store']['departments']['marketing']['head_count'].or_else('0') 566 | '0' 567 | 568 | """ 569 | if isinstance(value, Maybe): 570 | return value 571 | 572 | if value is not None: 573 | return Something(value) 574 | 575 | return Nothing() 576 | 577 | 578 | def get_doctest_globs(): 579 | class Person(object): 580 | def __init__(self, name): 581 | self.name = name 582 | 583 | eran = Person('eran') 584 | 585 | globals_dict = { 586 | 'nested_dict': maybe({ 587 | 'store': { 588 | 'name': 'MyStore', 589 | 'departments': { 590 | 'sales': {'head_count': '10'} 591 | } 592 | } 593 | }), 594 | 'eran': maybe(eran), 595 | 'maybe': maybe, 596 | } 597 | 598 | return globals_dict 599 | 600 | 601 | if __name__ == "__main__": 602 | import doctest 603 | doctest.testmod(globs=get_doctest_globs()) 604 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | wheel==0.23.0 2 | tox 3 | coverage 4 | flake8 5 | Sphinx 6 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [wheel] 2 | universal = 1 3 | 4 | [flake8] 5 | ignore = E501 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | try: 6 | from setuptools import setup 7 | except ImportError: 8 | from distutils.core import setup 9 | 10 | import codecs 11 | import os 12 | import re 13 | 14 | root_dir = os.path.abspath(os.path.dirname(__file__)) 15 | 16 | def get_build_number(): 17 | fname = 'build.info' 18 | if os.path.isfile(fname): 19 | with open(fname) as f: 20 | build_number = f.read() 21 | build_number = re.sub("[^a-z0-9]+","", build_number, flags=re.IGNORECASE) 22 | return '.' + build_number 23 | 24 | return '' 25 | 26 | def get_version(package_name): 27 | build_number = get_build_number() 28 | 29 | version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$") 30 | package_components = package_name.split('.') 31 | init_path = os.path.join(root_dir, *(package_components + ['__init__.py'])) 32 | with codecs.open(init_path, 'r', 'utf-8') as f: 33 | for line in f: 34 | match = version_re.match(line[:-1]) 35 | if match: 36 | return match.groups()[0]+build_number 37 | 38 | return '0.1.0' + build_number 39 | 40 | with open('README.rst') as readme_file: 41 | readme = readme_file.read() 42 | 43 | with open('HISTORY.rst') as history_file: 44 | history = history_file.read().replace('.. :changelog:', '') 45 | 46 | requirements = [ 47 | # TODO: put package requirements here 48 | ] 49 | 50 | test_requirements = [ 51 | # TODO: put package test requirements here 52 | ] 53 | 54 | setup( 55 | name='pymaybe', 56 | version=get_version('pymaybe'), 57 | description="A Python implementation of the Maybe pattern.", 58 | long_description=readme + '\n\n' + history, 59 | author="Eran Kampf", 60 | author_email='eran@ekampf.com', 61 | url='https://github.com/ekampf/pymaybe', 62 | packages=[ 63 | 'pymaybe', 64 | ], 65 | package_dir={'pymaybe': 'pymaybe'}, 66 | include_package_data=True, 67 | install_requires=requirements, 68 | license="BSD", 69 | zip_safe=False, 70 | keywords='pymaybe', 71 | classifiers=[ 72 | 'Development Status :: 5 - Production/Stable', 73 | 'Intended Audience :: Developers', 74 | 'License :: OSI Approved :: BSD License', 75 | 'Natural Language :: English', 76 | "Programming Language :: Python :: 2", 77 | "Programming Language :: Python :: 2.5", 78 | "Programming Language :: Python :: 2.6", 79 | "Programming Language :: Python :: 2.7", 80 | "Programming Language :: Python :: 3", 81 | "Programming Language :: Python :: 3.3", 82 | "Programming Language :: Python :: 3.4", 83 | ], 84 | test_suite='tests', 85 | tests_require=test_requirements 86 | ) 87 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /tests/test_pymaybe.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | test_pymaybe 6 | ---------------------------------- 7 | 8 | Tests for `pymaybe` module. 9 | """ 10 | 11 | import sys 12 | import unittest 13 | import doctest 14 | 15 | from pymaybe import maybe, Something, Nothing 16 | 17 | PY2 = sys.version_info[0] == 2 18 | PY3 = sys.version_info[0] == 3 19 | 20 | 21 | def load_tests(loader, tests, ignore): 22 | import pymaybe 23 | tests.addTests( 24 | doctest.DocTestSuite( 25 | pymaybe, 26 | globs=pymaybe.get_doctest_globs(), 27 | optionflags=doctest.IGNORE_EXCEPTION_DETAIL 28 | ) 29 | ) 30 | return tests 31 | 32 | PY2 = sys.version_info[0] == 2 33 | PY3 = sys.version_info[0] == 3 34 | 35 | 36 | class TestPyMaybe(unittest.TestCase): 37 | 38 | def test_maybe_withValue_returnsSomething(self): 39 | result = maybe("Value") 40 | self.assertIsInstance(result, Something) 41 | 42 | def test_maybe_withMaybe_returnMaybe(self): 43 | m = maybe("value") 44 | self.assertEqual(maybe(m), m) 45 | 46 | def test_maybe_withNone_returnsNothing(self): 47 | result = maybe(None) 48 | self.assertIsInstance(result, Nothing) 49 | 50 | # region Nothing - Comparison 51 | 52 | def test_comparisons(self): 53 | self.assertReallyEqual(Something(1), 1) 54 | self.assertReallyEqual(1, Something(1)) 55 | self.assertReallyEqual(Something(1), Something(1)) 56 | self.assertReallyEqual(Nothing(), Nothing()) 57 | 58 | self.assertReallyNotEqual(Something(1), Something(2)) 59 | self.assertReallyNotEqual(Something(1), Nothing()) 60 | self.assertReallyNotEqual(Nothing(), Something(1)) 61 | 62 | def test_nothing_cmp(self): 63 | if PY2: 64 | self.assertEqual(0, cmp(Nothing(), Nothing())) 65 | self.assertEqual(1, cmp(1, Nothing())) 66 | self.assertEqual(1, cmp(Something(5), Nothing())) 67 | self.assertEqual(1, cmp(5, Nothing())) 68 | self.assertEqual(-1, cmp(Nothing(), Something(5))) 69 | self.assertEqual(-1, cmp(Nothing(), 5)) 70 | 71 | def test_nothing_equalToNothing(self): 72 | self.assertTrue(Nothing() == Nothing()) 73 | 74 | def test_nothing_notEqualToSomething(self): 75 | self.assertFalse(Nothing() == Something(2)) 76 | self.assertFalse(Something(1) == Nothing()) 77 | 78 | def test_nothing_neSomething(self): 79 | self.assertTrue(Nothing() != Something(2)) 80 | self.assertTrue(Something(1) != Nothing()) 81 | 82 | def test_nothing_neNothing(self): 83 | self.assertFalse(Nothing() != Nothing()) 84 | 85 | def test_nothing_ltNothing_isFalse(self): 86 | self.assertFalse(Nothing() < Nothing()) 87 | 88 | def test_nothing_ltSomething_isTrue(self): 89 | self.assertTrue(Nothing() < Something(1)) 90 | 91 | def test_nothing_ltNone_isFalse(self): 92 | self.assertFalse(Nothing() < None) 93 | 94 | def test_nothing_ltNotNone_isFalse(self): 95 | self.assertTrue(Nothing() < "some") 96 | 97 | def test_nothing_gtAnything_isFalse(self): 98 | self.assertFalse(Nothing() > Nothing()) 99 | self.assertFalse(Nothing() > Something(123)) 100 | self.assertFalse(Nothing() > None) 101 | self.assertFalse(Nothing() > "Value") 102 | 103 | def test_nothing_leAnything_isTrue(self): 104 | self.assertTrue(Nothing() <= Nothing()) 105 | self.assertTrue(Nothing() <= Something(123)) 106 | self.assertTrue(Nothing() <= None) 107 | self.assertTrue(Nothing() <= "Value") 108 | 109 | def test_nothing_geNothing_isTrue(self): 110 | self.assertTrue(Nothing() >= Nothing()) 111 | 112 | def test_nothing_geNone_isTrue(self): 113 | self.assertTrue(Nothing() >= None) 114 | 115 | def test_nothing_geNotNoneOrNothing_isFalse(self): 116 | self.assertFalse(Nothing() >= Something(2)) 117 | self.assertFalse(Nothing() >= "some") 118 | 119 | # endregion 120 | 121 | # region Nothing - Dict 122 | 123 | def test_nothing_len_isZero(self): 124 | self.assertEqual(len(Nothing()), 0) 125 | 126 | def test_nothing_getItem_returnsNothing(self): 127 | n = Nothing()['name'] 128 | self.assertTrue(isinstance(n, Nothing)) 129 | self.assertTrue(n.is_none()) 130 | self.assertFalse(n.is_some()) 131 | 132 | def test_nothing_setItem_doestNothing(self): 133 | Nothing()['name'] = 'value' # Will raise if __setitem__ wasnt defined 134 | 135 | def test_nothing_delItem_doestNothing(self): 136 | del Nothing()['name'] # Will raise if __delitem__ wasnt defined 137 | 138 | # endregion 139 | 140 | # region Nothing - Custom representation 141 | 142 | def test_nothing_unicode(self): 143 | if PY2: 144 | self.assertEqual(unicode(Nothing()), unicode(None)) 145 | 146 | def test_nothing_nonzero_isFalse(self): 147 | self.assertFalse(bool(Nothing())) 148 | 149 | # endregion 150 | 151 | # region Nothing - Misc Methods 152 | 153 | def test_nothing_length_isZero(self): 154 | self.assertEqual(len(Nothing()), 0) 155 | 156 | def test_nothing_getItem_returnsNone(self): 157 | result = Nothing()[10] 158 | self.assertIsInstance(result, Nothing) 159 | 160 | def test_nothing_strings_returnNone(self): 161 | self.assertEqual(str(Nothing()), "Nothing") 162 | 163 | # endregion 164 | 165 | # region Something - Comparison 166 | 167 | def test_something_cmp(self): 168 | if PY2: 169 | n = Nothing() 170 | s = maybe(5) 171 | s1 = maybe(7) 172 | 173 | self.assertEqual(1, cmp(s, n)) 174 | self.assertEqual(cmp(5, 5), cmp(s, s)) 175 | self.assertEqual(cmp(5, 7), cmp(s, s1)) 176 | self.assertEqual(cmp(7, 5), cmp(s1, s)) 177 | self.assertEqual(cmp(5, 5), cmp(s, 5)) 178 | self.assertEqual(cmp(5, 7), cmp(s, 7)) 179 | self.assertEqual(cmp(7, 5), cmp(7, s)) 180 | 181 | def test_something_cmp_greaterThanNothing(self): 182 | l = [Something(0), Nothing()] 183 | sortedl = sorted(l) 184 | self.assertTrue(isinstance(sortedl[0], Nothing)) 185 | self.assertTrue(isinstance(sortedl[1], Something)) 186 | 187 | def test_something_cmp_handlesComparisonBetweenSomethings(self): 188 | l = [Something(10), Something(3)] 189 | sortedl = sorted(l) 190 | self.assertTrue(isinstance(sortedl[0], Something)) 191 | self.assertTrue(isinstance(sortedl[1], Something)) 192 | 193 | self.assertEqual(sortedl[0], 3) 194 | self.assertEqual(sortedl[1], 10) 195 | 196 | def test_something_cmp(self): 197 | l = [Something(1), 2, Nothing()] 198 | sortedl = sorted(l) 199 | self.assertTrue(isinstance(sortedl[0], Nothing)) 200 | self.assertTrue(isinstance(sortedl[1], Something)) 201 | self.assertTrue(isinstance(sortedl[2], int)) 202 | 203 | self.assertEqual(sortedl[0], None) 204 | self.assertEqual(sortedl[1], 1) 205 | self.assertEqual(sortedl[2], 2) 206 | 207 | def test_something_notEqualToNothing(self): 208 | self.assertFalse(Something(1) == Nothing()) 209 | self.assertFalse(Nothing() == Something(2)) 210 | 211 | def test_something_ltNothing_isFalse(self): 212 | self.assertFalse(Something("value") < Nothing()) 213 | 214 | def test_something_ltSomething_usesValue(self): 215 | self.assertFalse(Something(3) < Something(1)) 216 | self.assertTrue(Something(3) > Something(1)) 217 | 218 | def test_something_gtNothing_isTrue(self): 219 | self.assertTrue(Something("value") > Nothing()) 220 | 221 | def test_something_leNothing_isFalse(self): 222 | self.assertFalse(Something("value") <= Nothing()) 223 | 224 | def test_something_leSomething_comparesTheUnderlyingValue(self): 225 | self.assertTrue(Something(1) < Something(2)) 226 | self.assertFalse(Something(11) < Something(2)) 227 | 228 | def test_something_leValue_comparesTheUnderlyingValue(self): 229 | self.assertTrue(Something(1) < 2) 230 | self.assertTrue(Something(1) <= 2) 231 | self.assertTrue(Something(1) <= 1) 232 | self.assertFalse(Something(11) < 2) 233 | 234 | def test_something_geNothing_isTrue(self): 235 | self.assertTrue(Something("value") >= Nothing()) 236 | 237 | def test_something_geSomething_comparesTheUnderlyingValue(self): 238 | self.assertTrue(Something(11) > Something(2)) 239 | self.assertTrue(Something(11) >= Something(2)) 240 | self.assertTrue(Something(11) >= Something(11)) 241 | self.assertFalse(Something(1) > Something(2)) 242 | 243 | def test_something_geValue_comparesTheUnderlyingValue(self): 244 | self.assertTrue(Something(11) > 2) 245 | self.assertFalse(Something(1) > 2) 246 | 247 | # endregion 248 | 249 | def test_something_conversions(self): 250 | s = "value" 251 | d = dict(name="Eran") 252 | n = 123 253 | f = 3.14 254 | 255 | if PY2: 256 | self.assertEqual(unicode(Something(s)), s) 257 | 258 | self.assertEqual(long(Something(n)), n) 259 | self.assertIsInstance(long(Something(f)), long) 260 | 261 | self.assertEqual(str(Something(s)), "Something(%s)" % s) 262 | 263 | self.assertEqual(repr(Something(s)), "Something(%s)" % repr(s)) 264 | self.assertEqual(repr(Something(d)), "Something(%s)" % repr(d)) 265 | 266 | self.assertEqual(int(Something(n)), n) 267 | self.assertIsInstance(int(Something(n)), int) 268 | 269 | self.assertEqual(float(Something(f)), f) 270 | self.assertIsInstance(float(Something(f)), float) 271 | 272 | # region Something - Container Methods 273 | 274 | def test_something_len_isZero(self): 275 | s = maybe(dict(test='value')) 276 | self.assertEqual(len(s), 1) 277 | 278 | s = maybe([1, 2, 3]) 279 | self.assertEqual(len(s), 3) 280 | 281 | def test_something_getItem_returnsNothing(self): 282 | s = maybe(dict(test='value')) 283 | self.assertTrue(isinstance(s['test'], Something)) 284 | self.assertTrue(s['test'].is_some()) 285 | 286 | self.assertTrue(isinstance(s['test1'], Nothing)) 287 | self.assertTrue(s['test1'].is_none()) 288 | 289 | def test_something_list_getItem_returnsNothing(self): 290 | s = maybe([1, 2, 3]) 291 | self.assertTrue(isinstance(s[0], Something)) 292 | self.assertTrue(s[0].is_some()) 293 | self.assertEqual(s[0].get(), 1) 294 | 295 | self.assertTrue(isinstance(s['test1'], Nothing)) 296 | self.assertTrue(s['test1'].is_none()) 297 | 298 | self.assertTrue(isinstance(s[dict()], Nothing)) 299 | self.assertTrue(s[dict()].is_none()) 300 | 301 | self.assertTrue(isinstance(s[10], Nothing)) 302 | self.assertTrue(s[10].is_none()) 303 | 304 | def test_something_setItem_doestNothing(self): 305 | s = maybe(dict(test='value')) 306 | s['test'] = 'yeah' 307 | self.assertEqual(s['test'], 'yeah') 308 | self.assertTrue(s['test'].is_some()) 309 | 310 | def test_something_delItem_doestNothing(self): 311 | s = maybe(dict(test='value')) 312 | del s['test'] # Will raise if __delitem__ wasnt defined 313 | self.assertEqual(len(s), 0) 314 | self.assertTrue(s['test'].is_none()) 315 | 316 | def test_something_iter_onIterable_returnsArrayIterator(self): 317 | s = maybe([1, 2, 3, 4, 5]) 318 | l = list(iter(s)) 319 | self.assertEqual([1, 2, 3, 4, 5], l) 320 | 321 | def test_something_iter_onNotIterable_returnsArrayIterator(self): 322 | class Foo(object): 323 | pass 324 | 325 | obj = Foo() 326 | l = list(iter(maybe(obj))) 327 | self.assertEqual(l, [obj]) 328 | 329 | def test_something_missing_onDefaultDict_forwardsCallToDefaultDict(self): 330 | from collections import defaultdict 331 | d = maybe(defaultdict(lambda: 'default')) 332 | d['test'] = 'ok' 333 | 334 | self.assertEqual(d['doesnt exist'], 'default') 335 | self.assertEqual(d['test'], 'ok') 336 | 337 | self.assertTrue(d['doesnt exist'].is_some()) 338 | self.assertTrue(d['test'].is_some()) 339 | 340 | def test_something_reversed(self): 341 | l = maybe([1, 2, 3]) 342 | lr = list(reversed(l)) 343 | 344 | self.assertEqual(lr[0], 3) 345 | self.assertEqual(lr[1], 2) 346 | self.assertEqual(lr[2], 1) 347 | 348 | # endregion 349 | 350 | def test_something_typeConversions(self): 351 | import math 352 | 353 | self.assertEqual(complex(1), complex(Something(1))) 354 | self.assertEqual(oct(1), oct(Something(1))) 355 | self.assertEqual(hex(16), hex(Something(16))) 356 | self.assertEqual(math.trunc(math.pi), math.trunc(maybe(math.pi))) 357 | 358 | # region method call forwarding 359 | 360 | def test_something_forwardsMethodCalls(self): 361 | result = maybe('VALUE').lower() 362 | assert result.is_some() 363 | assert result == 'value', "result %s should be 'value'" % result 364 | assert result == maybe('value') 365 | 366 | def test_something_forwardsMethodCalls_handlesNonExisting(self): 367 | result = maybe('VALUE').lowerr() 368 | assert result.is_none() 369 | 370 | def test_nothing_forwardsMethodCalls_handlesNonExisting(self): 371 | result = maybe(None).invalid().call() 372 | assert result.is_none() 373 | 374 | # endregion 375 | 376 | # region Assertions (for compatibility between Python version) 377 | 378 | def assertIsInstance(self, obj, cls, msg=None): 379 | result = isinstance(obj, cls) 380 | self.assertTrue(result, msg=msg) 381 | 382 | # endregion 383 | 384 | def assertReallyEqual(self, a, b): 385 | self.assertEqual(a, b) 386 | self.assertEqual(b, a) 387 | self.assertTrue(a == b) 388 | self.assertTrue(b == a) 389 | self.assertFalse(a != b) 390 | self.assertFalse(b != a) 391 | if PY2: 392 | self.assertEqual(0, cmp(a, b)) 393 | self.assertEqual(0, cmp(b, a)) 394 | 395 | def assertReallyNotEqual(self, a, b): 396 | self.assertNotEqual(a, b) 397 | self.assertNotEqual(b, a) 398 | self.assertFalse(a == b) 399 | self.assertFalse(b == a) 400 | self.assertTrue(a != b) 401 | self.assertTrue(b != a) 402 | if PY2: 403 | self.assertNotEqual(0, cmp(a, b)) 404 | self.assertNotEqual(0, cmp(b, a)) 405 | 406 | 407 | if __name__ == '__main__': 408 | unittest.main() 409 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py25, py26, py27, py33, py34 3 | 4 | [testenv] 5 | setenv = 6 | PYTHONPATH = {toxinidir}:{toxinidir}/pymaybe 7 | commands = python setup.py test 8 | deps = 9 | -r{toxinidir}/requirements.txt 10 | 11 | [testenv:style] 12 | deps = 13 | -r{toxinidir}/requirements.txt 14 | flake8 15 | commands = 16 | python setup.py flake8 17 | 18 | [testenv:docs] 19 | changedir=docs/ 20 | deps = 21 | -r{toxinidir}/requirements.txt 22 | sphinx 23 | commands = 24 | sphinx-build -b linkcheck ./ _build/ 25 | sphinx-build -b html ./ _build/ --------------------------------------------------------------------------------