outcome-1.2.0/0000755000076500000240000000000014252063173013776 5ustar quentinstaff00000000000000outcome-1.2.0/PKG-INFO0000644000076500000240000000475314252063173015104 0ustar quentinstaff00000000000000Metadata-Version: 2.1 Name: outcome Version: 1.2.0 Summary: Capture the outcome of Python function calls. Home-page: https://github.com/python-trio/outcome Author: Frazer McLean Author-email: frazer@frazermclean.co.uk License: MIT OR Apache-2.0 Project-URL: Documentation, https://outcome.readthedocs.io/en/latest/ Project-URL: Chat, https://gitter.im/python-trio/general Description: .. image:: https://img.shields.io/badge/chat-join%20now-blue.svg :target: https://gitter.im/python-trio/general :alt: Join chatroom .. image:: https://img.shields.io/badge/docs-read%20now-blue.svg :target: https://outcome.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status .. image:: https://travis-ci.org/python-trio/trio.svg?branch=master :target: https://travis-ci.org/python-trio/outcome :alt: Automated test status (Linux and MacOS) .. image:: https://ci.appveyor.com/api/projects/status/c54uu4rxlgs2usmj/branch/master?svg=true :target: https://ci.appveyor.com/project/RazerM/outcome/history :alt: Automated test status (Windows) .. image:: https://codecov.io/gh/python-trio/trio/branch/master/graph/badge.svg :target: https://codecov.io/gh/python-trio/outcome :alt: Test coverage outcome ======= Welcome to `outcome `__! Capture the outcome of Python function calls. Extracted from the `Trio `__ project. License: Your choice of MIT or Apache License 2.0 Keywords: result Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Framework :: Trio Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: POSIX :: Linux Classifier: Operating System :: MacOS :: MacOS X Classifier: Operating System :: Microsoft :: Windows Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Requires-Python: >=3.7 Description-Content-Type: text/x-rst outcome-1.2.0/CODE_OF_CONDUCT.md0000644000076500000240000000020114252063111016556 0ustar quentinstaff00000000000000Please adhere to the Trio code of conduct. You can find it here: https://trio.readthedocs.io/en/latest/code-of-conduct.html outcome-1.2.0/LICENSE.APACHE20000644000076500000240000002613614252063111016005 0ustar quentinstaff00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. outcome-1.2.0/LICENSE.MIT0000644000076500000240000000202614252063111015423 0ustar quentinstaff00000000000000The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. outcome-1.2.0/LICENSE0000644000076500000240000000027114252063111014773 0ustar quentinstaff00000000000000This software is made available under the terms of *either* of the licenses found in LICENSE.APACHE2 or LICENSE.MIT. Contributions to are made under the terms of *both* these licenses. outcome-1.2.0/test-requirements.txt0000644000076500000240000000004114252063111020222 0ustar quentinstaff00000000000000pytest pytest-cov pytest-asyncio outcome-1.2.0/tests/0000755000076500000240000000000014252063173015140 5ustar quentinstaff00000000000000outcome-1.2.0/tests/test_sync.py0000644000076500000240000000655514252063111017530 0ustar quentinstaff00000000000000import sys import traceback import pytest import outcome from outcome import AlreadyUsedError, Error, Value def test_Outcome(): v = Value(1) assert v.value == 1 assert v.unwrap() == 1 assert repr(v) == "Value(1)" with pytest.raises(AlreadyUsedError): v.unwrap() v = Value(1) exc = RuntimeError("oops") e = Error(exc) assert e.error is exc with pytest.raises(RuntimeError): e.unwrap() with pytest.raises(AlreadyUsedError): e.unwrap() assert repr(e) == f"Error({exc!r})" e = Error(exc) with pytest.raises(TypeError): Error("hello") with pytest.raises(TypeError): Error(RuntimeError) def expect_1(): assert (yield) == 1 yield "ok" it = iter(expect_1()) next(it) assert v.send(it) == "ok" with pytest.raises(AlreadyUsedError): v.send(it) def expect_RuntimeError(): with pytest.raises(RuntimeError): yield yield "ok" it = iter(expect_RuntimeError()) next(it) assert e.send(it) == "ok" with pytest.raises(AlreadyUsedError): e.send(it) def test_Outcome_eq_hash(): v1 = Value(["hello"]) v2 = Value(["hello"]) v3 = Value("hello") v4 = Value("hello") assert v1 == v2 assert v1 != v3 with pytest.raises(TypeError): {v1} assert {v3, v4} == {v3} # exceptions in general compare by identity exc1 = RuntimeError("oops") exc2 = KeyError("foo") e1 = Error(exc1) e2 = Error(exc1) e3 = Error(exc2) e4 = Error(exc2) assert e1 == e2 assert e3 == e4 assert e1 != e3 assert {e1, e2, e3, e4} == {e1, e3} def test_Value_compare(): assert Value(1) < Value(2) assert not Value(3) < Value(2) with pytest.raises(TypeError): Value(1) < Value("foo") def test_capture(): def add(x, y): return x + y v = outcome.capture(add, 2, y=3) assert type(v) == Value assert v.unwrap() == 5 def raise_ValueError(x): raise ValueError(x) e = outcome.capture(raise_ValueError, "two") assert type(e) == Error assert type(e.error) is ValueError assert e.error.args == ("two",) def test_inheritance(): assert issubclass(Value, outcome.Outcome) assert issubclass(Error, outcome.Outcome) def test_traceback_frame_removal(): def raise_ValueError(x): raise ValueError(x) e = outcome.capture(raise_ValueError, 'abc') with pytest.raises(ValueError) as exc_info: e.unwrap() frames = traceback.extract_tb(exc_info.value.__traceback__) functions = [function for _, _, function, _ in frames] assert functions[-2:] == ['unwrap', 'raise_ValueError'] def test_Error_unwrap_does_not_create_reference_cycles(): # See comment in Error.unwrap for why reference cycles are tricky exc = ValueError() err = Error(exc) try: err.unwrap() except ValueError: pass # Top frame in the traceback is the current test function; we don't care # about its references assert exc.__traceback__.tb_frame is sys._getframe() # The next frame down is the 'unwrap' frame; we want to make sure it # doesn't reference the exception (or anything else for that matter, just # to be thorough) unwrap_frame = exc.__traceback__.tb_next.tb_frame assert unwrap_frame.f_code.co_name == "unwrap" assert unwrap_frame.f_locals == {} outcome-1.2.0/tests/test_async.py0000644000076500000240000000303514252063111017657 0ustar quentinstaff00000000000000import asyncio import traceback import pytest import outcome from outcome import AlreadyUsedError, Error, Value pytestmark = pytest.mark.asyncio async def test_acapture(): async def add(x, y): await asyncio.sleep(0) return x + y v = await outcome.acapture(add, 3, y=4) assert v == Value(7) async def raise_ValueError(x): await asyncio.sleep(0) raise ValueError(x) e = await outcome.acapture(raise_ValueError, 9) assert type(e.error) is ValueError assert e.error.args == (9,) async def test_asend(): async def my_agen_func(): assert (yield 1) == "value" with pytest.raises(KeyError): yield 2 yield 3 my_agen = my_agen_func().__aiter__() v = Value("value") e = Error(KeyError()) assert (await my_agen.asend(None)) == 1 assert (await v.asend(my_agen)) == 2 with pytest.raises(AlreadyUsedError): await v.asend(my_agen) assert (await e.asend(my_agen)) == 3 with pytest.raises(AlreadyUsedError): await e.asend(my_agen) with pytest.raises(StopAsyncIteration): await my_agen.asend(None) async def test_traceback_frame_removal(): async def raise_ValueError(x): raise ValueError(x) e = await outcome.acapture(raise_ValueError, 'abc') with pytest.raises(ValueError) as exc_info: e.unwrap() frames = traceback.extract_tb(exc_info.value.__traceback__) functions = [function for _, _, function, _ in frames] assert functions[-2:] == ['unwrap', 'raise_ValueError'] outcome-1.2.0/tests/__init__.py0000644000076500000240000000000014252063111017227 0ustar quentinstaff00000000000000outcome-1.2.0/MANIFEST.in0000644000076500000240000000031714252063111015525 0ustar quentinstaff00000000000000include README.rst CHEATSHEET.rst LICENSE* CODE_OF_CONDUCT* CONTRIBUTING* include .coveragerc .style.yapf include test-requirements.txt recursive-include docs * prune docs/build recursive-include tests *.py outcome-1.2.0/docs/0000755000076500000240000000000014252063173014726 5ustar quentinstaff00000000000000outcome-1.2.0/docs/Makefile0000644000076500000240000000114114252063111016353 0ustar quentinstaff00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SPHINXPROJ = outcome SOURCEDIR = source BUILDDIR = build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) outcome-1.2.0/docs/source/0000755000076500000240000000000014252063173016226 5ustar quentinstaff00000000000000outcome-1.2.0/docs/source/index.rst0000644000076500000240000000056414252063111020064 0ustar quentinstaff00000000000000====================================================== outcome: Capture the outcome of Python function calls. ====================================================== .. toctree:: :maxdepth: 2 tutorial.rst api.rst history.rst ==================== Indices and tables ==================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` * :ref:`glossary` outcome-1.2.0/docs/source/conf.py0000644000076500000240000001337514252063111017526 0ustar quentinstaff00000000000000#!/usr/bin/env python3 # # Documentation build configuration file, created by # sphinx-quickstart on Sat Jan 21 19:11:14 2017. # # 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. # 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. # import os import sys # So autodoc can import our package sys.path.insert(0, os.path.abspath('../..')) # Warn about all references to unknown targets nitpicky = True # Except for these ones, which we expect to point to unknown targets: nitpick_ignore = [ # Format is ('sphinx reference type', 'string'), e.g.: ('py:obj', 'bytes-like'), ] # -- 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.coverage', 'sphinx.ext.napoleon', 'sphinxcontrib_trio', ] intersphinx_mapping = { 'python': ('https://docs.python.org/3', None), 'trio': ('https://trio.readthedocs.io/en/stable', None), } autodoc_member_order = 'bysource' # Add any paths that contain templates here, relative to this directory. templates_path = [] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = 'outcome' copyright = 'The outcome authors' author = 'The outcome authors' # 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. import outcome version = outcome.__version__ # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set 'language' from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # The default language for :: blocks highlight_language = 'python3' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- 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 = 'alabaster' # We have to set this ourselves, not only because it's useful for local # testing, but also because if we don't then RTD will throw away our # html_theme_options. import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # 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 = { # default is 2 # show deeper nesting in the RTD theme's sidebar TOC # https://stackoverflow.com/questions/27669376/ # I'm not 100% sure this actually does anything with our current # versions/settings... 'navigation_depth': 4, 'logo_only': True, } # 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'] # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'outcomedoc' # -- 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': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'outcome.tex', 'Trio Documentation', author, 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'outcome', 'outcome Documentation', [author], 1) ] # -- 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 = [ (master_doc, 'outcome', 'outcome Documentation', author, 'outcome', 'Capture the outcome of Python function call.', 'Miscellaneous'), ] outcome-1.2.0/docs/source/tutorial.rst0000644000076500000240000000126014252063111020612 0ustar quentinstaff00000000000000======== Tutorial ======== .. currentmodule:: outcome Outcome provides a function for capturing the outcome of a Python function call, so that it can be passed around. The basic rule is:: result = outcome.capture(f, *args, **kwargs) x = result.unwrap() is the same as:: x = f(*args, **kwargs) even if ``f`` raises an error. There's also :func:`acapture`:: result = await outcome.acapture(f, *args, **kwargs) x = result.unwrap() which, like before, is the same as:: x = await f(*args, **kwargs) An Outcome object can only be unwrapped once. A second attempt would raise an :class:`AlreadyUsedError`. See the :ref:`api-reference` for the types involved. outcome-1.2.0/docs/source/_static/0000755000076500000240000000000014252063173017654 5ustar quentinstaff00000000000000outcome-1.2.0/docs/source/_static/.gitkeep0000644000076500000240000000000014252063111021263 0ustar quentinstaff00000000000000outcome-1.2.0/docs/source/history.rst0000644000076500000240000000347714252063151020470 0ustar quentinstaff00000000000000Release history =============== .. currentmodule:: outcome .. towncrier release notes start Outcome 1.2.0 (2022-06-14) -------------------------- Features ~~~~~~~~ - Add support for Python 3.9 and 3.10. (`#32 `__) Deprecations and Removals ~~~~~~~~~~~~~~~~~~~~~~~~~ - Drop support for Python 3.6. (`#32 `__) Outcome 1.1.0 (2020-11-16) -------------------------- Bugfixes ~~~~~~~~ - Tweaked the implementation of ``Error.unwrap`` to avoid creating a reference cycle between the exception object and the ``unwrap`` method's frame. This shouldn't affect most users, but it slightly reduces the amount of work that CPython's cycle collector has to do, and may reduce GC pauses in some cases. (`#29 `__) Deprecations and Removals ~~~~~~~~~~~~~~~~~~~~~~~~~ - Drop support for Python 2.7, 3.4, and 3.5. (`#27 `__) Outcome 1.0.1 (2019-10-16) -------------------------- Upgrade to attrs 19.2.0. Outcome 1.0.0 (2018-09-12) -------------------------- Features ~~~~~~~~ - On Python 3, the exception frame generated within :func:`capture` and :func:`acapture` has been removed from the traceback. (`#21 `__) - Outcome is now tested using asyncio instead of trio, which outcome is a dependency of. This makes it easier for third parties to package up Outcome. (`#13 `__) Outcome 0.1.0 (2018-07-10) -------------------------- Features ~~~~~~~~ - An Outcome may only be unwrapped or sent once. Attempting to do so a second time will raise an :class:`AlreadyUsedError`. (`#7 `__) outcome-1.2.0/docs/source/api.rst0000644000076500000240000000053314252063111017522 0ustar quentinstaff00000000000000.. _api-reference: ============= API Reference ============= .. module:: outcome .. autofunction:: capture .. autofunction:: acapture .. autoclass:: Outcome :members: :inherited-members: .. autoclass:: Value :members: :inherited-members: .. autoclass:: Error :members: :inherited-members: .. autoclass:: AlreadyUsedError outcome-1.2.0/docs/make.bat0000644000076500000240000000141314252063111016322 0ustar quentinstaff00000000000000@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set SOURCEDIR=source set BUILDDIR=build set SPHINXPROJ=outcome if "%1" == "" goto help %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% :end popd outcome-1.2.0/setup.py0000644000076500000240000000313114252063111015476 0ustar quentinstaff00000000000000from setuptools import find_packages, setup version = dict() with open('src/outcome/_version.py') as fp: version_mod = fp.read() exec(version_mod, version) LONG_DESC = open('README.rst').read() setup( name='outcome', version=version['__version__'], description='Capture the outcome of Python function calls.', url='https://github.com/python-trio/outcome', project_urls={ "Documentation": "https://outcome.readthedocs.io/en/latest/", "Chat": "https://gitter.im/python-trio/general", }, long_description=LONG_DESC, long_description_content_type='text/x-rst', author='Frazer McLean', author_email='frazer@frazermclean.co.uk', license='MIT OR Apache-2.0', packages=find_packages('src'), package_dir={'': 'src'}, install_requires=['attrs>=19.2.0'], python_requires='>=3.7', keywords='result', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Framework :: Trio', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], ) outcome-1.2.0/CONTRIBUTING.md0000644000076500000240000000021414252063111016214 0ustar quentinstaff00000000000000If you want to contribute to this code, please see the Trio contributing guide: https://trio.readthedocs.io/en/latest/contributing.html outcome-1.2.0/CHEATSHEET.rst0000644000076500000240000000143314252063111016136 0ustar quentinstaff00000000000000Tips ==== To run tests ------------ * Install requirements: ``pip install -r test-requirements.txt`` (possibly in a virtualenv) * Actually run the tests: ``pytest tests`` To run yapf ----------- * Show what changes yapf wants to make: ``yapf -rpd setup.py src tests`` * Apply all changes directly to the source tree: ``yapf -rpi setup.py src tests`` To make a release ----------------- * Update the version in ``outcome/_version.py`` * Run ``towncrier`` to collect your release notes. * Review your release notes. * Check everything in. * Double-check it all works, docs build, etc. * Build your sdist and wheel: ``python setup.py sdist bdist_wheel`` * Upload to PyPI: ``twine upload dist/*`` * Use ``git tag`` to tag your version. * Don't forget to ``git push --tags``. outcome-1.2.0/.style.yapf0000644000076500000240000001237514252063111016075 0ustar quentinstaff00000000000000[style] # Align closing bracket with visual indentation. align_closing_bracket_with_visual_indent=True # Allow dictionary keys to exist on multiple lines. For example: # # x = { # ('this is the first element of a tuple', # 'this is the second element of a tuple'): # value, # } allow_multiline_dictionary_keys=False # Allow lambdas to be formatted on more than one line. allow_multiline_lambdas=False # Insert a blank line before a class-level docstring. blank_line_before_class_docstring=False # Insert a blank line before a 'def' or 'class' immediately nested # within another 'def' or 'class'. For example: # # class Foo: # # <------ this blank line # def method(): # ... blank_line_before_nested_class_or_def=False # Do not split consecutive brackets. Only relevant when # dedent_closing_brackets is set. For example: # # call_func_that_takes_a_dict( # { # 'key1': 'value1', # 'key2': 'value2', # } # ) # # would reformat to: # # call_func_that_takes_a_dict({ # 'key1': 'value1', # 'key2': 'value2', # }) coalesce_brackets=False # The column limit. column_limit=79 # Indent width used for line continuations. continuation_indent_width=4 # Put closing brackets on a separate line, dedented, if the bracketed # expression can't fit in a single line. Applies to all kinds of brackets, # including function definitions and calls. For example: # # config = { # 'key1': 'value1', # 'key2': 'value2', # } # <--- this bracket is dedented and on a separate line # # time_series = self.remote_client.query_entity_counters( # entity='dev3246.region1', # key='dns.query_latency_tcp', # transform=Transformation.AVERAGE(window=timedelta(seconds=60)), # start_ts=now()-timedelta(days=3), # end_ts=now(), # ) # <--- this bracket is dedented and on a separate line dedent_closing_brackets=True # Place each dictionary entry onto its own line. each_dict_entry_on_separate_line=True # The regex for an i18n comment. The presence of this comment stops # reformatting of that line, because the comments are required to be # next to the string they translate. i18n_comment= # The i18n function call names. The presence of this function stops # reformattting on that line, because the string it has cannot be moved # away from the i18n comment. i18n_function_call= # Indent the dictionary value if it cannot fit on the same line as the # dictionary key. For example: # # config = { # 'key1': # 'value1', # 'key2': value1 + # value2, # } indent_dictionary_value=True # The number of columns to use for indentation. indent_width=4 # Join short lines into one line. E.g., single line 'if' statements. join_multiple_lines=False # Use spaces around default or named assigns. spaces_around_default_or_named_assign=False # Use spaces around the power operator. spaces_around_power_operator=False # The number of spaces required before a trailing comment. spaces_before_comment=2 # Insert a space between the ending comma and closing bracket of a list, # etc. space_between_ending_comma_and_closing_bracket=False # Split before arguments if the argument list is terminated by a # comma. split_arguments_when_comma_terminated=True # Set to True to prefer splitting before '&', '|' or '^' rather than # after. split_before_bitwise_operator=True # Split before a dictionary or set generator (comp_for). For example, note # the split before the 'for': # # foo = { # variable: 'Hello world, have a nice day!' # for variable in bar if variable != 42 # } split_before_dict_set_generator=True # If an argument / parameter list is going to be split, then split before # the first argument. split_before_first_argument=True # Set to True to prefer splitting before 'and' or 'or' rather than # after. split_before_logical_operator=True # Split named assignments onto individual lines. split_before_named_assigns=True # The penalty for splitting right after the opening bracket. split_penalty_after_opening_bracket=30 # The penalty for splitting the line after a unary operator. split_penalty_after_unary_operator=10000 # The penalty for splitting right before an if expression. split_penalty_before_if_expr=0 # The penalty of splitting the line around the '&', '|', and '^' # operators. split_penalty_bitwise_operator=300 # The penalty for characters over the column limit. split_penalty_excess_character=4500 # The penalty incurred by adding a line split to the unwrapped line. The # more line splits added the higher the penalty. split_penalty_for_added_line_split=30 # The penalty of splitting a list of "import as" names. For example: # # from a_very_long_or_indented_module_name_yada_yad import (long_argument_1, # long_argument_2, # long_argument_3) # # would reformat to something like: # # from a_very_long_or_indented_module_name_yada_yad import ( # long_argument_1, long_argument_2, long_argument_3) split_penalty_import_names=0 # The penalty of splitting the line around the 'and' and 'or' # operators. split_penalty_logical_operator=0 # Use the Tab character for indentation. use_tabs=False outcome-1.2.0/setup.cfg0000644000076500000240000000051314252063173015616 0ustar quentinstaff00000000000000[bdist_wheel] universal = 1 [isort] multi_line_output = 4 skip = ./build, ./docs known_first_party = outcome [coverage:run] branch = True source = outcome tests/ [coverage:report] precision = 1 exclude_lines = pragma: no cover abc.abstractmethod [tool:pytest] asyncio_mode = strict [egg_info] tag_build = tag_date = 0 outcome-1.2.0/README.rst0000644000076500000240000000210314252063111015451 0ustar quentinstaff00000000000000.. image:: https://img.shields.io/badge/chat-join%20now-blue.svg :target: https://gitter.im/python-trio/general :alt: Join chatroom .. image:: https://img.shields.io/badge/docs-read%20now-blue.svg :target: https://outcome.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status .. image:: https://travis-ci.org/python-trio/trio.svg?branch=master :target: https://travis-ci.org/python-trio/outcome :alt: Automated test status (Linux and MacOS) .. image:: https://ci.appveyor.com/api/projects/status/c54uu4rxlgs2usmj/branch/master?svg=true :target: https://ci.appveyor.com/project/RazerM/outcome/history :alt: Automated test status (Windows) .. image:: https://codecov.io/gh/python-trio/trio/branch/master/graph/badge.svg :target: https://codecov.io/gh/python-trio/outcome :alt: Test coverage outcome ======= Welcome to `outcome `__! Capture the outcome of Python function calls. Extracted from the `Trio `__ project. License: Your choice of MIT or Apache License 2.0 outcome-1.2.0/src/0000755000076500000240000000000014252063173014565 5ustar quentinstaff00000000000000outcome-1.2.0/src/outcome.egg-info/0000755000076500000240000000000014252063173017732 5ustar quentinstaff00000000000000outcome-1.2.0/src/outcome.egg-info/PKG-INFO0000644000076500000240000000475314252063173021040 0ustar quentinstaff00000000000000Metadata-Version: 2.1 Name: outcome Version: 1.2.0 Summary: Capture the outcome of Python function calls. Home-page: https://github.com/python-trio/outcome Author: Frazer McLean Author-email: frazer@frazermclean.co.uk License: MIT OR Apache-2.0 Project-URL: Documentation, https://outcome.readthedocs.io/en/latest/ Project-URL: Chat, https://gitter.im/python-trio/general Description: .. image:: https://img.shields.io/badge/chat-join%20now-blue.svg :target: https://gitter.im/python-trio/general :alt: Join chatroom .. image:: https://img.shields.io/badge/docs-read%20now-blue.svg :target: https://outcome.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status .. image:: https://travis-ci.org/python-trio/trio.svg?branch=master :target: https://travis-ci.org/python-trio/outcome :alt: Automated test status (Linux and MacOS) .. image:: https://ci.appveyor.com/api/projects/status/c54uu4rxlgs2usmj/branch/master?svg=true :target: https://ci.appveyor.com/project/RazerM/outcome/history :alt: Automated test status (Windows) .. image:: https://codecov.io/gh/python-trio/trio/branch/master/graph/badge.svg :target: https://codecov.io/gh/python-trio/outcome :alt: Test coverage outcome ======= Welcome to `outcome `__! Capture the outcome of Python function calls. Extracted from the `Trio `__ project. License: Your choice of MIT or Apache License 2.0 Keywords: result Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Framework :: Trio Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: POSIX :: Linux Classifier: Operating System :: MacOS :: MacOS X Classifier: Operating System :: Microsoft :: Windows Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Requires-Python: >=3.7 Description-Content-Type: text/x-rst outcome-1.2.0/src/outcome.egg-info/SOURCES.txt0000644000076500000240000000121214252063173021612 0ustar quentinstaff00000000000000.style.yapf CHEATSHEET.rst CODE_OF_CONDUCT.md CONTRIBUTING.md LICENSE LICENSE.APACHE2 LICENSE.MIT MANIFEST.in README.rst setup.cfg setup.py test-requirements.txt docs/Makefile docs/make.bat docs/source/api.rst docs/source/conf.py docs/source/history.rst docs/source/index.rst docs/source/tutorial.rst docs/source/_static/.gitkeep src/outcome/__init__.py src/outcome/_impl.py src/outcome/_util.py src/outcome/_version.py src/outcome.egg-info/PKG-INFO src/outcome.egg-info/SOURCES.txt src/outcome.egg-info/dependency_links.txt src/outcome.egg-info/requires.txt src/outcome.egg-info/top_level.txt tests/__init__.py tests/test_async.py tests/test_sync.pyoutcome-1.2.0/src/outcome.egg-info/requires.txt0000644000076500000240000000001614252063173022327 0ustar quentinstaff00000000000000attrs>=19.2.0 outcome-1.2.0/src/outcome.egg-info/top_level.txt0000644000076500000240000000001014252063173022453 0ustar quentinstaff00000000000000outcome outcome-1.2.0/src/outcome.egg-info/dependency_links.txt0000644000076500000240000000000114252063173024000 0ustar quentinstaff00000000000000 outcome-1.2.0/src/outcome/0000755000076500000240000000000014252063173016240 5ustar quentinstaff00000000000000outcome-1.2.0/src/outcome/_impl.py0000644000076500000240000001114114252063111017700 0ustar quentinstaff00000000000000import abc import attr from ._util import AlreadyUsedError, remove_tb_frames __all__ = ['Error', 'Outcome', 'Value', 'acapture', 'capture'] def capture(sync_fn, *args, **kwargs): """Run ``sync_fn(*args, **kwargs)`` and capture the result. Returns: Either a :class:`Value` or :class:`Error` as appropriate. """ try: return Value(sync_fn(*args, **kwargs)) except BaseException as exc: exc = remove_tb_frames(exc, 1) return Error(exc) async def acapture(async_fn, *args, **kwargs): """Run ``await async_fn(*args, **kwargs)`` and capture the result. Returns: Either a :class:`Value` or :class:`Error` as appropriate. """ try: return Value(await async_fn(*args, **kwargs)) except BaseException as exc: exc = remove_tb_frames(exc, 1) return Error(exc) @attr.s(repr=False, init=False, slots=True) class Outcome(abc.ABC): """An abstract class representing the result of a Python computation. This class has two concrete subclasses: :class:`Value` representing a value, and :class:`Error` representing an exception. In addition to the methods described below, comparison operators on :class:`Value` and :class:`Error` objects (``==``, ``<``, etc.) check that the other object is also a :class:`Value` or :class:`Error` object respectively, and then compare the contained objects. :class:`Outcome` objects are hashable if the contained objects are hashable. """ _unwrapped = attr.ib(default=False, eq=False, init=False) def _set_unwrapped(self): if self._unwrapped: raise AlreadyUsedError object.__setattr__(self, '_unwrapped', True) @abc.abstractmethod def unwrap(self): """Return or raise the contained value or exception. These two lines of code are equivalent:: x = fn(*args) x = outcome.capture(fn, *args).unwrap() """ @abc.abstractmethod def send(self, gen): """Send or throw the contained value or exception into the given generator object. Args: gen: A generator object supporting ``.send()`` and ``.throw()`` methods. """ @abc.abstractmethod async def asend(self, agen): """Send or throw the contained value or exception into the given async generator object. Args: agen: An async generator object supporting ``.asend()`` and ``.athrow()`` methods. """ @attr.s(frozen=True, repr=False, slots=True) class Value(Outcome): """Concrete :class:`Outcome` subclass representing a regular value. """ value = attr.ib() """The contained value.""" def __repr__(self): return f'Value({self.value!r})' def unwrap(self): self._set_unwrapped() return self.value def send(self, gen): self._set_unwrapped() return gen.send(self.value) async def asend(self, agen): self._set_unwrapped() return await agen.asend(self.value) @attr.s(frozen=True, repr=False, slots=True) class Error(Outcome): """Concrete :class:`Outcome` subclass representing a raised exception. """ error = attr.ib(validator=attr.validators.instance_of(BaseException)) """The contained exception object.""" def __repr__(self): return f'Error({self.error!r})' def unwrap(self): self._set_unwrapped() # Tracebacks show the 'raise' line below out of context, so let's give # this variable a name that makes sense out of context. captured_error = self.error try: raise captured_error finally: # We want to avoid creating a reference cycle here. Python does # collect cycles just fine, so it wouldn't be the end of the world # if we did create a cycle, but the cyclic garbage collector adds # latency to Python programs, and the more cycles you create, the # more often it runs, so it's nicer to avoid creating them in the # first place. For more details see: # # https://github.com/python-trio/trio/issues/1770 # # In particuar, by deleting this local variables from the 'unwrap' # methods frame, we avoid the 'captured_error' object's # __traceback__ from indirectly referencing 'captured_error'. del captured_error, self def send(self, it): self._set_unwrapped() return it.throw(self.error) async def asend(self, agen): self._set_unwrapped() return await agen.athrow(self.error) outcome-1.2.0/src/outcome/_version.py0000644000076500000240000000013114252063151020425 0ustar quentinstaff00000000000000# This file is imported from __init__.py and exec'd from setup.py __version__ = "1.2.0" outcome-1.2.0/src/outcome/__init__.py0000644000076500000240000000053714252063111020346 0ustar quentinstaff00000000000000"""Top-level package for outcome.""" from ._impl import Error, Outcome, Value, acapture, capture from ._util import AlreadyUsedError, fixup_module_metadata from ._version import __version__ __all__ = ( 'Error', 'Outcome', 'Value', 'acapture', 'capture', 'AlreadyUsedError' ) fixup_module_metadata(__name__, globals()) del fixup_module_metadata outcome-1.2.0/src/outcome/_util.py0000644000076500000240000000126114252063111017716 0ustar quentinstaff00000000000000class AlreadyUsedError(RuntimeError): """An Outcome can only be unwrapped once.""" pass def fixup_module_metadata(module_name, namespace): def fix_one(obj): mod = getattr(obj, "__module__", None) if mod is not None and mod.startswith("outcome."): obj.__module__ = module_name if isinstance(obj, type): for attr_value in obj.__dict__.values(): fix_one(attr_value) for objname in namespace["__all__"]: obj = namespace[objname] fix_one(obj) def remove_tb_frames(exc, n): tb = exc.__traceback__ for _ in range(n): tb = tb.tb_next return exc.with_traceback(tb)