pax_global_header00006660000000000000000000000064145667450000014521gustar00rootroot0000000000000052 comment=ae020e13b98d276a6558ffc25e82509fd4c288f0 sniffio-1.3.1/000077500000000000000000000000001456674500000131605ustar00rootroot00000000000000sniffio-1.3.1/.coveragerc000066400000000000000000000001611456674500000152770ustar00rootroot00000000000000[run] branch=True source=sniffio [report] precision = 1 exclude_lines = pragma: no cover abc.abstractmethod sniffio-1.3.1/.github/000077500000000000000000000000001456674500000145205ustar00rootroot00000000000000sniffio-1.3.1/.github/workflows/000077500000000000000000000000001456674500000165555ustar00rootroot00000000000000sniffio-1.3.1/.github/workflows/ci.yml000066400000000000000000000047641456674500000177060ustar00rootroot00000000000000name: CI on: [push, pull_request] jobs: Windows: name: 'Windows (${{ matrix.python }})' runs-on: 'windows-latest' strategy: fail-fast: false matrix: python: ['3.7', '3.8', '3.9', '3.10', '3.11', '3.12'] steps: - name: Checkout uses: actions/checkout@v4 - name: Setup python uses: actions/setup-python@v4 with: python-version: ${{ matrix.python }} allow-prereleases: true cache: pip cache-dependency-path: test-requirements.txt - name: Run tests run: ./ci.sh shell: bash env: # Should match 'name:' up above JOB_NAME: 'Windows (${{ matrix.python }})' Ubuntu: name: 'Ubuntu (${{ matrix.python }}${{ matrix.extra_name }})' timeout-minutes: 10 runs-on: 'ubuntu-latest' strategy: fail-fast: false matrix: python: ['3.7', '3.8', '3.9', '3.10', '3.11', '3.12-dev'] check_formatting: ['0'] extra_name: [''] include: - python: '3.10' check_formatting: '1' extra_name: ', check formatting' steps: - name: Checkout uses: actions/checkout@v4 - name: Setup python uses: actions/setup-python@v4 if: "!endsWith(matrix.python, '-dev')" with: python-version: ${{ matrix.python }} cache: pip cache-dependency-path: test-requirements.txt - name: Setup python (dev) uses: deadsnakes/action@v3.0.1 if: endsWith(matrix.python, '-dev') with: python-version: '${{ matrix.python }}' - name: Run tests run: ./ci.sh env: CHECK_FORMATTING: '${{ matrix.check_formatting }}' # Should match 'name:' up above JOB_NAME: 'Ubuntu (${{ matrix.python }}${{ matrix.extra_name }})' macOS: name: 'macOS (${{ matrix.python }})' timeout-minutes: 10 runs-on: 'macos-latest' strategy: fail-fast: false matrix: python: ['3.7', '3.8', '3.9', '3.10', '3.11', '3.12'] steps: - name: Checkout uses: actions/checkout@v4 - name: Setup python uses: actions/setup-python@v4 with: python-version: ${{ matrix.python }} allow-prereleases: true cache: pip cache-dependency-path: test-requirements.txt - name: Run tests run: ./ci.sh env: # Should match 'name:' up above JOB_NAME: 'macOS (${{ matrix.python }})' sniffio-1.3.1/.gitignore000066400000000000000000000011041456674500000151440ustar00rootroot00000000000000# Add any project-specific files here: # Sphinx docs docs/build/ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *~ \#* .#* # C extensions *.so # Distribution / packaging .Python /build/ /develop-eggs/ /dist/ /eggs/ /lib/ /lib64/ /parts/ /sdist/ /var/ *.egg-info/ .installed.cfg *.egg # Installer logs pip-log.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache .pytest_cache nosetests.xml coverage.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject # Rope .ropeproject # Django stuff: *.log *.pot sniffio-1.3.1/.mypy.ini000066400000000000000000000004431456674500000147360ustar00rootroot00000000000000[mypy] # Error codes can be used to write more specific `type: ignore` comments. show_error_codes = True [mypy-curio.*] # Curio doesn't provide type hints. ignore_missing_imports = True [mypy-pytest.*] # The version of pytest used doesn't provide type hints. ignore_missing_imports = True sniffio-1.3.1/.readthedocs.yml000066400000000000000000000003311456674500000162430ustar00rootroot00000000000000# https://docs.readthedocs.io/en/latest/yaml-config.html version: 2 build: os: ubuntu-22.04 tools: python: "3.8" formats: - htmlzip - epub python: install: - requirements: ci/rtd-requirements.txt sniffio-1.3.1/.style.yapf000066400000000000000000000123751456674500000152670ustar00rootroot00000000000000[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 sniffio-1.3.1/CHEATSHEET.rst000066400000000000000000000014311456674500000153260ustar00rootroot00000000000000Tips ==== To run tests ------------ * Install requirements: ``pip install -r test-requirements.txt`` (possibly in a virtualenv) * Actually run the tests: ``pytest sniffio`` To run yapf ----------- * Show what changes yapf wants to make: ``yapf -rpd setup.py sniffio`` * Apply all changes directly to the source tree: ``yapf -rpi setup.py sniffio`` To make a release ----------------- * Update the version in ``sniffio/_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``. sniffio-1.3.1/CODE_OF_CONDUCT.md000066400000000000000000000001421456674500000157540ustar00rootroot00000000000000For the Trio code of conduct, see: https://trio.readthedocs.io/en/latest/code-of-conduct.html sniffio-1.3.1/CONTRIBUTING.md000066400000000000000000000001421456674500000154060ustar00rootroot00000000000000For the Trio contributing guide, see: https://trio.readthedocs.io/en/latest/contributing.html sniffio-1.3.1/LICENSE000066400000000000000000000002711456674500000141650ustar00rootroot00000000000000This 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. sniffio-1.3.1/LICENSE.APACHE2000066400000000000000000000261361456674500000151770ustar00rootroot00000000000000 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. sniffio-1.3.1/LICENSE.MIT000066400000000000000000000020261456674500000146150ustar00rootroot00000000000000The 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. sniffio-1.3.1/MANIFEST.in000066400000000000000000000002621456674500000147160ustar00rootroot00000000000000include README.rst CHEATSHEET.rst LICENSE* CODE_OF_CONDUCT* CONTRIBUTING* include .coveragerc .style.yapf include test-requirements.txt recursive-include docs * prune docs/build sniffio-1.3.1/README.rst000066400000000000000000000050311456674500000146460ustar00rootroot00000000000000.. 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://sniffio.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status .. image:: https://img.shields.io/pypi/v/sniffio.svg :target: https://pypi.org/project/sniffio :alt: Latest PyPi version .. image:: https://img.shields.io/conda/vn/conda-forge/sniffio.svg :target: https://anaconda.org/conda-forge/sniffio :alt: Latest conda-forge version .. image:: https://travis-ci.org/python-trio/sniffio.svg?branch=master :target: https://travis-ci.org/python-trio/sniffio :alt: Automated test status .. image:: https://codecov.io/gh/python-trio/sniffio/branch/master/graph/badge.svg :target: https://codecov.io/gh/python-trio/sniffio :alt: Test coverage ================================================================= sniffio: Sniff out which async library your code is running under ================================================================= You're writing a library. You've decided to be ambitious, and support multiple async I/O packages, like `Trio `__, and `asyncio `__, and ... You've written a bunch of clever code to handle all the differences. But... how do you know *which* piece of clever code to run? This is a tiny package whose only purpose is to let you detect which async library your code is running under. * Documentation: https://sniffio.readthedocs.io * Bug tracker and source code: https://github.com/python-trio/sniffio * License: MIT or Apache License 2.0, your choice * Contributor guide: https://trio.readthedocs.io/en/latest/contributing.html * Code of conduct: Contributors are requested to follow our `code of conduct `_ in all project spaces. This library is maintained by the Trio project, as a service to the async Python community as a whole. Quickstart ---------- .. code-block:: python3 from sniffio import current_async_library import trio import asyncio async def print_library(): library = current_async_library() print("This is:", library) # Prints "This is trio" trio.run(print_library) # Prints "This is asyncio" asyncio.run(print_library()) For more details, including how to add support to new async libraries, `please peruse our fine manual `__. sniffio-1.3.1/ci.sh000077500000000000000000000024731456674500000141200ustar00rootroot00000000000000#!/bin/bash set -ex MYPY_VERSION=0.782 YAPF_VERSION=0.22.0 pip install -U pip setuptools wheel if [ "$CHECK_FORMATTING" = "1" ]; then pip install yapf==${YAPF_VERSION} if ! yapf -rpd sniffio; then cat <= 1.6.1 sphinx_rtd_theme sphinxcontrib-trio sniffio-1.3.1/docs/000077500000000000000000000000001456674500000141105ustar00rootroot00000000000000sniffio-1.3.1/docs/Makefile000066400000000000000000000011411456674500000155450ustar00rootroot00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SPHINXPROJ = sniffio 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) sniffio-1.3.1/docs/make.bat000066400000000000000000000014131456674500000155140ustar00rootroot00000000000000@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set SOURCEDIR=source set BUILDDIR=build set SPHINXPROJ=sniffio 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 sniffio-1.3.1/docs/source/000077500000000000000000000000001456674500000154105ustar00rootroot00000000000000sniffio-1.3.1/docs/source/_static/000077500000000000000000000000001456674500000170365ustar00rootroot00000000000000sniffio-1.3.1/docs/source/_static/.gitkeep000066400000000000000000000000001456674500000204550ustar00rootroot00000000000000sniffio-1.3.1/docs/source/conf.py000066400000000000000000000134411456674500000167120ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # 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 = 'sniffio' copyright = 'The sniffio authors' author = 'The sniffio 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 sniffio version = sniffio.__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 = 'sniffiodoc' # -- 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, 'sniffio.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, 'sniffio', 'sniffio 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, 'sniffio', 'sniffio Documentation', author, 'sniffio', 'Sniff out which async library your code is running under', 'Miscellaneous'), ] sniffio-1.3.1/docs/source/history.rst000066400000000000000000000021471456674500000176470ustar00rootroot00000000000000Release history =============== .. currentmodule:: sniffio .. towncrier release notes start Sniffio 1.3.1 (2024-02-26) -------------------------- Bugfixes ~~~~~~~~ - Added missing ``thread_local`` to ``sniffio.__all__`` (`#44 `__) sniffio 1.3.0 (2022-09-01) -------------------------- Features ~~~~~~~~ - Add support for Python 3.9 and 3.10. (`#29 `__) - Provide ``sniffio.thread_local.name`` for coroutine libraries to set (`#23 `__) Deprecations and Removals ~~~~~~~~~~~~~~~~~~~~~~~~~ - Drop support for Python 3.5 and 3.6. (`#29 `__) sniffio 1.2.0 (2020-10-11) -------------------------- Features ~~~~~~~~ - Include type hints (`#17 `__) sniffio 1.1.0 (2019-04-19) -------------------------- Features ~~~~~~~~ - Sniff for curio. (`#5 `__) sniffio 1.0.0 (2018-07-31) -------------------------- Initial release. sniffio-1.3.1/docs/source/index.rst000066400000000000000000000064651456674500000172640ustar00rootroot00000000000000.. documentation master file, created by sphinx-quickstart on Sat Jan 21 19:11:14 2017. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. ================================================================= sniffio: Sniff out which async library your code is running under ================================================================= You're writing a library. You've decided to be ambitious, and support multiple async I/O packages, like `Trio `__, and `asyncio `__, and ... You've written a bunch of clever code to handle all the differences. But... how do you know *which* piece of clever code to run? This is a tiny package whose only purpose is to let you detect which async library your code is running under. * Documentation: https://sniffio.readthedocs.io * Bug tracker and source code: https://github.com/python-trio/sniffio * License: MIT or Apache License 2.0, your choice * Contributor guide: https://trio.readthedocs.io/en/latest/contributing.html * Code of conduct: Contributors are requested to follow our `code of conduct `_ in all project spaces. This library is maintained by the Trio project, as a service to the async Python community as a whole. .. module:: sniffio Usage ===== .. autofunction:: current_async_library .. autoexception:: AsyncLibraryNotFoundError Adding support to a new async library ===================================== If you'd like your library to be detected by ``sniffio``, it's pretty easy. **Step 1:** Pick the magic string that will identify your library. To avoid collisions, this should match your library's PEP 503 normalized name on PyPI. **Step 2:** There's a special :class:`threading.local` object: .. data:: thread_local.name Make sure that whenever your library is calling a coroutine ``throw()``, ``send()``, or ``close()`` that this is set to your identifier string. In most cases, this will be as simple as: .. code-block:: python3 from sniffio import thread_local # Your library's step function def step(...): old_name, thread_local.name = thread_local.name, "my-library's-PyPI-name" try: result = coro.send(None) finally: thread_local.name = old_name **Step 3:** Send us a PR to add your library to the list of supported libraries above. That's it! There are libraries that directly drive a sniffio-naive coroutine from another, outer sniffio-aware coroutine such as `trio_asyncio`. These libraries should make sure to set the correct value while calling a synchronous function that will go on to drive the sniffio-naive coroutine. .. code-block:: python3 from sniffio import thread_local # Your library's compatibility loop async def main_loop(self, ...) -> None: ... handle: asyncio.Handle = await self.get_next_handle() old_name, thread_local.name = thread_local.name, "asyncio" try: result = handle._callback(obj._args) finally: thread_local.name = old_name .. toctree:: :maxdepth: 1 history.rst ==================== Indices and tables ==================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` * :ref:`glossary` sniffio-1.3.1/newsfragments/000077500000000000000000000000001456674500000160435ustar00rootroot00000000000000sniffio-1.3.1/newsfragments/.gitkeep000066400000000000000000000000001456674500000174620ustar00rootroot00000000000000sniffio-1.3.1/newsfragments/README.rst000066400000000000000000000025611456674500000175360ustar00rootroot00000000000000Adding newsfragments ==================== This directory collects "newsfragments": short files that each contain a snippet of ReST-formatted text that will be added to the next release notes. This should be a description of aspects of the change (if any) that are relevant to users. (This contrasts with your commit message and PR description, which are a description of the change as relevant to people working on the code itself.) Each file should be named like ``..rst``, where ```` is an issue numbers, and ```` is one of: * ``feature`` * ``bugfix`` * ``doc`` * ``removal`` * ``misc`` So for example: ``123.feature.rst``, ``456.bugfix.rst`` If your PR fixes an issue, use that number here. If there is no issue, then after you submit the PR and get the PR number you can add a newsfragment using that instead. Note that the ``towncrier`` tool will automatically reflow your text, so don't try to do any fancy formatting. You can install ``towncrier`` and then run ``towncrier --draft`` if you want to get a preview of how your change will look in the final release notes. Making releases =============== ``pip install towncrier``, then run ``towncrier``. (You can use ``towncrier --draft`` to get a preview of what this will do.) You can configure ``towncrier`` (for example: customizing the different types of changes) by modifying ``pyproject.toml``. sniffio-1.3.1/pyproject.toml000066400000000000000000000030511456674500000160730ustar00rootroot00000000000000[build-system] requires = [ "setuptools >= 64", "setuptools_scm >= 6.4" ] build-backend = "setuptools.build_meta" [project] name = "sniffio" description = "Sniff out which async library your code is running under" readme = "README.rst" authors = [{name = "Nathaniel J. Smith", email = "njs@pobox.com"}] license = {text = "MIT OR Apache-2.0"} keywords = ["async", "trio", "asyncio"] classifiers = [ "License :: OSI Approved :: MIT License", "License :: OSI Approved :: Apache Software License", "Framework :: Trio", "Framework :: AsyncIO", "Operating System :: POSIX :: Linux", "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft :: Windows", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Intended Audience :: Developers", "Development Status :: 5 - Production/Stable", ] requires-python = ">= 3.7" dynamic = ["version"] [project.urls] Homepage = "https://github.com/python-trio/sniffio" Documentation = "https://sniffio.readthedocs.io/" Changelog = "https://sniffio.readthedocs.io/en/latest/history.html" [tool.setuptools.dynamic] version = {attr = "sniffio._version.__version__"} [tool.setuptools.packages.find] include = ["sniffio*"] namespaces = false [tool.towncrier] package = "sniffio" filename = "docs/source/history.rst" directory = "newsfragments" underlines = ["-", "~", "^"] issue_format = "`#{issue} `__" sniffio-1.3.1/sniffio/000077500000000000000000000000001456674500000146155ustar00rootroot00000000000000sniffio-1.3.1/sniffio/__init__.py000066400000000000000000000005171456674500000167310ustar00rootroot00000000000000"""Top-level package for sniffio.""" __all__ = [ "current_async_library", "AsyncLibraryNotFoundError", "current_async_library_cvar", "thread_local", ] from ._version import __version__ from ._impl import ( current_async_library, AsyncLibraryNotFoundError, current_async_library_cvar, thread_local, ) sniffio-1.3.1/sniffio/_impl.py000066400000000000000000000054331456674500000162740ustar00rootroot00000000000000from contextvars import ContextVar from typing import Optional import sys import threading current_async_library_cvar = ContextVar( "current_async_library_cvar", default=None ) # type: ContextVar[Optional[str]] class _ThreadLocal(threading.local): # Since threading.local provides no explicit mechanism is for setting # a default for a value, a custom class with a class attribute is used # instead. name = None # type: Optional[str] thread_local = _ThreadLocal() class AsyncLibraryNotFoundError(RuntimeError): pass def current_async_library() -> str: """Detect which async library is currently running. The following libraries are currently supported: ================ =========== ============================ Library Requires Magic string ================ =========== ============================ **Trio** Trio v0.6+ ``"trio"`` **Curio** - ``"curio"`` **asyncio** ``"asyncio"`` **Trio-asyncio** v0.8.2+ ``"trio"`` or ``"asyncio"``, depending on current mode ================ =========== ============================ Returns: A string like ``"trio"``. Raises: AsyncLibraryNotFoundError: if called from synchronous context, or if the current async library was not recognized. Examples: .. code-block:: python3 from sniffio import current_async_library async def generic_sleep(seconds): library = current_async_library() if library == "trio": import trio await trio.sleep(seconds) elif library == "asyncio": import asyncio await asyncio.sleep(seconds) # ... and so on ... else: raise RuntimeError(f"Unsupported library {library!r}") """ value = thread_local.name if value is not None: return value value = current_async_library_cvar.get() if value is not None: return value # Need to sniff for asyncio if "asyncio" in sys.modules: import asyncio try: current_task = asyncio.current_task # type: ignore[attr-defined] except AttributeError: current_task = asyncio.Task.current_task # type: ignore[attr-defined] try: if current_task() is not None: return "asyncio" except RuntimeError: pass # Sniff for curio (for now) if 'curio' in sys.modules: from curio.meta import curio_running if curio_running(): return 'curio' raise AsyncLibraryNotFoundError( "unknown async library, or not in async context" ) sniffio-1.3.1/sniffio/_tests/000077500000000000000000000000001456674500000161165ustar00rootroot00000000000000sniffio-1.3.1/sniffio/_tests/__init__.py000066400000000000000000000000001456674500000202150ustar00rootroot00000000000000sniffio-1.3.1/sniffio/_tests/test_sniffio.py000066400000000000000000000040121456674500000211610ustar00rootroot00000000000000import os import sys import pytest from .. import ( current_async_library, AsyncLibraryNotFoundError, current_async_library_cvar, thread_local ) def test_basics_cvar(): with pytest.raises(AsyncLibraryNotFoundError): current_async_library() token = current_async_library_cvar.set("generic-lib") try: assert current_async_library() == "generic-lib" finally: current_async_library_cvar.reset(token) with pytest.raises(AsyncLibraryNotFoundError): current_async_library() def test_basics_tlocal(): with pytest.raises(AsyncLibraryNotFoundError): current_async_library() old_name, thread_local.name = thread_local.name, "generic-lib" try: assert current_async_library() == "generic-lib" finally: thread_local.name = old_name with pytest.raises(AsyncLibraryNotFoundError): current_async_library() def test_asyncio(): import asyncio with pytest.raises(AsyncLibraryNotFoundError): current_async_library() ran = [] async def this_is_asyncio(): assert current_async_library() == "asyncio" # Call it a second time to exercise the caching logic assert current_async_library() == "asyncio" ran.append(True) asyncio.run(this_is_asyncio()) assert ran == [True] with pytest.raises(AsyncLibraryNotFoundError): current_async_library() @pytest.mark.skipif( sys.version_info >= (3, 12), reason= "curio broken on 3.12 (https://github.com/python-trio/sniffio/pull/42)", ) def test_curio(): import curio with pytest.raises(AsyncLibraryNotFoundError): current_async_library() ran = [] async def this_is_curio(): assert current_async_library() == "curio" # Call it a second time to exercise the caching logic assert current_async_library() == "curio" ran.append(True) curio.run(this_is_curio) assert ran == [True] with pytest.raises(AsyncLibraryNotFoundError): current_async_library() sniffio-1.3.1/sniffio/_version.py000066400000000000000000000001311456674500000170060ustar00rootroot00000000000000# This file is imported from __init__.py and exec'd from setup.py __version__ = "1.3.1" sniffio-1.3.1/sniffio/py.typed000066400000000000000000000000001456674500000163020ustar00rootroot00000000000000sniffio-1.3.1/test-requirements.txt000066400000000000000000000000301456674500000174120ustar00rootroot00000000000000pytest pytest-cov curio