Spaces:
Paused
Paused
Deploy Sensorflow Studio
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .venv-deploy/.gitignoreAdded+2
- .venv-deploy/bin/Activate.ps1Added+248
- .venv-deploy/bin/activateAdded+76
- .venv-deploy/bin/activate.cshAdded+27
- .venv-deploy/bin/activate.fishAdded+69
- .venv-deploy/bin/hfAdded+8
- .venv-deploy/bin/httpxAdded+8
- .venv-deploy/bin/huggingface-cliAdded+8
- .venv-deploy/bin/idnaAdded+8
- .venv-deploy/bin/pipAdded+8
- .venv-deploy/bin/pip3Added+8
- .venv-deploy/bin/pip3.14Added+8
- .venv-deploy/bin/pythonAdded
- .venv-deploy/bin/python3Added
- .venv-deploy/bin/python3.14Added
- .venv-deploy/bin/tiny-agentsAdded+8
- .venv-deploy/bin/tqdmAdded+8
- .venv-deploy/bin/𝜋thonAdded
- .venv-deploy/lib/python3.14/site-packages/_yaml/__init__.pyAdded+33
- .venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/INSTALLERAdded+1
- .venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/METADATAAdded+107
- .venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/RECORDAdded+96
- .venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/WHEELAdded+5
- .venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/entry_points.txtAdded+2
- .venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/licenses/LICENSEAdded+20
- .venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/scm_file_list.jsonAdded+119
- .venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/scm_version.jsonAdded+8
- .venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/top_level.txtAdded+1
- .venv-deploy/lib/python3.14/site-packages/anyio/__init__.pyAdded+115
- .venv-deploy/lib/python3.14/site-packages/anyio/_backends/__init__.pyAdded
- .venv-deploy/lib/python3.14/site-packages/anyio/_backends/_asyncio.pyAdded
- .venv-deploy/lib/python3.14/site-packages/anyio/_backends/_trio.pyAdded+1468
- .venv-deploy/lib/python3.14/site-packages/anyio/_core/__init__.pyAdded
- .venv-deploy/lib/python3.14/site-packages/anyio/_core/_asyncio_selector_thread.pyAdded+167
- .venv-deploy/lib/python3.14/site-packages/anyio/_core/_contextmanagers.pyAdded+200
- .venv-deploy/lib/python3.14/site-packages/anyio/_core/_eventloop.pyAdded+240
- .venv-deploy/lib/python3.14/site-packages/anyio/_core/_exceptions.pyAdded+177
- .venv-deploy/lib/python3.14/site-packages/anyio/_core/_fileio.pyAdded+960
- .venv-deploy/lib/python3.14/site-packages/anyio/_core/_resources.pyAdded+18
- .venv-deploy/lib/python3.14/site-packages/anyio/_core/_signals.pyAdded+29
- .venv-deploy/lib/python3.14/site-packages/anyio/_core/_sockets.pyAdded+1011
- .venv-deploy/lib/python3.14/site-packages/anyio/_core/_streams.pyAdded+52
- .venv-deploy/lib/python3.14/site-packages/anyio/_core/_subprocesses.pyAdded+196
- .venv-deploy/lib/python3.14/site-packages/anyio/_core/_synchronization.pyAdded+772
- .venv-deploy/lib/python3.14/site-packages/anyio/_core/_tasks.pyAdded+412
- .venv-deploy/lib/python3.14/site-packages/anyio/_core/_tempfile.pyAdded+613
- .venv-deploy/lib/python3.14/site-packages/anyio/_core/_testing.pyAdded+82
- .venv-deploy/lib/python3.14/site-packages/anyio/_core/_typedattr.pyAdded+81
- .venv-deploy/lib/python3.14/site-packages/anyio/abc/__init__.pyAdded+58
- .venv-deploy/lib/python3.14/site-packages/anyio/abc/_eventloop.pyAdded+410
12# Created by venv; see https://docs.python.org/3/library/venv.html*123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248<#
.Synopsis
Activate a Python virtual environment for the current PowerShell session.
.Description
Pushes the python executable for a virtual environment to the front of the
$Env:PATH environment variable and sets the prompt to signify that you are
in a Python virtual environment. Makes use of the command line switches as
well as the `pyvenv.cfg` file values present in the virtual environment.
.Parameter VenvDir
Path to the directory that contains the virtual environment to activate. The
default value for this is the parent of the directory that the Activate.ps1
script is located within.
.Parameter Prompt
The prompt prefix to display when this virtual environment is activated. By
default, this prompt is the name of the virtual environment folder (VenvDir)
surrounded by parentheses and followed by a single space (ie. '(.venv) ').
.Example
Activate.ps1
Activates the Python virtual environment that contains the Activate.ps1 script.
.Example
Activate.ps1 -Verbose
Activates the Python virtual environment that contains the Activate.ps1 script,
and shows extra information about the activation as it executes.
.Example
Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
Activates the Python virtual environment located in the specified location.
.Example
Activate.ps1 -Prompt "MyPython"
Activates the Python virtual environment that contains the Activate.ps1 script,
and prefixes the current prompt with the specified string (surrounded in
parentheses) while the virtual environment is active.
.Notes
On Windows, it may be required to enable this Activate.ps1 script by setting the
execution policy for the user. You can do this by issuing the following PowerShell
command:
PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
For more information on Execution Policies:
https://go.microsoft.com/fwlink/?LinkID=135170
#>
Param(
[Parameter(Mandatory = $false)]
[String]
$VenvDir,
[Parameter(Mandatory = $false)]
[String]
$Prompt
)
<# Function declarations --------------------------------------------------- #>
<#
.Synopsis
Remove all shell session elements added by the Activate script, including the
addition of the virtual environment's Python executable from the beginning of
the PATH variable.
.Parameter NonDestructive
If present, do not remove this function from the global namespace for the
session.
#>
function global:deactivate ([switch]$NonDestructive) {
# Revert to original values
# The prior prompt:
if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
}
# The prior PYTHONHOME:
if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
}
# The prior PATH:
if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
Remove-Item -Path Env:_OLD_VIRTUAL_PATH
}
# Just remove the VIRTUAL_ENV altogether:
if (Test-Path -Path Env:VIRTUAL_ENV) {
Remove-Item -Path env:VIRTUAL_ENV
}
# Just remove VIRTUAL_ENV_PROMPT altogether.
if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) {
Remove-Item -Path env:VIRTUAL_ENV_PROMPT
}
# Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
}
# Leave deactivate function in the global namespace if requested:
if (-not $NonDestructive) {
Remove-Item -Path function:deactivate
}
}
<#
.Description
Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
given folder, and returns them in a map.
For each line in the pyvenv.cfg file, if that line can be parsed into exactly
two strings separated by `=` (with any amount of whitespace surrounding the =)
then it is considered a `key = value` line. The left hand string is the key,
the right hand is the value.
If the value starts with a `'` or a `"` then the first and last character is
stripped from the value before being captured.
.Parameter ConfigDir
Path to the directory that contains the `pyvenv.cfg` file.
#>
function Get-PyVenvConfig(
[String]
$ConfigDir
) {
Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
# Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
$pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
# An empty map will be returned if no config file is found.
$pyvenvConfig = @{ }
if ($pyvenvConfigPath) {
Write-Verbose "File exists, parse `key = value` lines"
$pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
$pyvenvConfigContent | ForEach-Object {
$keyval = $PSItem -split "\s*=\s*", 2
if ($keyval[0] -and $keyval[1]) {
$val = $keyval[1]
# Remove extraneous quotations around a string value.
if ("'""".Contains($val.Substring(0, 1))) {
$val = $val.Substring(1, $val.Length - 2)
}
$pyvenvConfig[$keyval[0]] = $val
Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
}
}
}
return $pyvenvConfig
}
<# Begin Activate script --------------------------------------------------- #>
# Determine the containing directory of this script
$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
$VenvExecDir = Get-Item -Path $VenvExecPath
Write-Verbose "Activation script is located in path: '$VenvExecPath'"
Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
# Set values required in priority: CmdLine, ConfigFile, Default
# First, get the location of the virtual environment, it might not be
# VenvExecDir if specified on the command line.
if ($VenvDir) {
Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
}
else {
Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
$VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
Write-Verbose "VenvDir=$VenvDir"
}
# Next, read the `pyvenv.cfg` file to determine any required value such
# as `prompt`.
$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
# Next, set the prompt from the command line, or the config file, or
# just use the name of the virtual environment folder.
if ($Prompt) {
Write-Verbose "Prompt specified as argument, using '$Prompt'"
}
else {
Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
$Prompt = $pyvenvCfg['prompt'];
}
else {
Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)"
Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
$Prompt = Split-Path -Path $venvDir -Leaf
}
}
Write-Verbose "Prompt = '$Prompt'"
Write-Verbose "VenvDir='$VenvDir'"
# Deactivate any currently active virtual environment, but leave the
# deactivate function in place.
deactivate -nondestructive
# Now set the environment variable VIRTUAL_ENV, used by many tools to determine
# that there is an activated venv.
$env:VIRTUAL_ENV = $VenvDir
$env:VIRTUAL_ENV_PROMPT = $Prompt
if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
Write-Verbose "Setting prompt to '$Prompt'"
# Set the prompt to include the env name
# Make sure _OLD_VIRTUAL_PROMPT is global
function global:_OLD_VIRTUAL_PROMPT { "" }
Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
function global:prompt {
Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
_OLD_VIRTUAL_PROMPT
}
}
# Clear PYTHONHOME
if (Test-Path -Path Env:PYTHONHOME) {
Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
Remove-Item -Path Env:PYTHONHOME
}
# Add the venv to the PATH
Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
$Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576# This file must be used with "source bin/activate" *from bash*# You cannot run it directly
deactivate () { # reset old environment variables if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then PATH="${_OLD_VIRTUAL_PATH:-}" export PATH unset _OLD_VIRTUAL_PATH fi if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}" export PYTHONHOME unset _OLD_VIRTUAL_PYTHONHOME fi
# Call hash to forget past locations. Without forgetting # past locations the $PATH changes we made may not be respected. # See "man bash" for more details. hash is usually a builtin of your shell hash -r 2> /dev/null
if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then PS1="${_OLD_VIRTUAL_PS1:-}" export PS1 unset _OLD_VIRTUAL_PS1 fi
unset VIRTUAL_ENV unset VIRTUAL_ENV_PROMPT if [ ! "${1:-}" = "nondestructive" ] ; then # Self destruct! unset -f deactivate fi}
# unset irrelevant variablesdeactivate nondestructive
# on Windows, a path can contain colons and backslashes and has to be converted:case "$(uname)" in CYGWIN*|MSYS*|MINGW*) # transform D:\path\to\venv to /d/path/to/venv on MSYS and MINGW # and to /cygdrive/d/path/to/venv on Cygwin VIRTUAL_ENV=$(cygpath '/Users/dr.wael/Library/Mobile Documents/com~apple~CloudDocs/Documents/Code/DrivingRepo/hf-space/.venv-deploy') export VIRTUAL_ENV ;; *) # use the path as-is export VIRTUAL_ENV='/Users/dr.wael/Library/Mobile Documents/com~apple~CloudDocs/Documents/Code/DrivingRepo/hf-space/.venv-deploy' ;;esac
_OLD_VIRTUAL_PATH="$PATH"PATH="$VIRTUAL_ENV/"bin":$PATH"export PATH
VIRTUAL_ENV_PROMPT=.venv-deployexport VIRTUAL_ENV_PROMPT
# unset PYTHONHOME if set# this will fail if PYTHONHOME is set to the empty string (which is bad anyway)# could use `if (set -u; : $PYTHONHOME) ;` in bashif [ -n "${PYTHONHOME:-}" ] ; then _OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}" unset PYTHONHOMEfi
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then _OLD_VIRTUAL_PS1="${PS1:-}" PS1="(".venv-deploy") ${PS1:-}" export PS1fi
# Call hash to forget past commands. Without forgetting# past commands the $PATH changes we made may not be respectedhash -r 2> /dev/null123456789101112131415161718192021222324252627# This file must be used with "source bin/activate.csh" *from csh*.# You cannot run it directly.
# Created by Davide Di Blasi <davidedb@gmail.com>.# Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate'
# Unset irrelevant variables.deactivate nondestructive
setenv VIRTUAL_ENV '/Users/dr.wael/Library/Mobile Documents/com~apple~CloudDocs/Documents/Code/DrivingRepo/hf-space/.venv-deploy'
set _OLD_VIRTUAL_PATH="$PATH"setenv PATH "$VIRTUAL_ENV/"bin":$PATH"setenv VIRTUAL_ENV_PROMPT .venv-deploy
set _OLD_VIRTUAL_PROMPT="$prompt"
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then set prompt = "(".venv-deploy") $prompt:q"endif
alias pydoc python -m pydoc
rehash123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869# This file must be used with "source <venv>/bin/activate.fish" *from fish*# (https://fishshell.com/). You cannot run it directly.
function deactivate -d "Exit virtual environment and return to normal shell environment" # reset old environment variables if test -n "$_OLD_VIRTUAL_PATH" set -gx PATH $_OLD_VIRTUAL_PATH set -e _OLD_VIRTUAL_PATH end if test -n "$_OLD_VIRTUAL_PYTHONHOME" set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME set -e _OLD_VIRTUAL_PYTHONHOME end
if test -n "$_OLD_FISH_PROMPT_OVERRIDE" set -e _OLD_FISH_PROMPT_OVERRIDE # prevents error when using nested fish instances (Issue #93858) if functions -q _old_fish_prompt functions -e fish_prompt functions -c _old_fish_prompt fish_prompt functions -e _old_fish_prompt end end
set -e VIRTUAL_ENV set -e VIRTUAL_ENV_PROMPT if test "$argv[1]" != "nondestructive" # Self-destruct! functions -e deactivate endend
# Unset irrelevant variables.deactivate nondestructive
set -gx VIRTUAL_ENV '/Users/dr.wael/Library/Mobile Documents/com~apple~CloudDocs/Documents/Code/DrivingRepo/hf-space/.venv-deploy'
set -gx _OLD_VIRTUAL_PATH $PATHset -gx PATH "$VIRTUAL_ENV/"bin $PATHset -gx VIRTUAL_ENV_PROMPT .venv-deploy
# Unset PYTHONHOME if set.if set -q PYTHONHOME set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME set -e PYTHONHOMEend
if test -z "$VIRTUAL_ENV_DISABLE_PROMPT" # fish uses a function instead of an env var to generate the prompt.
# Save the current fish_prompt function as the function _old_fish_prompt. functions -c fish_prompt _old_fish_prompt
# With the original prompt function renamed, we can override with our own. function fish_prompt # Save the return status of the last command. set -l old_status $status
# Output the venv prompt; color taken from the blue of the Python logo. printf "%s(%s)%s " (set_color 4B8BBE) .venv-deploy (set_color normal)
# Restore the return status of the previous command. echo "exit $old_status" | . # Output the original/"old" prompt. _old_fish_prompt end
set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"end12345678#!/bin/sh'''exec' "/Users/dr.wael/Library/Mobile Documents/com~apple~CloudDocs/Documents/Code/DrivingRepo/hf-space/.venv-deploy/bin/python3.14" "$0" "$@"' '''import sysfrom huggingface_hub.cli.hf import mainif __name__ == '__main__': sys.argv[0] = sys.argv[0].removesuffix('.exe') sys.exit(main())12345678#!/bin/sh'''exec' "/Users/dr.wael/Library/Mobile Documents/com~apple~CloudDocs/Documents/Code/DrivingRepo/hf-space/.venv-deploy/bin/python3.14" "$0" "$@"' '''import sysfrom httpx import mainif __name__ == '__main__': sys.argv[0] = sys.argv[0].removesuffix('.exe') sys.exit(main())12345678#!/bin/sh'''exec' "/Users/dr.wael/Library/Mobile Documents/com~apple~CloudDocs/Documents/Code/DrivingRepo/hf-space/.venv-deploy/bin/python3.14" "$0" "$@"' '''import sysfrom huggingface_hub.cli.deprecated_cli import mainif __name__ == '__main__': sys.argv[0] = sys.argv[0].removesuffix('.exe') sys.exit(main())12345678#!/bin/sh'''exec' "/Users/dr.wael/Library/Mobile Documents/com~apple~CloudDocs/Documents/Code/DrivingRepo/hf-space/.venv-deploy/bin/python3.14" "$0" "$@"' '''import sysfrom idna.cli import mainif __name__ == '__main__': sys.argv[0] = sys.argv[0].removesuffix('.exe') sys.exit(main())12345678#!/bin/sh'''exec' "/Users/dr.wael/Library/Mobile Documents/com~apple~CloudDocs/Documents/Code/DrivingRepo/hf-space/.venv-deploy/bin/python3.14" "$0" "$@"' '''import sysfrom pip._internal.cli.main import mainif __name__ == '__main__': sys.argv[0] = sys.argv[0].removesuffix('.exe') sys.exit(main())12345678#!/bin/sh'''exec' "/Users/dr.wael/Library/Mobile Documents/com~apple~CloudDocs/Documents/Code/DrivingRepo/hf-space/.venv-deploy/bin/python3.14" "$0" "$@"' '''import sysfrom pip._internal.cli.main import mainif __name__ == '__main__': sys.argv[0] = sys.argv[0].removesuffix('.exe') sys.exit(main())12345678#!/bin/sh'''exec' "/Users/dr.wael/Library/Mobile Documents/com~apple~CloudDocs/Documents/Code/DrivingRepo/hf-space/.venv-deploy/bin/python3.14" "$0" "$@"' '''import sysfrom pip._internal.cli.main import mainif __name__ == '__main__': sys.argv[0] = sys.argv[0].removesuffix('.exe') sys.exit(main())12345678#!/bin/sh'''exec' "/Users/dr.wael/Library/Mobile Documents/com~apple~CloudDocs/Documents/Code/DrivingRepo/hf-space/.venv-deploy/bin/python3.14" "$0" "$@"' '''import sysfrom huggingface_hub.inference._mcp.cli import appif __name__ == '__main__': sys.argv[0] = sys.argv[0].removesuffix('.exe') sys.exit(app())12345678#!/bin/sh'''exec' "/Users/dr.wael/Library/Mobile Documents/com~apple~CloudDocs/Documents/Code/DrivingRepo/hf-space/.venv-deploy/bin/python3.14" "$0" "$@"' '''import sysfrom tqdm.cli import mainif __name__ == '__main__': sys.argv[0] = sys.argv[0].removesuffix('.exe') sys.exit(main())123456789101112131415161718192021222324252627282930313233# This is a stub package designed to roughly emulate the _yaml# extension module, which previously existed as a standalone module# and has been moved into the `yaml` package namespace.# It does not perfectly mimic its old counterpart, but should get# close enough for anyone who's relying on it even when they shouldn't.import yaml
# in some circumstances, the yaml module we imoprted may be from a different version, so we need# to tread carefully when poking at it here (it may not have the attributes we expect)if not getattr(yaml, '__with_libyaml__', False): from sys import version_info
exc = ModuleNotFoundError if version_info >= (3, 6) else ImportError raise exc("No module named '_yaml'")else: from yaml._yaml import * import warnings warnings.warn( 'The _yaml extension module is now located at yaml._yaml' ' and its location is subject to change. To use the' ' LibYAML-based parser and emitter, import from `yaml`:' ' `from yaml import CLoader as Loader, CDumper as Dumper`.', DeprecationWarning ) del warnings # Don't `del yaml` here because yaml is actually an existing # namespace member of _yaml.
__name__ = '_yaml'# If the module is top-level (i.e. not a part of any specific package)# then the attribute should be set to ''.# https://docs.python.org/3.8/library/types.html__package__ = ''1pip123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107Metadata-Version: 2.4Name: anyioVersion: 4.14.2Summary: High-level concurrency and networking framework on top of asyncio or TrioAuthor-email: Alex Grönholm <alex.gronholm@nextday.fi>License-Expression: MITProject-URL: Documentation, https://anyio.readthedocs.io/en/latest/Project-URL: Changelog, https://anyio.readthedocs.io/en/stable/versionhistory.htmlProject-URL: Source code, https://github.com/agronholm/anyioProject-URL: Issue tracker, https://github.com/agronholm/anyio/issuesClassifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: DevelopersClassifier: Framework :: AnyIOClassifier: Typing :: TypedClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Programming Language :: Python :: 3.15Requires-Python: >=3.10Description-Content-Type: text/x-rstLicense-File: LICENSERequires-Dist: exceptiongroup>=1.0.2; python_version < "3.11"Requires-Dist: idna>=2.8Requires-Dist: typing_extensions>=4.5; python_version < "3.13"Provides-Extra: trioRequires-Dist: trio>=0.32.0; extra == "trio"Dynamic: license-file
.. image:: https://github.com/agronholm/anyio/actions/workflows/test.yml/badge.svg :target: https://github.com/agronholm/anyio/actions/workflows/test.yml :alt: Build Status.. image:: https://coveralls.io/repos/github/agronholm/anyio/badge.svg?branch=master :target: https://coveralls.io/github/agronholm/anyio?branch=master :alt: Code Coverage.. image:: https://readthedocs.org/projects/anyio/badge/?version=latest :target: https://anyio.readthedocs.io/en/latest/?badge=latest :alt: Documentation.. image:: https://badges.gitter.im/gitterHQ/gitter.svg :target: https://gitter.im/python-trio/AnyIO :alt: Gitter chat.. image:: https://tidelift.com/badges/package/pypi/anyio :target: https://tidelift.com/subscription/pkg/pypi-anyio :alt: Tidelift
AnyIO is an asynchronous networking and concurrency library that works on top of either asyncio_ orTrio_. It implements Trio-like `structured concurrency`_ (SC) on top of asyncio and works in harmonywith the native SC of Trio itself.
Applications and libraries written against AnyIO's API will run unmodified on either asyncio_ orTrio_. AnyIO can also be adopted into a library or application incrementally – bit by bit, no fullrefactoring necessary. It will blend in with the native libraries of your chosen backend.
To find out why you might want to use AnyIO's APIs instead of asyncio's, you can read about it`here <https://anyio.readthedocs.io/en/stable/why.html>`_.
Documentation-------------
View full documentation at: https://anyio.readthedocs.io/
Features--------
AnyIO offers the following functionality:
* Task groups (nurseries_ in trio terminology)* High-level networking (TCP, UDP and UNIX sockets)
* `Happy eyeballs`_ algorithm for TCP connections (more robust than that of asyncio on Python 3.8) * async/await style UDP sockets (unlike asyncio where you still have to use Transports and Protocols)
* A versatile API for byte streams and object streams* Inter-task synchronization and communication (locks, conditions, events, semaphores, object streams)* Worker threads* Subprocesses* Subinterpreter support for code parallelization (on Python 3.13 and later)* Asynchronous file I/O (using worker threads)* Signal handling* Asynchronous versions of the functools_ and itertools_ modules
AnyIO also comes with its own pytest_ plugin which also supports asynchronous fixtures.It even works with the popular Hypothesis_ library.
.. _asyncio: https://docs.python.org/3/library/asyncio.html.. _Trio: https://github.com/python-trio/trio.. _structured concurrency: https://en.wikipedia.org/wiki/Structured_concurrency.. _nurseries: https://trio.readthedocs.io/en/stable/reference-core.html#nurseries-and-spawning.. _Happy eyeballs: https://en.wikipedia.org/wiki/Happy_Eyeballs.. _pytest: https://docs.pytest.org/en/latest/.. _functools: https://docs.python.org/3/library/functools.html.. _itertools: https://docs.python.org/3/library/itertools.html.. _Hypothesis: https://hypothesis.works/
Security contact information----------------------------
To report a security vulnerability, please use the `Tidelift security contact`_.Tidelift will coordinate the fix and disclosure.
.. _Tidelift security contact: https://tidelift.com/security123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596anyio-4.14.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
anyio-4.14.2.dist-info/METADATA,sha256=xeb8Tf2DMxmROyh756MNmTXpIIx--RdjBiGFWqrE1Bk,4645
anyio-4.14.2.dist-info/RECORD,,
anyio-4.14.2.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
anyio-4.14.2.dist-info/entry_points.txt,sha256=_d6Yu6uiaZmNe0CydowirE9Cmg7zUL2g08tQpoS3Qvc,39
anyio-4.14.2.dist-info/licenses/LICENSE,sha256=U2GsncWPLvX9LpsJxoKXwX8ElQkJu8gCO9uC6s8iwrA,1081
anyio-4.14.2.dist-info/scm_file_list.json,sha256=wDSXGv8Ehn5ZW5BhB-RlaAc16zY_OfO27qrlMfMMZy8,3654
anyio-4.14.2.dist-info/scm_version.json,sha256=KgaUx31SyaqGFQFKpG3FO9kCk-ygOKS7Uf0yk56OzaY,161
anyio-4.14.2.dist-info/top_level.txt,sha256=QglSMiWX8_5dpoVAEIHdEYzvqFMdSYWmCj6tYw2ITkQ,6
anyio/__init__.py,sha256=HitUIfzvAojSeaHVmJ9rFn8k_yI63G6s_jUL2QChf4U,6405
anyio/__pycache__/__init__.cpython-314.pyc,,
anyio/__pycache__/from_thread.cpython-314.pyc,,
anyio/__pycache__/functools.cpython-314.pyc,,
anyio/__pycache__/itertools.cpython-314.pyc,,
anyio/__pycache__/lowlevel.cpython-314.pyc,,
anyio/__pycache__/pytest_plugin.cpython-314.pyc,,
anyio/__pycache__/to_interpreter.cpython-314.pyc,,
anyio/__pycache__/to_process.cpython-314.pyc,,
anyio/__pycache__/to_thread.cpython-314.pyc,,
anyio/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
anyio/_backends/__pycache__/__init__.cpython-314.pyc,,
anyio/_backends/__pycache__/_asyncio.cpython-314.pyc,,
anyio/_backends/__pycache__/_trio.cpython-314.pyc,,
anyio/_backends/_asyncio.py,sha256=eK0j8PI0O7y3bX8cUBsafoWP8wsXR-szP6ciyP4Mkkk,104400
anyio/_backends/_trio.py,sha256=hoTXL8zI81v4UE-YT_cr2fzh_zY1mKdmZD3oQHmeR0E,45583
anyio/_core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
anyio/_core/__pycache__/__init__.cpython-314.pyc,,
anyio/_core/__pycache__/_asyncio_selector_thread.cpython-314.pyc,,
anyio/_core/__pycache__/_contextmanagers.cpython-314.pyc,,
anyio/_core/__pycache__/_eventloop.cpython-314.pyc,,
anyio/_core/__pycache__/_exceptions.cpython-314.pyc,,
anyio/_core/__pycache__/_fileio.cpython-314.pyc,,
anyio/_core/__pycache__/_resources.cpython-314.pyc,,
anyio/_core/__pycache__/_signals.cpython-314.pyc,,
anyio/_core/__pycache__/_sockets.cpython-314.pyc,,
anyio/_core/__pycache__/_streams.cpython-314.pyc,,
anyio/_core/__pycache__/_subprocesses.cpython-314.pyc,,
anyio/_core/__pycache__/_synchronization.cpython-314.pyc,,
anyio/_core/__pycache__/_tasks.cpython-314.pyc,,
anyio/_core/__pycache__/_tempfile.cpython-314.pyc,,
anyio/_core/__pycache__/_testing.cpython-314.pyc,,
anyio/_core/__pycache__/_typedattr.cpython-314.pyc,,
anyio/_core/_asyncio_selector_thread.py,sha256=2PdxFM3cs02Kp6BSppbvmRT7q7asreTW5FgBxEsflBo,5626
anyio/_core/_contextmanagers.py,sha256=YInBCabiEeS-UaP_Jdxa1CaFC71ETPW8HZTHIM8Rsc8,7215
anyio/_core/_eventloop.py,sha256=ByZUeJD9alMfcyTseRo5IzTO0IltEul_Gyq9iqSjqDk,6658
anyio/_core/_exceptions.py,sha256=OfzLO4Z3Hog1TnipbIn72YNtkoYxS4lHW9MqKDeGc88,4936
anyio/_core/_fileio.py,sha256=hHfyV0bXDL-R2ZNnInwse3nmTAd36AIz1cBxgmAwzAQ,31358
anyio/_core/_resources.py,sha256=NbmU5O5UX3xEyACnkmYX28Fmwdl-f-ny0tHym26e0w0,435
anyio/_core/_signals.py,sha256=mjTBB2hTKNPRlU0IhnijeQedpWOGERDiMjSlJQsFrug,1016
anyio/_core/_sockets.py,sha256=HtjiSH-yzehlqh_LpD3PGIafDuUCwd8gueUuk5MFeNk,35288
anyio/_core/_streams.py,sha256=FczFwIgDpnkK0bODWJXMpsUJYdvAD04kaUaGzJU8DK0,1806
anyio/_core/_subprocesses.py,sha256=M2GCc4NKXCbB_GtEskJgndiM2b0VS0NK_ohmFxri7O8,7923
anyio/_core/_synchronization.py,sha256=kgPk88-eVOmY-pDNs-ReRbcEelY1a7YczuVBPsZwc8A,21591
anyio/_core/_tasks.py,sha256=y99vRi-AFzEv6kyvIwqrzuskE2NMiNItWnuWGk7eOr4,13126
anyio/_core/_tempfile.py,sha256=jE2w59FRF3yRo4vjkjfZF2YcqsBZvc66VWRwrJGDYGk,19624
anyio/_core/_testing.py,sha256=u7MPqGXwpTxqI7hclSdNA30z2GH1Nw258uwKvy_RfBg,2340
anyio/_core/_typedattr.py,sha256=P4ozZikn3-DbpoYcvyghS_FOYAgbmUxeoU8-L_07pZM,2508
anyio/abc/__init__.py,sha256=6mWhcl_pGXhrgZVHP_TCfMvIXIOp9mroEFM90fYCU_U,2869
anyio/abc/__pycache__/__init__.cpython-314.pyc,,
anyio/abc/__pycache__/_eventloop.cpython-314.pyc,,
anyio/abc/__pycache__/_resources.cpython-314.pyc,,
anyio/abc/__pycache__/_sockets.cpython-314.pyc,,
anyio/abc/__pycache__/_streams.cpython-314.pyc,,
anyio/abc/__pycache__/_subprocesses.cpython-314.pyc,,
anyio/abc/__pycache__/_tasks.cpython-314.pyc,,
anyio/abc/__pycache__/_testing.cpython-314.pyc,,
anyio/abc/_eventloop.py,sha256=OqWYSEj0TmwL_xniCJt3_jHFWsuMk9THk8tCTGsKapI,10681
anyio/abc/_resources.py,sha256=DrYvkNN1hH6Uvv5_5uKySvDsnknGVDe8FCKfko0VtN8,783
anyio/abc/_sockets.py,sha256=OmVDrfemVvF9c5K1tpBgQyV6fn5v0XyCExLAqBOGz9o,13124
anyio/abc/_streams.py,sha256=rnSwRy-6y80TPQtIXit5LjMMiU1CCWS1oMNsmJQHRTg,7582
anyio/abc/_subprocesses.py,sha256=cumAPJTktOQtw63IqG0lDpyZqu_l1EElvQHMiwJgL08,2067
anyio/abc/_tasks.py,sha256=m-FtE4phxeNIELSG7A3H7VUz3jA2Ib5J2JIew8-PS6o,6642
anyio/abc/_testing.py,sha256=9YYM2AXsYFvf4PLjUEr6yRxDiUeB5QbY_gOg0X_C6lY,2034
anyio/from_thread.py,sha256=JYsbaCaIB_Iit6kNhtXSteJGt4PcQ7ncq0nIpcelIrg,19265
anyio/functools.py,sha256=T4JS8IXq-x1S0Lbo2owF8l9fza2KypO147QLeyz4cjs,11797
anyio/itertools.py,sha256=QV-9mnRCr2yBph8g01QFvN-bQ_Yle-8Sl13YSydBlMI,16168
anyio/lowlevel.py,sha256=-59484Z6K5jF7XJJhHxYHIKnvFH_uAeMhl9a_AfaSHI,6280
anyio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
anyio/pytest_plugin.py,sha256=paMpI_VMNQf2bir0LfvgMpXSiYJoHDzWdKUVTyoHmvQ,13609
anyio/streams/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
anyio/streams/__pycache__/__init__.cpython-314.pyc,,
anyio/streams/__pycache__/buffered.cpython-314.pyc,,
anyio/streams/__pycache__/file.cpython-314.pyc,,
anyio/streams/__pycache__/memory.cpython-314.pyc,,
anyio/streams/__pycache__/stapled.cpython-314.pyc,,
anyio/streams/__pycache__/text.cpython-314.pyc,,
anyio/streams/__pycache__/tls.cpython-314.pyc,,
anyio/streams/buffered.py,sha256=u7hCD8SNrYHcutG6K5wEiy1F88-pizgjvEFM22Kq2Cw,6746
anyio/streams/file.py,sha256=6jujI2m-QJITqqKFamrupX_DNsU7y2Fz3omLZxOLuY0,4524
anyio/streams/memory.py,sha256=ZmKWCLpyItOCXmvCQT-L8IyJHNFaB-OVJbrn88CaMo0,10776
anyio/streams/stapled.py,sha256=mDNF9Gj4deXfOuKSZmgkEG-QExYAKAGjYBHbrs-rJaQ,4486
anyio/streams/text.py,sha256=BcVAGJw1VRvtIqnv-o0Rb0pwH7p8vwlvl21xHq522ag,5765
anyio/streams/tls.py,sha256=Gvs--YOoFxcyn-hakXOiPM8H-aEp8nsU6k9rTrKqJA4,15801
anyio/to_interpreter.py,sha256=_mLngrMy97TMR6VbW4Y6YzDUk9ZuPcQMPlkuyRh3C9k,7100
anyio/to_process.py,sha256=jHw7v6XHBNIfYa6DqnqKY0gsRo8ScOCh8fo19fqFvjU,9848
anyio/to_thread.py,sha256=bYszW0lCDfTmLnXbAYic05HEe_Di_0UWKabgL2vU0T0,275012345Wheel-Version: 1.0Generator: setuptools (83.0.0)Root-Is-Purelib: trueTag: py3-none-any
12[pytest11]anyio = anyio.pytest_plugin1234567891011121314151617181920The MIT License (MIT)
Copyright (c) 2018 Alex Grönholm
Permission is hereby granted, free of charge, to any person obtaining a copy ofthis software and associated documentation files (the "Software"), to deal inthe Software without restriction, including without limitation the rights touse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies ofthe 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 allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESSFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS ORCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHERIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119{ "files": [ ".pre-commit-config.yaml", "LICENSE", "pyproject.toml", "AGENTS.md", "README.rst", "CLAUDE.md", ".readthedocs.yml", ".gitignore", "docs/tempfile.rst", "docs/signals.rst", "docs/synchronization.rst", "docs/contextmanagers.rst", "docs/testing.rst", "docs/networking.rst", "docs/contributing.rst", "docs/index.rst", "docs/versionhistory.rst", "docs/threads.rst", "docs/api.rst", "docs/typedattrs.rst", "docs/basics.rst", "docs/fileio.rst", "docs/cancellation.rst", "docs/support.rst", "docs/streams.rst", "docs/why.rst", "docs/tasks.rst", "docs/migration.rst", "docs/conf.py", "docs/subprocesses.rst", "docs/faq.rst", "docs/subinterpreters.rst", "src/anyio/functools.py", "src/anyio/py.typed", "src/anyio/__init__.py", "src/anyio/pytest_plugin.py", "src/anyio/itertools.py", "src/anyio/to_interpreter.py", "src/anyio/from_thread.py", "src/anyio/to_process.py", "src/anyio/to_thread.py", "src/anyio/lowlevel.py", "src/anyio/_backends/_trio.py", "src/anyio/_backends/__init__.py", "src/anyio/_backends/_asyncio.py", "src/anyio/streams/memory.py", "src/anyio/streams/__init__.py", "src/anyio/streams/tls.py", "src/anyio/streams/file.py", "src/anyio/streams/text.py", "src/anyio/streams/stapled.py", "src/anyio/streams/buffered.py", "src/anyio/abc/_eventloop.py", "src/anyio/abc/__init__.py", "src/anyio/abc/_sockets.py", "src/anyio/abc/_tasks.py", "src/anyio/abc/_subprocesses.py", "src/anyio/abc/_resources.py", "src/anyio/abc/_streams.py", "src/anyio/abc/_testing.py", "src/anyio/_core/_typedattr.py", "src/anyio/_core/_eventloop.py", "src/anyio/_core/__init__.py", "src/anyio/_core/_tempfile.py", "src/anyio/_core/_sockets.py", "src/anyio/_core/_tasks.py", "src/anyio/_core/_fileio.py", "src/anyio/_core/_synchronization.py", "src/anyio/_core/_subprocesses.py", "src/anyio/_core/_resources.py", "src/anyio/_core/_contextmanagers.py", "src/anyio/_core/_exceptions.py", "src/anyio/_core/_streams.py", "src/anyio/_core/_signals.py", "src/anyio/_core/_asyncio_selector_thread.py", "src/anyio/_core/_testing.py", "tests/test_itertools.py", "tests/test_functools.py", "tests/test_eventloop.py", "tests/__init__.py", "tests/test_to_thread.py", "tests/test_from_thread.py", "tests/test_lowlevel.py", "tests/test_to_interpreter.py", "tests/test_sockets.py", "tests/test_typedattr.py", "tests/test_to_process.py", "tests/test_all_attributes.py", "tests/test_synchronization.py", "tests/test_debugging.py", "tests/test_contextmanagers.py", "tests/test_fileio.py", "tests/conftest.py", "tests/test_signals.py", "tests/test_deprecations.py", "tests/test_tempfile.py", "tests/test_taskgroups.py", "tests/test_pytest_plugin.py", "tests/test_subprocesses.py", "tests/streams/test_text.py", "tests/streams/test_memory.py", "tests/streams/__init__.py", "tests/streams/test_file.py", "tests/streams/test_stapled.py", "tests/streams/test_tls.py", "tests/streams/test_buffered.py", ".github/pull_request_template.md", ".github/dependabot.yml", ".github/FUNDING.yml", ".github/ISSUE_TEMPLATE/features_request.yaml", ".github/ISSUE_TEMPLATE/bug_report.yaml", ".github/ISSUE_TEMPLATE/config.yml", ".github/workflows/test.yml", ".github/workflows/test-downstream.yml", ".github/workflows/publish.yml" ]}12345678{ "tag": "4.14.2", "distance": 0, "node": "gc384f99687c64c59ed8a11c3a0f11a2d57daff71", "dirty": false, "branch": "HEAD", "node_date": "2026-07-12"}1anyio123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115from __future__ import annotations
from ._core._contextmanagers import AsyncContextManagerMixin as AsyncContextManagerMixinfrom ._core._contextmanagers import ContextManagerMixin as ContextManagerMixinfrom ._core._eventloop import current_time as current_timefrom ._core._eventloop import get_all_backends as get_all_backendsfrom ._core._eventloop import get_available_backends as get_available_backendsfrom ._core._eventloop import get_cancelled_exc_class as get_cancelled_exc_classfrom ._core._eventloop import run as runfrom ._core._eventloop import sleep as sleepfrom ._core._eventloop import sleep_forever as sleep_foreverfrom ._core._eventloop import sleep_until as sleep_untilfrom ._core._exceptions import BrokenResourceError as BrokenResourceErrorfrom ._core._exceptions import BrokenWorkerInterpreter as BrokenWorkerInterpreterfrom ._core._exceptions import BrokenWorkerProcess as BrokenWorkerProcessfrom ._core._exceptions import BusyResourceError as BusyResourceErrorfrom ._core._exceptions import ClosedResourceError as ClosedResourceErrorfrom ._core._exceptions import ConnectionFailed as ConnectionFailedfrom ._core._exceptions import DelimiterNotFound as DelimiterNotFoundfrom ._core._exceptions import EndOfStream as EndOfStreamfrom ._core._exceptions import IncompleteRead as IncompleteReadfrom ._core._exceptions import NoEventLoopError as NoEventLoopErrorfrom ._core._exceptions import RunFinishedError as RunFinishedErrorfrom ._core._exceptions import TaskCancelled as TaskCancelledfrom ._core._exceptions import TaskFailed as TaskFailedfrom ._core._exceptions import TaskNotFinished as TaskNotFinishedfrom ._core._exceptions import TypedAttributeLookupError as TypedAttributeLookupErrorfrom ._core._exceptions import WouldBlock as WouldBlockfrom ._core._fileio import AsyncFile as AsyncFilefrom ._core._fileio import Path as Pathfrom ._core._fileio import open_file as open_filefrom ._core._fileio import wrap_file as wrap_filefrom ._core._resources import aclose_forcefully as aclose_forcefullyfrom ._core._signals import open_signal_receiver as open_signal_receiverfrom ._core._sockets import TCPConnectable as TCPConnectablefrom ._core._sockets import UNIXConnectable as UNIXConnectablefrom ._core._sockets import as_connectable as as_connectablefrom ._core._sockets import connect_tcp as connect_tcpfrom ._core._sockets import connect_unix as connect_unixfrom ._core._sockets import create_connected_udp_socket as create_connected_udp_socketfrom ._core._sockets import ( create_connected_unix_datagram_socket as create_connected_unix_datagram_socket,)from ._core._sockets import create_tcp_listener as create_tcp_listenerfrom ._core._sockets import create_udp_socket as create_udp_socketfrom ._core._sockets import create_unix_datagram_socket as create_unix_datagram_socketfrom ._core._sockets import create_unix_listener as create_unix_listenerfrom ._core._sockets import getaddrinfo as getaddrinfofrom ._core._sockets import getnameinfo as getnameinfofrom ._core._sockets import notify_closing as notify_closingfrom ._core._sockets import wait_readable as wait_readablefrom ._core._sockets import wait_socket_readable as wait_socket_readablefrom ._core._sockets import wait_socket_writable as wait_socket_writablefrom ._core._sockets import wait_writable as wait_writablefrom ._core._streams import create_memory_object_stream as create_memory_object_streamfrom ._core._subprocesses import open_process as open_processfrom ._core._subprocesses import run_process as run_processfrom ._core._synchronization import CapacityLimiter as CapacityLimiterfrom ._core._synchronization import ( CapacityLimiterStatistics as CapacityLimiterStatistics,)from ._core._synchronization import Condition as Conditionfrom ._core._synchronization import ConditionStatistics as ConditionStatisticsfrom ._core._synchronization import Event as Eventfrom ._core._synchronization import EventStatistics as EventStatisticsfrom ._core._synchronization import Lock as Lockfrom ._core._synchronization import LockStatistics as LockStatisticsfrom ._core._synchronization import ResourceGuard as ResourceGuardfrom ._core._synchronization import Semaphore as Semaphorefrom ._core._synchronization import SemaphoreStatistics as SemaphoreStatisticsfrom ._core._tasks import TASK_STATUS_IGNORED as TASK_STATUS_IGNOREDfrom ._core._tasks import CancelScope as CancelScopefrom ._core._tasks import TaskHandle as TaskHandlefrom ._core._tasks import create_task_group as create_task_groupfrom ._core._tasks import current_effective_deadline as current_effective_deadlinefrom ._core._tasks import fail_after as fail_afterfrom ._core._tasks import move_on_after as move_on_afterfrom ._core._tempfile import NamedTemporaryFile as NamedTemporaryFilefrom ._core._tempfile import SpooledTemporaryFile as SpooledTemporaryFilefrom ._core._tempfile import TemporaryDirectory as TemporaryDirectoryfrom ._core._tempfile import TemporaryFile as TemporaryFilefrom ._core._tempfile import gettempdir as gettempdirfrom ._core._tempfile import gettempdirb as gettempdirbfrom ._core._tempfile import mkdtemp as mkdtempfrom ._core._tempfile import mkstemp as mkstempfrom ._core._testing import TaskInfo as TaskInfofrom ._core._testing import get_current_task as get_current_taskfrom ._core._testing import get_running_tasks as get_running_tasksfrom ._core._testing import wait_all_tasks_blocked as wait_all_tasks_blockedfrom ._core._typedattr import TypedAttributeProvider as TypedAttributeProviderfrom ._core._typedattr import TypedAttributeSet as TypedAttributeSetfrom ._core._typedattr import typed_attribute as typed_attribute
# Re-export imports so they look like they live directly in this packagefor __value in list(locals().values()): if getattr(__value, "__module__", "").startswith("anyio."): __value.__module__ = __name__
del __value
def __getattr__(attr: str) -> type[BrokenWorkerInterpreter]: """Support deprecated aliases.""" if attr == "BrokenWorkerIntepreter": import warnings
warnings.warn( "The 'BrokenWorkerIntepreter' alias is deprecated, use 'BrokenWorkerInterpreter' instead.", DeprecationWarning, stacklevel=2, ) return BrokenWorkerInterpreter
raise AttributeError(f"module {__name__!r} has no attribute {attr!r}")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468from __future__ import annotations
import arrayimport mathimport osimport socketimport sysimport typesimport weakreffrom collections.abc import ( AsyncGenerator, AsyncIterator, Awaitable, Callable, Collection, Coroutine, Iterable, Sequence,)from contextlib import AbstractContextManagerfrom contextvars import Contextfrom dataclasses import dataclassfrom functools import partial, wrapsfrom io import IOBasefrom os import PathLikefrom signal import Signalsfrom socket import AddressFamily, SocketKindfrom types import TracebackTypefrom typing import ( IO, TYPE_CHECKING, Any, Generic, Literal, NoReturn, ParamSpec, TypeVar, cast, overload,)
import trio.from_threadimport trio.lowlevelfrom outcome import Error, Outcome, Valuefrom trio.lowlevel import ( current_root_task, current_task, notify_closing, wait_readable, wait_writable,)from trio.socket import SocketType as TrioSocketTypefrom trio.to_thread import run_sync
from .. import ( CapacityLimiterStatistics, EventStatistics, LockStatistics, RunFinishedError, TaskInfo, WouldBlock, abc,)from .._core._eventloop import claim_worker_threadfrom .._core._exceptions import ( BrokenResourceError, BusyResourceError, ClosedResourceError, EndOfStream,)from .._core._sockets import convert_ipv6_sockaddrfrom .._core._streams import create_memory_object_streamfrom .._core._synchronization import ( CapacityLimiter as BaseCapacityLimiter,)from .._core._synchronization import Event as BaseEventfrom .._core._synchronization import Lock as BaseLockfrom .._core._synchronization import ( ResourceGuard, SemaphoreStatistics,)from .._core._synchronization import Semaphore as BaseSemaphorefrom .._core._tasks import CancelScope as BaseCancelScopefrom .._core._tasks import TaskHandlefrom ..abc import IPSockAddrType, UDPPacketType, UNIXDatagramPacketTypefrom ..abc._eventloop import AsyncBackend, StrOrBytesPathfrom ..abc._tasks import T_contra, call_for_coroutine, get_callable_namefrom ..streams.memory import MemoryObjectSendStream
if TYPE_CHECKING: from _typeshed import FileDescriptorLike
if sys.version_info >= (3, 11): from typing import TypeVarTuple, Unpackelse: from exceptiongroup import BaseExceptionGroup from typing_extensions import TypeVarTuple, Unpack
T = TypeVar("T")T_Retval = TypeVar("T_Retval")T_co = TypeVar("T_co", covariant=True)T_SockAddr = TypeVar("T_SockAddr", str, IPSockAddrType)PosArgsT = TypeVarTuple("PosArgsT")P = ParamSpec("P")
def ensure_returns_coro( func: Callable[P, Awaitable[T_Retval]],) -> Callable[P, Coroutine[Any, Any, T_Retval]]: @wraps(func) def wrapper(*args: P.args, **kwargs: P.kwargs) -> Coroutine[Any, Any, T_Retval]: awaitable = func(*args, **kwargs) # Check the common case first. if isinstance(awaitable, Coroutine): return awaitable elif not isinstance(awaitable, Awaitable): # The user violated the type annotations. Still, we should pass this on to # Trio so it can raise with an appropriate message. return awaitable else:
@wraps(func) async def inner_wrapper() -> T_Retval: return await awaitable
return inner_wrapper()
return wrapper
## Event loop#
RunVar = trio.lowlevel.RunVar
## Timeouts and cancellation#
class CancelScope(BaseCancelScope): __slots__ = ("__original",)
def __new__( cls, original: trio.CancelScope | None = None, **kwargs: object ) -> CancelScope: return object.__new__(cls)
def __init__(self, original: trio.CancelScope | None = None, **kwargs: Any) -> None: self.__original = original or trio.CancelScope(**kwargs)
def __enter__(self) -> CancelScope: self.__original.__enter__() return self
def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> bool: return self.__original.__exit__(exc_type, exc_val, exc_tb)
def cancel(self, reason: str | None = None) -> None: self.__original.cancel(reason)
@property def deadline(self) -> float: return self.__original.deadline
@deadline.setter def deadline(self, value: float) -> None: self.__original.deadline = value
@property def cancel_called(self) -> bool: return self.__original.cancel_called
@property def cancelled_caught(self) -> bool: return self.__original.cancelled_caught
@property def shield(self) -> bool: return self.__original.shield
@shield.setter def shield(self, value: bool) -> None: self.__original.shield = value
## Task groups#
empty_start_value = object()
class _TrioTaskStatus(Generic[T_contra], abc.TaskStatus[T_contra]): early_start_value: T_contra | object = empty_start_value real_task_status: trio.TaskStatus[T_contra | None] | None = None
def started(self, value: T_contra | None = None) -> None: if self.real_task_status is None: if self.early_start_value is not empty_start_value: raise RuntimeError("called 'started' twice on the same task status")
self.early_start_value = value else: self.real_task_status.started(value)
class TaskGroup(abc.TaskGroup): def __init__(self) -> None: self._entered = False self._active = False self._nursery_manager = trio.open_nursery(strict_exception_groups=True) self.cancel_scope = None # type: ignore[assignment]
async def __aenter__(self) -> TaskGroup: if self._entered: raise RuntimeError("TaskGroup cannot be entered more than once")
self._entered = True self._active = True self._nursery = await self._nursery_manager.__aenter__() self.cancel_scope = CancelScope(self._nursery.cancel_scope) return self
async def __aexit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> bool: try: # trio.Nursery.__exit__ returns bool; .open_nursery has wrong type return await self._nursery_manager.__aexit__(exc_type, exc_val, exc_tb) # type: ignore[return-value] except BaseExceptionGroup as exc: if not exc.split(trio.Cancelled)[1]: raise trio.Cancelled._create() from exc
raise finally: del exc_val, exc_tb self._active = False
def _check_active(self, coro: Coroutine | None = None) -> None: if not self._active: if coro is not None: coro.close()
raise RuntimeError( "This task group is not active; no new tasks can be started." )
def create_task( self, coro: Coroutine[Any, Any, T_co], *, name: object = None, context: Context | None = None, ) -> TaskHandle[T_co]: if not isinstance(coro, Coroutine): raise TypeError(f"expected a coroutine, got {coro.__class__.__qualname__}")
self._check_active(coro) handle = TaskHandle(coro, name) if context is not None: context.run( partial(self._nursery.start_soon, handle._run_coro, name=handle.name) ) else: self._nursery.start_soon(handle._run_coro, name=handle.name)
return handle
async def start( self, func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]], *args: Unpack[PosArgsT], name: object = None, return_handle: Literal[False] | Literal[True] = False, ) -> Any: handle: TaskHandle[T_co]
async def run_coro_with_task_status( *, task_status: trio.TaskStatus[Any] ) -> None: nonlocal handle wrapper_task_status = _TrioTaskStatus() coro = call_for_coroutine(func, args, task_status=wrapper_task_status) if wrapper_task_status.early_start_value is not empty_start_value: task_status.started(wrapper_task_status.early_start_value) else: wrapper_task_status.real_task_status = task_status
handle = TaskHandle(coro, name) await handle._run_coro()
self._check_active() final_name = get_callable_name(func, name) start_value = await self._nursery.start( run_coro_with_task_status, name=final_name ) if return_handle: handle._start_value = start_value return handle else: return start_value
## Subprocesses#
@dataclass(eq=False)class ReceiveStreamWrapper(abc.ByteReceiveStream): _stream: trio.abc.ReceiveStream
async def receive(self, max_bytes: int | None = None) -> bytes: if max_bytes is not None and max_bytes < 1: raise ValueError("max_bytes must be a positive integer")
try: data = await self._stream.receive_some(max_bytes) except trio.ClosedResourceError as exc: raise ClosedResourceError from exc.__cause__ except trio.BrokenResourceError as exc: raise BrokenResourceError from exc.__cause__
if data: return bytes(data) else: raise EndOfStream
async def aclose(self) -> None: await self._stream.aclose()
@dataclass(eq=False)class SendStreamWrapper(abc.ByteSendStream): _stream: trio.abc.SendStream
async def send(self, item: bytes) -> None: try: await self._stream.send_all(item) except trio.ClosedResourceError as exc: raise ClosedResourceError from exc.__cause__ except trio.BrokenResourceError as exc: raise BrokenResourceError from exc.__cause__
async def aclose(self) -> None: await self._stream.aclose()
@dataclass(eq=False)class Process(abc.Process): _process: trio.Process _stdin: abc.ByteSendStream | None _stdout: abc.ByteReceiveStream | None _stderr: abc.ByteReceiveStream | None
async def aclose(self) -> None: with CancelScope(shield=True): if self._stdin: await self._stdin.aclose() if self._stdout: await self._stdout.aclose() if self._stderr: await self._stderr.aclose()
try: await self.wait() except BaseException: self.kill() with CancelScope(shield=True): await self.wait() raise
async def wait(self) -> int: return await self._process.wait()
def terminate(self) -> None: self._process.terminate()
def kill(self) -> None: self._process.kill()
def send_signal(self, signal: Signals) -> None: self._process.send_signal(signal)
@property def pid(self) -> int: return self._process.pid
@property def returncode(self) -> int | None: return self._process.returncode
@property def stdin(self) -> abc.ByteSendStream | None: return self._stdin
@property def stdout(self) -> abc.ByteReceiveStream | None: return self._stdout
@property def stderr(self) -> abc.ByteReceiveStream | None: return self._stderr
class _ProcessPoolShutdownInstrument(trio.abc.Instrument): def after_run(self) -> None: super().after_run()
current_default_worker_process_limiter: trio.lowlevel.RunVar = RunVar( "current_default_worker_process_limiter")
async def _shutdown_process_pool(workers: set[abc.Process]) -> None: try: await trio.sleep(math.inf) except trio.Cancelled: for process in workers: if process.returncode is None: process.kill()
with CancelScope(shield=True): for process in workers: await process.aclose()
## Sockets and networking#
class _TrioSocketMixin(Generic[T_SockAddr]): def __init__(self, trio_socket: TrioSocketType) -> None: self._trio_socket = trio_socket self._closed = False
def _check_closed(self) -> None: if self._closed: raise ClosedResourceError if self._trio_socket.fileno() < 0: raise BrokenResourceError
@property def _raw_socket(self) -> socket.socket: return self._trio_socket._sock # type: ignore[attr-defined]
async def aclose(self) -> None: if self._trio_socket.fileno() >= 0: self._closed = True self._trio_socket.close()
def _convert_socket_error(self, exc: BaseException) -> NoReturn: if isinstance(exc, trio.ClosedResourceError): raise ClosedResourceError from exc elif self._trio_socket.fileno() < 0 and self._closed: raise ClosedResourceError from None elif isinstance(exc, OSError): raise BrokenResourceError from exc else: raise exc
class SocketStream(_TrioSocketMixin, abc.SocketStream): def __init__(self, trio_socket: TrioSocketType) -> None: super().__init__(trio_socket) self._receive_guard = ResourceGuard("reading from") self._send_guard = ResourceGuard("writing to")
async def receive(self, max_bytes: int = 65536) -> bytes: if max_bytes < 1: raise ValueError("max_bytes must be a positive integer")
with self._receive_guard: try: data = await self._trio_socket.recv(max_bytes) except BaseException as exc: self._convert_socket_error(exc)
if data: return data else: raise EndOfStream
async def send(self, item: bytes) -> None: with self._send_guard: view = memoryview(item) while view: try: bytes_sent = await self._trio_socket.send(view) except BaseException as exc: self._convert_socket_error(exc)
view = view[bytes_sent:]
async def send_eof(self) -> None: self._trio_socket.shutdown(socket.SHUT_WR)
class UNIXSocketStream(SocketStream, abc.UNIXSocketStream): async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]: if not isinstance(msglen, int) or msglen < 0: raise ValueError("msglen must be a non-negative integer") if not isinstance(maxfds, int) or maxfds < 1: raise ValueError("maxfds must be a positive integer")
fds = array.array("i") await trio.lowlevel.checkpoint() with self._receive_guard: while True: try: message, ancdata, flags, addr = await self._trio_socket.recvmsg( msglen, socket.CMSG_LEN(maxfds * fds.itemsize) ) except BaseException as exc: self._convert_socket_error(exc) else: if not message and not ancdata: raise EndOfStream
break
for cmsg_level, cmsg_type, cmsg_data in ancdata: if cmsg_level != socket.SOL_SOCKET or cmsg_type != socket.SCM_RIGHTS: raise RuntimeError( f"Received unexpected ancillary data; message = {message!r}, " f"cmsg_level = {cmsg_level}, cmsg_type = {cmsg_type}" )
fds.frombytes(cmsg_data[: len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
return message, list(fds)
async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None: if not message: raise ValueError("message must not be empty") if not fds: raise ValueError("fds must not be empty")
filenos: list[int] = [] for fd in fds: if isinstance(fd, int): filenos.append(fd) elif isinstance(fd, IOBase): filenos.append(fd.fileno())
fdarray = array.array("i", filenos) await trio.lowlevel.checkpoint() with self._send_guard: while True: try: await self._trio_socket.sendmsg( [message], [ ( socket.SOL_SOCKET, socket.SCM_RIGHTS, fdarray, ) ], ) break except BaseException as exc: self._convert_socket_error(exc)
class TCPSocketListener(_TrioSocketMixin, abc.SocketListener): def __init__(self, raw_socket: socket.socket): super().__init__(trio.socket.from_stdlib_socket(raw_socket)) self._accept_guard = ResourceGuard("accepting connections from")
async def accept(self) -> SocketStream: with self._accept_guard: try: trio_socket, _addr = await self._trio_socket.accept() except BaseException as exc: self._convert_socket_error(exc)
trio_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) return SocketStream(trio_socket)
class UNIXSocketListener(_TrioSocketMixin, abc.SocketListener): def __init__(self, raw_socket: socket.socket): super().__init__(trio.socket.from_stdlib_socket(raw_socket)) self._accept_guard = ResourceGuard("accepting connections from")
async def accept(self) -> UNIXSocketStream: with self._accept_guard: try: trio_socket, _addr = await self._trio_socket.accept() except BaseException as exc: self._convert_socket_error(exc)
return UNIXSocketStream(trio_socket)
class UDPSocket(_TrioSocketMixin[IPSockAddrType], abc.UDPSocket): def __init__(self, trio_socket: TrioSocketType) -> None: super().__init__(trio_socket) self._receive_guard = ResourceGuard("reading from") self._send_guard = ResourceGuard("writing to")
async def receive(self) -> tuple[bytes, IPSockAddrType]: with self._receive_guard: try: data, addr = await self._trio_socket.recvfrom(65536) return data, convert_ipv6_sockaddr(addr) except BaseException as exc: self._convert_socket_error(exc)
async def send(self, item: UDPPacketType) -> None: with self._send_guard: try: await self._trio_socket.sendto(*item) except BaseException as exc: self._convert_socket_error(exc)
class ConnectedUDPSocket(_TrioSocketMixin[IPSockAddrType], abc.ConnectedUDPSocket): def __init__(self, trio_socket: TrioSocketType) -> None: super().__init__(trio_socket) self._receive_guard = ResourceGuard("reading from") self._send_guard = ResourceGuard("writing to")
async def receive(self) -> bytes: with self._receive_guard: try: return await self._trio_socket.recv(65536) except BaseException as exc: self._convert_socket_error(exc)
async def send(self, item: bytes) -> None: with self._send_guard: try: await self._trio_socket.send(item) except BaseException as exc: self._convert_socket_error(exc)
class UNIXDatagramSocket(_TrioSocketMixin[str], abc.UNIXDatagramSocket): def __init__(self, trio_socket: TrioSocketType) -> None: super().__init__(trio_socket) self._receive_guard = ResourceGuard("reading from") self._send_guard = ResourceGuard("writing to")
async def receive(self) -> UNIXDatagramPacketType: with self._receive_guard: try: data, addr = await self._trio_socket.recvfrom(65536) return data, addr except BaseException as exc: self._convert_socket_error(exc)
async def send(self, item: UNIXDatagramPacketType) -> None: with self._send_guard: try: await self._trio_socket.sendto(*item) except BaseException as exc: self._convert_socket_error(exc)
class ConnectedUNIXDatagramSocket( _TrioSocketMixin[str], abc.ConnectedUNIXDatagramSocket): def __init__(self, trio_socket: TrioSocketType) -> None: super().__init__(trio_socket) self._receive_guard = ResourceGuard("reading from") self._send_guard = ResourceGuard("writing to")
async def receive(self) -> bytes: with self._receive_guard: try: return await self._trio_socket.recv(65536) except BaseException as exc: self._convert_socket_error(exc)
async def send(self, item: bytes) -> None: with self._send_guard: try: await self._trio_socket.send(item) except BaseException as exc: self._convert_socket_error(exc)
## Synchronization#
class Event(BaseEvent): __slots__ = ("__original",)
def __new__(cls) -> Event: return object.__new__(cls)
def __init__(self) -> None: self.__original = trio.Event()
def is_set(self) -> bool: return self.__original.is_set()
async def wait(self) -> None: return await self.__original.wait()
def statistics(self) -> EventStatistics: orig_statistics = self.__original.statistics() return EventStatistics(tasks_waiting=orig_statistics.tasks_waiting)
def set(self) -> None: self.__original.set()
class Lock(BaseLock): __slots__ = "_fast_acquire", "__original"
def __new__(cls, *, fast_acquire: bool = False) -> Lock: return object.__new__(cls)
def __init__(self, *, fast_acquire: bool = False) -> None: self._fast_acquire = fast_acquire self.__original = trio.Lock()
@staticmethod def _convert_runtime_error_msg(exc: RuntimeError) -> None: if exc.args == ("attempt to re-acquire an already held Lock",): exc.args = ("Attempted to acquire an already held Lock",)
async def acquire(self) -> None: if not self._fast_acquire: try: await self.__original.acquire() except RuntimeError as exc: self._convert_runtime_error_msg(exc) raise
return
# This is the "fast path" where we don't let other tasks run await trio.lowlevel.checkpoint_if_cancelled() try: self.__original.acquire_nowait() except trio.WouldBlock: await self.__original._lot.park() except RuntimeError as exc: self._convert_runtime_error_msg(exc) raise
def acquire_nowait(self) -> None: try: self.__original.acquire_nowait() except trio.WouldBlock: raise WouldBlock from None except RuntimeError as exc: self._convert_runtime_error_msg(exc) raise
def locked(self) -> bool: return self.__original.locked()
def release(self) -> None: self.__original.release()
def statistics(self) -> LockStatistics: orig_statistics = self.__original.statistics() owner = TrioTaskInfo(orig_statistics.owner) if orig_statistics.owner else None return LockStatistics( orig_statistics.locked, owner, orig_statistics.tasks_waiting )
class Semaphore(BaseSemaphore): __slots__ = ("__original",)
def __new__( cls, initial_value: int, *, max_value: int | None = None, fast_acquire: bool = False, ) -> Semaphore: return object.__new__(cls)
def __init__( self, initial_value: int, *, max_value: int | None = None, fast_acquire: bool = False, ) -> None: super().__init__(initial_value, max_value=max_value, fast_acquire=fast_acquire) self.__original = trio.Semaphore(initial_value, max_value=max_value)
async def acquire(self) -> None: if not self._fast_acquire: await self.__original.acquire() return
# This is the "fast path" where we don't let other tasks run await trio.lowlevel.checkpoint_if_cancelled() try: self.__original.acquire_nowait() except trio.WouldBlock: await self.__original._lot.park()
def acquire_nowait(self) -> None: try: self.__original.acquire_nowait() except trio.WouldBlock: raise WouldBlock from None
@property def max_value(self) -> int | None: return self.__original.max_value
@property def value(self) -> int: return self.__original.value
def release(self) -> None: self.__original.release()
def statistics(self) -> SemaphoreStatistics: orig_statistics = self.__original.statistics() return SemaphoreStatistics(orig_statistics.tasks_waiting)
class CapacityLimiter(BaseCapacityLimiter): __slots__ = ("__original",)
def __new__( cls, total_tokens: float | None = None, *, original: trio.CapacityLimiter | None = None, ) -> CapacityLimiter: return object.__new__(cls)
def __init__( self, total_tokens: float | None = None, *, original: trio.CapacityLimiter | None = None, ) -> None: if original is not None: self.__original = original else: assert total_tokens is not None self.__original = trio.CapacityLimiter(total_tokens)
async def __aenter__(self) -> None: return await self.__original.__aenter__()
async def __aexit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: await self.__original.__aexit__(exc_type, exc_val, exc_tb)
@property def total_tokens(self) -> float: return self.__original.total_tokens
@total_tokens.setter def total_tokens(self, value: float) -> None: self.__original.total_tokens = value
@property def borrowed_tokens(self) -> int: return self.__original.borrowed_tokens
@property def available_tokens(self) -> float: return self.__original.available_tokens
def acquire_nowait(self) -> None: try: self.__original.acquire_nowait() except trio.WouldBlock: raise WouldBlock from None
def acquire_on_behalf_of_nowait(self, borrower: object) -> None: try: self.__original.acquire_on_behalf_of_nowait(borrower) except trio.WouldBlock: raise WouldBlock from None
async def acquire(self) -> None: await self.__original.acquire()
async def acquire_on_behalf_of(self, borrower: object) -> None: await self.__original.acquire_on_behalf_of(borrower)
def release(self) -> None: return self.__original.release()
def release_on_behalf_of(self, borrower: object) -> None: return self.__original.release_on_behalf_of(borrower)
def statistics(self) -> CapacityLimiterStatistics: orig = self.__original.statistics() return CapacityLimiterStatistics( borrowed_tokens=orig.borrowed_tokens, total_tokens=orig.total_tokens, borrowers=tuple(orig.borrowers), tasks_waiting=orig.tasks_waiting, )
_capacity_limiter_wrapper: trio.lowlevel.RunVar = RunVar("_capacity_limiter_wrapper")
## Signal handling#
class _SignalReceiver: _iterator: AsyncIterator[int]
def __init__(self, signals: tuple[Signals, ...]): self._signals = signals
def __enter__(self) -> _SignalReceiver: self._cm = trio.open_signal_receiver(*self._signals) self._iterator = self._cm.__enter__() return self
def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> bool | None: return self._cm.__exit__(exc_type, exc_val, exc_tb)
def __aiter__(self) -> _SignalReceiver: return self
async def __anext__(self) -> Signals: signum = await self._iterator.__anext__() return Signals(signum)
## Testing and debugging#
class TestRunner(abc.TestRunner): def __init__(self, **options: Any) -> None: from queue import Queue
self._call_queue: Queue[Callable[[], object]] = Queue() self._send_stream: ( MemoryObjectSendStream[tuple[Awaitable[Any], list[Outcome]]] | None ) = None self._options = options
def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None, ) -> None: if self._send_stream: self._send_stream.close() while self._send_stream is not None: self._call_queue.get()()
def is_running(self) -> bool: return trio.lowlevel.in_trio_task()
async def _run_tests_and_fixtures(self) -> None: self._send_stream, receive_stream = create_memory_object_stream[ tuple[Awaitable[Any], list[Outcome]] ](1) with receive_stream: async for awaitable, outcome_holder in receive_stream: try: retval = await awaitable except BaseException as exc: outcome_holder.append(Error(exc)) else: outcome_holder.append(Value(retval))
def _main_task_finished(self, outcome: object) -> None: self._send_stream = None
def _call_in_runner_task( self, func: Callable[P, Awaitable[T_Retval]], /, *args: P.args, **kwargs: P.kwargs, ) -> T_Retval: if self._send_stream is None: trio.lowlevel.start_guest_run( self._run_tests_and_fixtures, run_sync_soon_threadsafe=self._call_queue.put, done_callback=self._main_task_finished, **self._options, ) while self._send_stream is None: self._call_queue.get()()
outcome_holder: list[Outcome] = [] self._send_stream.send_nowait((func(*args, **kwargs), outcome_holder)) while not outcome_holder: self._call_queue.get()()
return outcome_holder[0].unwrap()
def run_asyncgen_fixture( self, fixture_func: Callable[..., AsyncGenerator[T_Retval, Any]], kwargs: dict[str, Any], ) -> Iterable[T_Retval]: asyncgen = fixture_func(**kwargs) fixturevalue: T_Retval = self._call_in_runner_task(asyncgen.asend, None)
yield fixturevalue
try: self._call_in_runner_task(asyncgen.asend, None) except StopAsyncIteration: pass else: self._call_in_runner_task(asyncgen.aclose) raise RuntimeError("Async generator fixture did not stop")
def run_fixture( self, fixture_func: Callable[..., Coroutine[Any, Any, T_Retval]], kwargs: dict[str, Any], ) -> T_Retval: return self._call_in_runner_task(fixture_func, **kwargs)
def run_test( self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any] ) -> None: self._call_in_runner_task(test_func, **kwargs)
class TrioTaskInfo(TaskInfo): def __init__(self, task: trio.lowlevel.Task): parent_id = None if task.parent_nursery and task.parent_nursery.parent_task: parent_id = id(task.parent_nursery.parent_task)
super().__init__(id(task), parent_id, task.name, task.coro) self._task = weakref.proxy(task)
def has_pending_cancellation(self) -> bool: try: return self._task._cancel_status.effectively_cancelled except ReferenceError: # If the task is no longer around, it surely doesn't have a cancellation # pending return False
class TrioBackend(AsyncBackend): @classmethod def run( cls, func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], args: tuple[Unpack[PosArgsT]], kwargs: dict[str, Any], options: dict[str, Any], ) -> T_Retval: assert not kwargs, "unreachable, and not supported by Trio" return trio.run(ensure_returns_coro(func), *args, **options)
@classmethod def current_token(cls) -> object: return trio.lowlevel.current_trio_token()
@classmethod def current_time(cls) -> float: return trio.current_time()
@classmethod def cancelled_exception_class(cls) -> type[BaseException]: return trio.Cancelled
@classmethod async def checkpoint(cls) -> None: await trio.lowlevel.checkpoint()
@classmethod async def checkpoint_if_cancelled(cls) -> None: await trio.lowlevel.checkpoint_if_cancelled()
@classmethod async def cancel_shielded_checkpoint(cls) -> None: await trio.lowlevel.cancel_shielded_checkpoint()
@classmethod async def sleep(cls, delay: float) -> None: await trio.sleep(delay)
@classmethod def create_cancel_scope( cls, *, deadline: float = math.inf, shield: bool = False ) -> abc.CancelScope: return CancelScope(deadline=deadline, shield=shield)
@classmethod def current_effective_deadline(cls) -> float: return trio.current_effective_deadline()
@classmethod def create_task_group(cls) -> abc.TaskGroup: return TaskGroup()
@classmethod def create_event(cls) -> abc.Event: return Event()
@classmethod def create_lock(cls, *, fast_acquire: bool) -> Lock: return Lock(fast_acquire=fast_acquire)
@classmethod def create_semaphore( cls, initial_value: int, *, max_value: int | None = None, fast_acquire: bool = False, ) -> abc.Semaphore: return Semaphore(initial_value, max_value=max_value, fast_acquire=fast_acquire)
@classmethod def create_capacity_limiter(cls, total_tokens: float) -> CapacityLimiter: return CapacityLimiter(total_tokens)
@classmethod async def run_sync_in_worker_thread( cls, func: Callable[[Unpack[PosArgsT]], T_Retval], args: tuple[Unpack[PosArgsT]], abandon_on_cancel: bool = False, limiter: abc.CapacityLimiter | None = None, ) -> T_Retval: def wrapper() -> T_Retval: with claim_worker_thread(TrioBackend, token): return func(*args)
token = TrioBackend.current_token() return await run_sync( wrapper, abandon_on_cancel=abandon_on_cancel, limiter=cast(trio.CapacityLimiter, limiter), )
@classmethod def check_cancelled(cls) -> None: trio.from_thread.check_cancelled()
@classmethod def run_async_from_thread( cls, func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]], args: tuple[Unpack[PosArgsT]], token: object, ) -> T_co: trio_token = cast("trio.lowlevel.TrioToken | None", token) try: return trio.from_thread.run(func, *args, trio_token=trio_token) except trio.RunFinishedError: raise RunFinishedError from None
@classmethod def run_sync_from_thread( cls, func: Callable[[Unpack[PosArgsT]], T_Retval], args: tuple[Unpack[PosArgsT]], token: object, ) -> T_Retval: trio_token = cast("trio.lowlevel.TrioToken | None", token) try: return trio.from_thread.run_sync(func, *args, trio_token=trio_token) except trio.RunFinishedError: raise RunFinishedError from None
@classmethod async def open_process( cls, command: StrOrBytesPath | Sequence[StrOrBytesPath], *, stdin: int | IO[Any] | None, stdout: int | IO[Any] | None, stderr: int | IO[Any] | None, **kwargs: Any, ) -> Process: def convert_item(item: StrOrBytesPath) -> str: str_or_bytes = os.fspath(item) if isinstance(str_or_bytes, str): return str_or_bytes else: return os.fsdecode(str_or_bytes)
if isinstance(command, (str, bytes, PathLike)): process = await trio.lowlevel.open_process( convert_item(command), stdin=stdin, stdout=stdout, stderr=stderr, shell=True, **kwargs, ) else: process = await trio.lowlevel.open_process( [convert_item(item) for item in command], stdin=stdin, stdout=stdout, stderr=stderr, shell=False, **kwargs, )
stdin_stream = SendStreamWrapper(process.stdin) if process.stdin else None stdout_stream = ReceiveStreamWrapper(process.stdout) if process.stdout else None stderr_stream = ReceiveStreamWrapper(process.stderr) if process.stderr else None return Process(process, stdin_stream, stdout_stream, stderr_stream)
@classmethod def setup_process_pool_exit_at_shutdown(cls, workers: set[abc.Process]) -> None: trio.lowlevel.spawn_system_task(_shutdown_process_pool, workers)
@classmethod async def connect_tcp( cls, host: str, port: int, local_address: IPSockAddrType | None = None ) -> SocketStream: family = socket.AF_INET6 if ":" in host else socket.AF_INET trio_socket = trio.socket.socket(family) trio_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) if local_address: await trio_socket.bind(local_address)
try: await trio_socket.connect((host, port)) except BaseException: trio_socket.close() raise
return SocketStream(trio_socket)
@classmethod async def connect_unix(cls, path: str | bytes) -> abc.UNIXSocketStream: trio_socket = trio.socket.socket(socket.AF_UNIX) try: await trio_socket.connect(path) except BaseException: trio_socket.close() raise
return UNIXSocketStream(trio_socket)
@classmethod def create_tcp_listener(cls, sock: socket.socket) -> abc.SocketListener: return TCPSocketListener(sock)
@classmethod def create_unix_listener(cls, sock: socket.socket) -> abc.SocketListener: return UNIXSocketListener(sock)
@classmethod async def create_udp_socket( cls, family: socket.AddressFamily, local_address: IPSockAddrType | None, remote_address: IPSockAddrType | None, reuse_port: bool, ) -> UDPSocket | ConnectedUDPSocket: trio_socket = trio.socket.socket(family=family, type=socket.SOCK_DGRAM)
if reuse_port: trio_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
if local_address: await trio_socket.bind(local_address)
if remote_address: await trio_socket.connect(remote_address) return ConnectedUDPSocket(trio_socket) else: return UDPSocket(trio_socket)
@classmethod @overload async def create_unix_datagram_socket( cls, raw_socket: socket.socket, remote_path: None ) -> abc.UNIXDatagramSocket: ...
@classmethod @overload async def create_unix_datagram_socket( cls, raw_socket: socket.socket, remote_path: str | bytes ) -> abc.ConnectedUNIXDatagramSocket: ...
@classmethod async def create_unix_datagram_socket( cls, raw_socket: socket.socket, remote_path: str | bytes | None ) -> abc.UNIXDatagramSocket | abc.ConnectedUNIXDatagramSocket: trio_socket = trio.socket.from_stdlib_socket(raw_socket)
if remote_path: await trio_socket.connect(remote_path) return ConnectedUNIXDatagramSocket(trio_socket) else: return UNIXDatagramSocket(trio_socket)
@classmethod async def getaddrinfo( cls, host: bytes | str | None, port: str | int | None, *, family: int | AddressFamily = 0, type: int | SocketKind = 0, proto: int = 0, flags: int = 0, ) -> Sequence[ tuple[ AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], ] ]: return await trio.socket.getaddrinfo(host, port, family, type, proto, flags)
@classmethod async def getnameinfo( cls, sockaddr: IPSockAddrType, flags: int = 0 ) -> tuple[str, str]: return await trio.socket.getnameinfo(sockaddr, flags)
@classmethod async def wait_readable(cls, obj: FileDescriptorLike) -> None: try: await wait_readable(obj) except trio.ClosedResourceError as exc: raise ClosedResourceError().with_traceback(exc.__traceback__) from None except trio.BusyResourceError: raise BusyResourceError("reading from") from None
@classmethod async def wait_writable(cls, obj: FileDescriptorLike) -> None: try: await wait_writable(obj) except trio.ClosedResourceError as exc: raise ClosedResourceError().with_traceback(exc.__traceback__) from None except trio.BusyResourceError: raise BusyResourceError("writing to") from None
@classmethod def notify_closing(cls, obj: FileDescriptorLike) -> None: notify_closing(obj)
@classmethod async def wrap_listener_socket(cls, sock: socket.socket) -> abc.SocketListener: if hasattr(socket, "AF_UNIX") and sock.family == socket.AF_UNIX: return UNIXSocketListener(sock)
return TCPSocketListener(sock)
@classmethod async def wrap_stream_socket(cls, sock: socket.socket) -> SocketStream: trio_sock = trio.socket.from_stdlib_socket(sock) return SocketStream(trio_sock)
@classmethod async def wrap_unix_stream_socket(cls, sock: socket.socket) -> UNIXSocketStream: trio_sock = trio.socket.from_stdlib_socket(sock) return UNIXSocketStream(trio_sock)
@classmethod async def wrap_udp_socket(cls, sock: socket.socket) -> UDPSocket: trio_sock = trio.socket.from_stdlib_socket(sock) return UDPSocket(trio_sock)
@classmethod async def wrap_connected_udp_socket(cls, sock: socket.socket) -> ConnectedUDPSocket: trio_sock = trio.socket.from_stdlib_socket(sock) return ConnectedUDPSocket(trio_sock)
@classmethod async def wrap_unix_datagram_socket(cls, sock: socket.socket) -> UNIXDatagramSocket: trio_sock = trio.socket.from_stdlib_socket(sock) return UNIXDatagramSocket(trio_sock)
@classmethod async def wrap_connected_unix_datagram_socket( cls, sock: socket.socket ) -> ConnectedUNIXDatagramSocket: trio_sock = trio.socket.from_stdlib_socket(sock) return ConnectedUNIXDatagramSocket(trio_sock)
@classmethod def current_default_thread_limiter(cls) -> CapacityLimiter: try: return _capacity_limiter_wrapper.get() except LookupError: limiter = CapacityLimiter( original=trio.to_thread.current_default_thread_limiter() ) _capacity_limiter_wrapper.set(limiter) return limiter
@classmethod def open_signal_receiver( cls, *signals: Signals ) -> AbstractContextManager[AsyncIterator[Signals]]: return _SignalReceiver(signals)
@classmethod def get_current_task(cls) -> TaskInfo: task = current_task() return TrioTaskInfo(task)
@classmethod def get_running_tasks(cls) -> Sequence[TaskInfo]: root_task = current_root_task() assert root_task task_infos = [TrioTaskInfo(root_task)] nurseries = root_task.child_nurseries while nurseries: new_nurseries: list[trio.Nursery] = [] for nursery in nurseries: for task in nursery.child_tasks: task_infos.append(TrioTaskInfo(task)) new_nurseries.extend(task.child_nurseries)
nurseries = new_nurseries
return task_infos
@classmethod async def wait_all_tasks_blocked(cls) -> None: from trio.testing import wait_all_tasks_blocked
await wait_all_tasks_blocked()
@classmethod def create_test_runner(cls, options: dict[str, Any]) -> TestRunner: return TestRunner(**options)
backend_class = TrioBackend123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167from __future__ import annotations
import asyncioimport socketimport threadingfrom collections.abc import Callablefrom selectors import EVENT_READ, EVENT_WRITE, DefaultSelectorfrom typing import TYPE_CHECKING, Any
if TYPE_CHECKING: from _typeshed import FileDescriptorLike
_selector_lock = threading.Lock()_selector: Selector | None = None
class Selector: def __init__(self) -> None: self._thread = threading.Thread(target=self.run, name="AnyIO socket selector") self._selector = DefaultSelector() self._send, self._receive = socket.socketpair() self._send.setblocking(False) self._receive.setblocking(False) # This somewhat reduces the amount of memory wasted queueing up data # for wakeups. With these settings, maximum number of 1-byte sends # before getting BlockingIOError: # Linux 4.8: 6 # macOS (darwin 15.5): 1 # Windows 10: 525347 # Windows you're weird. (And on Windows setting SNDBUF to 0 makes send # blocking, even on non-blocking sockets, so don't do that.) self._receive.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1) self._send.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1) # On Windows this is a TCP socket so this might matter. On other # platforms this fails b/c AF_UNIX sockets aren't actually TCP. try: self._send.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) except OSError: pass
self._selector.register(self._receive, EVENT_READ) self._closed = False
def start(self) -> None: self._thread.start() threading._register_atexit(self._stop) # type: ignore[attr-defined]
def _stop(self) -> None: global _selector self._closed = True self._notify_self() self._send.close() self._thread.join() self._selector.unregister(self._receive) self._receive.close() self._selector.close() _selector = None assert not self._selector.get_map(), ( "selector still has registered file descriptors after shutdown" )
def _notify_self(self) -> None: try: self._send.send(b"\x00") except BlockingIOError: pass
def add_reader(self, fd: FileDescriptorLike, callback: Callable[[], Any]) -> None: loop = asyncio.get_running_loop() try: key = self._selector.get_key(fd) except KeyError: self._selector.register(fd, EVENT_READ, {EVENT_READ: (loop, callback)}) else: if EVENT_READ in key.data: raise ValueError( "this file descriptor is already registered for reading" )
key.data[EVENT_READ] = loop, callback self._selector.modify(fd, key.events | EVENT_READ, key.data)
self._notify_self()
def add_writer(self, fd: FileDescriptorLike, callback: Callable[[], Any]) -> None: loop = asyncio.get_running_loop() try: key = self._selector.get_key(fd) except KeyError: self._selector.register(fd, EVENT_WRITE, {EVENT_WRITE: (loop, callback)}) else: if EVENT_WRITE in key.data: raise ValueError( "this file descriptor is already registered for writing" )
key.data[EVENT_WRITE] = loop, callback self._selector.modify(fd, key.events | EVENT_WRITE, key.data)
self._notify_self()
def remove_reader(self, fd: FileDescriptorLike) -> bool: try: key = self._selector.get_key(fd) except KeyError: return False
if new_events := key.events ^ EVENT_READ: del key.data[EVENT_READ] self._selector.modify(fd, new_events, key.data) else: self._selector.unregister(fd)
return True
def remove_writer(self, fd: FileDescriptorLike) -> bool: try: key = self._selector.get_key(fd) except KeyError: return False
if new_events := key.events ^ EVENT_WRITE: del key.data[EVENT_WRITE] self._selector.modify(fd, new_events, key.data) else: self._selector.unregister(fd)
return True
def run(self) -> None: while not self._closed: for key, events in self._selector.select(): if key.fileobj is self._receive: try: while self._receive.recv(4096): pass except BlockingIOError: pass
continue
if events & EVENT_READ: loop, callback = key.data[EVENT_READ] self.remove_reader(key.fd) try: loop.call_soon_threadsafe(callback) except RuntimeError: pass # the loop was already closed
if events & EVENT_WRITE: loop, callback = key.data[EVENT_WRITE] self.remove_writer(key.fd) try: loop.call_soon_threadsafe(callback) except RuntimeError: pass # the loop was already closed
def get_selector() -> Selector: global _selector
with _selector_lock: if _selector is None: _selector = Selector() _selector.start()
return _selector123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200from __future__ import annotations
from abc import abstractmethodfrom contextlib import AbstractAsyncContextManager, AbstractContextManagerfrom inspect import isasyncgen, iscoroutine, isgeneratorfrom types import TracebackTypefrom typing import Protocol, TypeVar, cast, final
_T_co = TypeVar("_T_co", covariant=True)_ExitT_co = TypeVar("_ExitT_co", covariant=True, bound="bool | None")
class _SupportsCtxMgr(Protocol[_T_co, _ExitT_co]): def __contextmanager__(self) -> AbstractContextManager[_T_co, _ExitT_co]: ...
class _SupportsAsyncCtxMgr(Protocol[_T_co, _ExitT_co]): def __asynccontextmanager__( self, ) -> AbstractAsyncContextManager[_T_co, _ExitT_co]: ...
class ContextManagerMixin: """ Mixin class providing context manager functionality via a generator-based implementation.
This class allows you to implement a context manager via :meth:`__contextmanager__` which should return a generator. The mechanics are meant to mirror those of :func:`@contextmanager <contextlib.contextmanager>`.
.. note:: Classes using this mix-in are not reentrant as context managers, meaning that once you enter it, you can't re-enter before first exiting it.
.. seealso:: :doc:`contextmanagers` """
__cm: AbstractContextManager[object, bool | None] | None = None
@final def __enter__(self: _SupportsCtxMgr[_T_co, bool | None]) -> _T_co: # Needed for mypy to assume self still has the __cm member assert isinstance(self, ContextManagerMixin) if self.__cm is not None: raise RuntimeError( f"this {self.__class__.__qualname__} has already been entered" )
cm = self.__contextmanager__() if not isinstance(cm, AbstractContextManager): if isgenerator(cm): raise TypeError( "__contextmanager__() returned a generator object instead of " "a context manager. Did you forget to add the @contextmanager " "decorator?" )
raise TypeError( f"__contextmanager__() did not return a context manager object, " f"but {cm.__class__!r}" )
if cm is self: raise TypeError( f"{self.__class__.__qualname__}.__contextmanager__() returned " f"self. Did you forget to add the @contextmanager decorator and a " f"'yield' statement?" )
value = cm.__enter__() self.__cm = cm return value
@final def __exit__( self: _SupportsCtxMgr[object, _ExitT_co], exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> _ExitT_co: # Needed for mypy to assume self still has the __cm member assert isinstance(self, ContextManagerMixin) if self.__cm is None: raise RuntimeError( f"this {self.__class__.__qualname__} has not been entered yet" )
# Prevent circular references cm = self.__cm del self.__cm
return cast(_ExitT_co, cm.__exit__(exc_type, exc_val, exc_tb))
@abstractmethod def __contextmanager__(self) -> AbstractContextManager[object, bool | None]: """ Implement your context manager logic here.
This method **must** be decorated with :func:`@contextmanager <contextlib.contextmanager>`.
.. note:: Remember that the ``yield`` will raise any exception raised in the enclosed context block, so use a ``finally:`` block to clean up resources!
:return: a context manager object """
class AsyncContextManagerMixin: """ Mixin class providing async context manager functionality via a generator-based implementation.
This class allows you to implement a context manager via :meth:`__asynccontextmanager__`. The mechanics are meant to mirror those of :func:`@asynccontextmanager <contextlib.asynccontextmanager>`.
.. note:: Classes using this mix-in are not reentrant as context managers, meaning that once you enter it, you can't re-enter before first exiting it.
.. seealso:: :doc:`contextmanagers` """
__cm: AbstractAsyncContextManager[object, bool | None] | None = None
@final async def __aenter__(self: _SupportsAsyncCtxMgr[_T_co, bool | None]) -> _T_co: # Needed for mypy to assume self still has the __cm member assert isinstance(self, AsyncContextManagerMixin) if self.__cm is not None: raise RuntimeError( f"this {self.__class__.__qualname__} has already been entered" )
cm = self.__asynccontextmanager__() if not isinstance(cm, AbstractAsyncContextManager): if isasyncgen(cm): raise TypeError( "__asynccontextmanager__() returned an async generator instead of " "an async context manager. Did you forget to add the " "@asynccontextmanager decorator?" ) elif iscoroutine(cm): cm.close() raise TypeError( "__asynccontextmanager__() returned a coroutine object instead of " "an async context manager. Did you forget to add the " "@asynccontextmanager decorator and a 'yield' statement?" )
raise TypeError( f"__asynccontextmanager__() did not return an async context manager, " f"but {cm.__class__!r}" )
if cm is self: raise TypeError( f"{self.__class__.__qualname__}.__asynccontextmanager__() returned " f"self. Did you forget to add the @asynccontextmanager decorator and a " f"'yield' statement?" )
value = await cm.__aenter__() self.__cm = cm return value
@final async def __aexit__( self: _SupportsAsyncCtxMgr[object, _ExitT_co], exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> _ExitT_co: assert isinstance(self, AsyncContextManagerMixin) if self.__cm is None: raise RuntimeError( f"this {self.__class__.__qualname__} has not been entered yet" )
# Prevent circular references cm = self.__cm del self.__cm
return cast(_ExitT_co, await cm.__aexit__(exc_type, exc_val, exc_tb))
@abstractmethod def __asynccontextmanager__( self, ) -> AbstractAsyncContextManager[object, bool | None]: """ Implement your async context manager logic here.
This method **must** be decorated with :func:`@asynccontextmanager <contextlib.asynccontextmanager>`.
.. note:: Remember that the ``yield`` will raise any exception raised in the enclosed context block, so use a ``finally:`` block to clean up resources!
:return: an async context manager object """123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240from __future__ import annotations
import mathimport sysimport threadingfrom collections.abc import Awaitable, Callable, Generatorfrom contextlib import contextmanagerfrom contextvars import Tokenfrom importlib import import_modulefrom typing import TYPE_CHECKING, Any, TypeVar
from ._exceptions import NoEventLoopError
if sys.version_info >= (3, 11): from typing import TypeVarTuple, Unpackelse: from typing_extensions import TypeVarTuple, Unpack
sniffio: Anytry: import sniffioexcept ModuleNotFoundError: sniffio = None
if TYPE_CHECKING: from ..abc import AsyncBackend
# This must be updated when new backends are introducedBACKENDS = "asyncio", "trio"
T_Retval = TypeVar("T_Retval")PosArgsT = TypeVarTuple("PosArgsT")
threadlocals = threading.local()loaded_backends: dict[str, type[AsyncBackend]] = {}
def run( func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], *args: Unpack[PosArgsT], backend: str = "asyncio", backend_options: dict[str, Any] | None = None,) -> T_Retval: """ Run the given coroutine function in an asynchronous event loop.
The current thread must not be already running an event loop.
:param func: a coroutine function :param args: positional arguments to ``func`` :param backend: name of the asynchronous event loop implementation – currently either ``asyncio`` or ``trio`` :param backend_options: keyword arguments to call the backend ``run()`` implementation with (documented :ref:`here <backend options>`) :return: the return value of the coroutine function :raises RuntimeError: if an asynchronous event loop is already running in this thread :raises LookupError: if the named backend is not found
""" if asynclib_name := current_async_library(): raise RuntimeError(f"Already running {asynclib_name} in this thread")
try: async_backend = get_async_backend(backend) except ImportError as exc: if backend in BACKENDS: raise LookupError( f"Backend {backend!r} is not available. " f"Install it with: pip install anyio[{backend}]" ) from exc
raise LookupError(f"No such backend: {backend}") from exc
token = None if asynclib_name is None: # Since we're in control of the event loop, we can cache the name of the async # library token = set_current_async_library(backend)
try: backend_options = backend_options or {} return async_backend.run(func, args, {}, backend_options) finally: reset_current_async_library(token)
async def sleep(delay: float) -> None: """ Pause the current task for the specified duration.
:param delay: the duration, in seconds
""" return await get_async_backend().sleep(delay)
async def sleep_forever() -> None: """ Pause the current task until it's cancelled.
This is a shortcut for ``sleep(math.inf)``.
.. versionadded:: 3.1
""" await sleep(math.inf)
async def sleep_until(deadline: float) -> None: """ Pause the current task until the given time.
:param deadline: the absolute time to wake up at (according to the internal monotonic clock of the event loop)
.. versionadded:: 3.1
""" now = current_time() await sleep(max(deadline - now, 0))
def current_time() -> float: """ Return the current value of the event loop's internal clock.
:return: the clock value (seconds) :raises NoEventLoopError: if no supported asynchronous event loop is running in the current thread
""" return get_async_backend().current_time()
def get_all_backends() -> tuple[str, ...]: """Return a tuple of the names of all built-in backends.""" return BACKENDS
def get_available_backends() -> tuple[str, ...]: """ Test for the availability of built-in backends.
:return a tuple of the built-in backend names that were successfully imported
.. versionadded:: 4.12
""" available_backends: list[str] = [] for backend_name in get_all_backends(): try: get_async_backend(backend_name) except ImportError: continue
available_backends.append(backend_name)
return tuple(available_backends)
def get_cancelled_exc_class() -> type[BaseException]: """ Return the current async library's cancellation exception class.
:raises NoEventLoopError: if no supported asynchronous event loop is running in the current thread
""" return get_async_backend().cancelled_exception_class()
## Private API#
@contextmanagerdef claim_worker_thread( backend_class: type[AsyncBackend], token: object) -> Generator[Any, None, None]: from ..lowlevel import EventLoopToken
threadlocals.current_token = EventLoopToken(backend_class, token) try: yield finally: del threadlocals.current_token
def get_async_backend(asynclib_name: str | None = None) -> type[AsyncBackend]: if asynclib_name is None: asynclib_name = current_async_library() if not asynclib_name: raise NoEventLoopError( f"Not currently running on any asynchronous event loop. " f"Available async backends: {', '.join(get_all_backends())}" )
# We use our own dict instead of sys.modules to get the already imported back-end # class because the appropriate modules in sys.modules could potentially be only # partially initialized try: return loaded_backends[asynclib_name] except KeyError: module = import_module(f"anyio._backends._{asynclib_name}") loaded_backends[asynclib_name] = module.backend_class return module.backend_class
def current_async_library() -> str | None: if sniffio is None: # If sniffio is not installed, we assume we're either running asyncio or nothing import asyncio
try: asyncio.get_running_loop() return "asyncio" except RuntimeError: pass else: try: return sniffio.current_async_library() except sniffio.AsyncLibraryNotFoundError: pass
return None
def set_current_async_library(asynclib_name: str | None) -> Token | None: # no-op if sniffio is not installed if sniffio is None: return None
return sniffio.current_async_library_cvar.set(asynclib_name)
def reset_current_async_library(token: Token | None) -> None: if token is not None: sniffio.current_async_library_cvar.reset(token)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177from __future__ import annotations
import sysfrom collections.abc import Generatorfrom textwrap import dedentfrom typing import Any
if sys.version_info < (3, 11): from exceptiongroup import BaseExceptionGroup
class BrokenResourceError(Exception): """ Raised when trying to use a resource that has been rendered unusable due to external causes (e.g. a send stream whose peer has disconnected). """
class BrokenWorkerProcess(Exception): """ Raised by :meth:`~anyio.to_process.run_sync` if the worker process terminates abruptly or otherwise misbehaves. """
class BrokenWorkerInterpreter(Exception): """ Raised by :meth:`~anyio.to_interpreter.run_sync` if an unexpected exception is raised in the subinterpreter. """
def __init__(self, excinfo: Any): # This was adapted from concurrent.futures.interpreter.ExecutionFailed msg = excinfo.formatted if not msg: if excinfo.type and excinfo.msg: msg = f"{excinfo.type.__name__}: {excinfo.msg}" else: msg = excinfo.type.__name__ or excinfo.msg
super().__init__(msg) self.excinfo = excinfo
def __str__(self) -> str: try: formatted = self.excinfo.errdisplay except Exception: return super().__str__() else: return dedent( f""" {super().__str__()}
Uncaught in the interpreter:
{formatted} """.strip() )
class BusyResourceError(Exception): """ Raised when two tasks are trying to read from or write to the same resource concurrently. """
def __init__(self, action: str): super().__init__(f"Another task is already {action} this resource")
class ClosedResourceError(Exception): """Raised when trying to use a resource that has been closed."""
class ConnectionFailed(OSError): """ Raised when a connection attempt fails.
.. note:: This class inherits from :exc:`OSError` for backwards compatibility. """
def iterate_exceptions( exception: BaseException,) -> Generator[BaseException, None, None]: if isinstance(exception, BaseExceptionGroup): for exc in exception.exceptions: yield from iterate_exceptions(exc) else: yield exception
class DelimiterNotFound(Exception): """ Raised during :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_until` if the maximum number of bytes has been read without the delimiter being found. """
def __init__(self, max_bytes: int) -> None: super().__init__( f"The delimiter was not found among the first {max_bytes} bytes" )
class EndOfStream(Exception): """ Raised when trying to read from a stream that has been closed from the other end. """
class IncompleteRead(Exception): """ Raised during :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_exactly` or :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_until` if the connection is closed before the requested amount of bytes has been read. """
def __init__(self) -> None: super().__init__( "The stream was closed before the read operation could be completed" )
class TypedAttributeLookupError(LookupError): """ Raised by :meth:`~anyio.TypedAttributeProvider.extra` when the given typed attribute is not found and no default value has been given. """
class WouldBlock(Exception): """Raised by ``X_nowait`` functions if ``X()`` would block."""
class NoEventLoopError(RuntimeError): """ Raised by several functions that require an event loop to be running in the current thread when there is no running event loop.
This is also raised by :func:`.from_thread.run` and :func:`.from_thread.run_sync` if not calling from an AnyIO worker thread, and no ``token`` was passed. """
class RunFinishedError(RuntimeError): """ Raised by :func:`.from_thread.run` and :func:`.from_thread.run_sync` if the event loop associated with the explicitly passed token has already finished. """
def __init__(self) -> None: super().__init__( "The event loop associated with the given token has already finished" )
class TaskFailed(Exception): """ Raised when awaiting on, or attempting to access the return value of, a :class:`.TaskHandle` that raised an exception. """
class TaskCancelled(TaskFailed): """ Raised when awaiting on, or attempting to access the return value of, a :class:`.TaskHandle` that was cancelled. """
class TaskNotFinished(Exception): """ Raised when attempting to access the return value or exception of a :class:`.TaskHandle` that is still pending completion. """123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960from __future__ import annotations
import osimport pathlibimport sysfrom collections.abc import ( AsyncIterator, Callable, Iterable, Iterator, Sequence,)from dataclasses import dataclassfrom functools import partialfrom os import PathLikefrom typing import ( IO, TYPE_CHECKING, Any, AnyStr, ClassVar, Final, Generic, TypeVar, overload,)
from .. import to_threadfrom ..abc import AsyncResourcefrom ._synchronization import CapacityLimiter
if sys.version_info >= (3, 11): from typing import Selfelse: from typing_extensions import Self
if sys.version_info >= (3, 14): from pathlib.types import PathInfo
if TYPE_CHECKING: from types import ModuleType
from _typeshed import OpenBinaryMode, OpenTextMode, ReadableBuffer, WriteableBufferelse: ReadableBuffer = OpenBinaryMode = OpenTextMode = WriteableBuffer = object
T = TypeVar("T", bound="Path")
class AsyncFile(AsyncResource, Generic[AnyStr]): """ An asynchronous file object.
This class wraps a standard file object and provides async friendly versions of the following blocking methods (where available on the original file object):
* read * read1 * readline * readlines * readinto * readinto1 * write * writelines * truncate * seek * tell * flush
All other methods are directly passed through.
This class supports the asynchronous context manager protocol which closes the underlying file at the end of the context block.
This class also supports asynchronous iteration::
async with await open_file(...) as f: async for line in f: print(line) """
def __init__( self, fp: IO[AnyStr], *, limiter: CapacityLimiter | None = None ) -> None: if limiter is not None and not isinstance(limiter, CapacityLimiter): raise TypeError( f"limiter must be a CapacityLimiter or None, not " f"{limiter.__class__.__name__}" )
self._fp: Any = fp self._limiter = limiter
def __getattr__(self, name: str) -> object: return getattr(self._fp, name)
@property def limiter(self) -> CapacityLimiter | None: """The capacity limiter used by this file object, if not the global limiter.""" return self._limiter
@property def wrapped(self) -> IO[AnyStr]: """The wrapped file object.""" return self._fp
async def __aiter__(self) -> AsyncIterator[AnyStr]: while True: line = await self.readline() if line: yield line else: break
async def aclose(self) -> None: return await to_thread.run_sync(self._fp.close, limiter=self._limiter)
async def read(self, size: int = -1) -> AnyStr: return await to_thread.run_sync(self._fp.read, size, limiter=self._limiter)
async def read1(self: AsyncFile[bytes], size: int = -1) -> bytes: return await to_thread.run_sync(self._fp.read1, size, limiter=self._limiter)
async def readline(self) -> AnyStr: return await to_thread.run_sync(self._fp.readline, limiter=self._limiter)
async def readlines(self) -> list[AnyStr]: return await to_thread.run_sync(self._fp.readlines, limiter=self._limiter)
async def readinto(self: AsyncFile[bytes], b: WriteableBuffer) -> int: return await to_thread.run_sync(self._fp.readinto, b, limiter=self._limiter)
async def readinto1(self: AsyncFile[bytes], b: WriteableBuffer) -> int: return await to_thread.run_sync(self._fp.readinto1, b, limiter=self._limiter)
@overload async def write(self: AsyncFile[bytes], b: ReadableBuffer) -> int: ...
@overload async def write(self: AsyncFile[str], b: str) -> int: ...
async def write(self, b: ReadableBuffer | str) -> int: return await to_thread.run_sync(self._fp.write, b, limiter=self._limiter)
@overload async def writelines( self: AsyncFile[bytes], lines: Iterable[ReadableBuffer] ) -> None: ...
@overload async def writelines(self: AsyncFile[str], lines: Iterable[str]) -> None: ...
async def writelines(self, lines: Iterable[ReadableBuffer] | Iterable[str]) -> None: return await to_thread.run_sync( self._fp.writelines, lines, limiter=self._limiter )
async def truncate(self, size: int | None = None) -> int: return await to_thread.run_sync(self._fp.truncate, size, limiter=self._limiter)
async def seek(self, offset: int, whence: int | None = os.SEEK_SET) -> int: return await to_thread.run_sync( self._fp.seek, offset, whence, limiter=self._limiter )
async def tell(self) -> int: return await to_thread.run_sync(self._fp.tell, limiter=self._limiter)
async def flush(self) -> None: return await to_thread.run_sync(self._fp.flush, limiter=self._limiter)
@overloadasync def open_file( file: str | PathLike[str] | int, mode: OpenBinaryMode, buffering: int = ..., encoding: str | None = ..., errors: str | None = ..., newline: str | None = ..., closefd: bool = ..., opener: Callable[[str, int], int] | None = ..., *, limiter: CapacityLimiter | None = ...,) -> AsyncFile[bytes]: ...
@overloadasync def open_file( file: str | PathLike[str] | int, mode: OpenTextMode = ..., buffering: int = ..., encoding: str | None = ..., errors: str | None = ..., newline: str | None = ..., closefd: bool = ..., opener: Callable[[str, int], int] | None = ..., *, limiter: CapacityLimiter | None = ...,) -> AsyncFile[str]: ...
async def open_file( file: str | PathLike[str] | int, mode: str = "r", buffering: int = -1, encoding: str | None = None, errors: str | None = None, newline: str | None = None, closefd: bool = True, opener: Callable[[str, int], int] | None = None, *, limiter: CapacityLimiter | None = None,) -> AsyncFile[Any]: """ Open a file asynchronously.
Except for ``limiter``, the arguments are exactly the same as for the builtin :func:`open`.
:param limiter: an optional capacity limiter to use with the file instead of the default one :return: an asynchronous file object
.. versionchanged:: 4.14.0 Added the ``limiter`` keyword argument.
""" fp = await to_thread.run_sync( open, file, mode, buffering, encoding, errors, newline, closefd, opener, limiter=limiter, ) return AsyncFile(fp, limiter=limiter)
def wrap_file( file: IO[AnyStr], *, limiter: CapacityLimiter | None = None) -> AsyncFile[AnyStr]: """ Wrap an existing file as an asynchronous file.
:param file: an existing file-like object :param limiter: an optional capacity limiter to use with the file instead of the default one :return: an asynchronous file object
.. versionchanged:: 4.14.0 Added the ``limiter`` keyword argument.
""" return AsyncFile(file, limiter=limiter)
@dataclass(eq=False)class _PathIterator(AsyncIterator[T]): iterator: Iterator[PathLike[str]] limiter: CapacityLimiter | None # This was added to ensure that iterating over a subclass of Path yields instances # of that subclass rather than the base Path class. path_cls: type[T]
async def __anext__(self) -> T: nextval = await to_thread.run_sync( next, self.iterator, None, abandon_on_cancel=True, limiter=self.limiter ) if nextval is None: raise StopAsyncIteration from None
return self.path_cls(nextval, limiter=self.limiter)
class Path: """ An asynchronous version of :class:`pathlib.Path`.
This class cannot be substituted for :class:`pathlib.Path` or :class:`pathlib.PurePath`, but it is compatible with the :class:`os.PathLike` interface.
It implements the Python 3.10 version of :class:`pathlib.Path` interface, except for the deprecated :meth:`~pathlib.Path.link_to` method.
Some methods may be unavailable or have limited functionality, based on the Python version:
* :meth:`~pathlib.Path.copy` (available on Python 3.14 or later) * :meth:`~pathlib.Path.copy_into` (available on Python 3.14 or later) * :meth:`~pathlib.Path.from_uri` (available on Python 3.13 or later) * :meth:`~pathlib.PurePath.full_match` (available on Python 3.13 or later) * :attr:`~pathlib.Path.info` (available on Python 3.14 or later) * :meth:`~pathlib.Path.is_junction` (available on Python 3.12 or later) * :meth:`~pathlib.PurePath.match` (the ``case_sensitive`` parameter is only available on Python 3.13 or later) * :meth:`~pathlib.Path.move` (available on Python 3.14 or later) * :meth:`~pathlib.Path.move_into` (available on Python 3.14 or later) * :meth:`~pathlib.PurePath.relative_to` (the ``walk_up`` parameter is only available on Python 3.12 or later) * :meth:`~pathlib.Path.walk` (available on Python 3.12 or later)
Any methods that do disk I/O need to be awaited on. These methods are:
* :meth:`~pathlib.Path.absolute` * :meth:`~pathlib.Path.chmod` * :meth:`~pathlib.Path.cwd` * :meth:`~pathlib.Path.exists` * :meth:`~pathlib.Path.expanduser` * :meth:`~pathlib.Path.group` * :meth:`~pathlib.Path.hardlink_to` * :meth:`~pathlib.Path.home` * :meth:`~pathlib.Path.is_block_device` * :meth:`~pathlib.Path.is_char_device` * :meth:`~pathlib.Path.is_dir` * :meth:`~pathlib.Path.is_fifo` * :meth:`~pathlib.Path.is_file` * :meth:`~pathlib.Path.is_junction` * :meth:`~pathlib.Path.is_mount` * :meth:`~pathlib.Path.is_socket` * :meth:`~pathlib.Path.is_symlink` * :meth:`~pathlib.Path.lchmod` * :meth:`~pathlib.Path.lstat` * :meth:`~pathlib.Path.mkdir` * :meth:`~pathlib.Path.open` * :meth:`~pathlib.Path.owner` * :meth:`~pathlib.Path.read_bytes` * :meth:`~pathlib.Path.read_text` * :meth:`~pathlib.Path.readlink` * :meth:`~pathlib.Path.rename` * :meth:`~pathlib.Path.replace` * :meth:`~pathlib.Path.resolve` * :meth:`~pathlib.Path.rmdir` * :meth:`~pathlib.Path.samefile` * :meth:`~pathlib.Path.stat` * :meth:`~pathlib.Path.symlink_to` * :meth:`~pathlib.Path.touch` * :meth:`~pathlib.Path.unlink` * :meth:`~pathlib.Path.walk` * :meth:`~pathlib.Path.write_bytes` * :meth:`~pathlib.Path.write_text`
Additionally, the following methods return an async iterator yielding :class:`~.Path` objects:
* :meth:`~pathlib.Path.glob` * :meth:`~pathlib.Path.iterdir` * :meth:`~pathlib.Path.rglob`
.. versionchanged:: 4.14.0 Added the ``limiter`` keyword argument. """
__slots__ = "_path", "_limiter", "__weakref__"
__weakref__: Any
def __init__( self, *args: str | PathLike[str], limiter: CapacityLimiter | None = None ) -> None: if limiter is not None and not isinstance(limiter, CapacityLimiter): raise TypeError( f"limiter must be a CapacityLimiter or None, not " f"{limiter.__class__.__name__}" )
self._path: Final[pathlib.Path] = pathlib.Path(*args) self._limiter = limiter
def __fspath__(self) -> str: return self._path.__fspath__()
if sys.version_info >= (3, 15):
def __vfspath__(self) -> str: return self._path.__vfspath__()
def __str__(self) -> str: return self._path.__str__()
def __repr__(self) -> str: return f"{self.__class__.__name__}({self.as_posix()!r})"
def __bytes__(self) -> bytes: return self._path.__bytes__()
def __hash__(self) -> int: return self._path.__hash__()
def __eq__(self, other: object) -> bool: target = other._path if isinstance(other, Path) else other return self._path.__eq__(target)
def __lt__(self, other: pathlib.PurePath | Path) -> bool: target = other._path if isinstance(other, Path) else other return self._path.__lt__(target)
def __le__(self, other: pathlib.PurePath | Path) -> bool: target = other._path if isinstance(other, Path) else other return self._path.__le__(target)
def __gt__(self, other: pathlib.PurePath | Path) -> bool: target = other._path if isinstance(other, Path) else other return self._path.__gt__(target)
def __ge__(self, other: pathlib.PurePath | Path) -> bool: target = other._path if isinstance(other, Path) else other return self._path.__ge__(target)
def __truediv__(self, other: str | PathLike[str]) -> Self: return type(self)(self._path / other, limiter=self._limiter)
def __rtruediv__(self, other: str | PathLike[str]) -> Self: return type(self)(other, limiter=self._limiter) / self
@property def limiter(self) -> CapacityLimiter | None: """The capacity limiter used by this path, if not the global limiter.""" return self._limiter
@property def parts(self) -> tuple[str, ...]: return self._path.parts
@property def drive(self) -> str: return self._path.drive
@property def root(self) -> str: return self._path.root
@property def anchor(self) -> str: return self._path.anchor
@property def parents(self) -> Sequence[Self]: return tuple(type(self)(p, limiter=self._limiter) for p in self._path.parents)
@property def parent(self) -> Self: return type(self)(self._path.parent, limiter=self._limiter)
@property def name(self) -> str: return self._path.name
@property def suffix(self) -> str: return self._path.suffix
@property def suffixes(self) -> list[str]: return self._path.suffixes
@property def stem(self) -> str: return self._path.stem
async def absolute(self) -> Self: path = await to_thread.run_sync(self._path.absolute, limiter=self._limiter) return type(self)(path, limiter=self._limiter)
def as_posix(self) -> str: return self._path.as_posix()
def as_uri(self) -> str: return self._path.as_uri()
if sys.version_info >= (3, 13): parser: ClassVar[ModuleType] = pathlib.Path.parser
@classmethod def from_uri(cls, uri: str, *, limiter: CapacityLimiter | None = None) -> Self: return cls(pathlib.Path.from_uri(uri), limiter=limiter)
def full_match( self, path_pattern: str, *, case_sensitive: bool | None = None ) -> bool: return self._path.full_match(path_pattern, case_sensitive=case_sensitive)
def match( self, path_pattern: str, *, case_sensitive: bool | None = None ) -> bool: return self._path.match(path_pattern, case_sensitive=case_sensitive) else:
def match(self, path_pattern: str) -> bool: return self._path.match(path_pattern)
if sys.version_info >= (3, 14):
@property def info(self) -> PathInfo: return self._path.info
async def copy( self, target: str | os.PathLike[str], *, follow_symlinks: bool = True, preserve_metadata: bool = False, ) -> Self: func = partial( self._path.copy, follow_symlinks=follow_symlinks, preserve_metadata=preserve_metadata, ) return type(self)( await to_thread.run_sync( func, pathlib.Path(target), limiter=self._limiter ), limiter=self._limiter, )
async def copy_into( self, target_dir: str | os.PathLike[str], *, follow_symlinks: bool = True, preserve_metadata: bool = False, ) -> Self: func = partial( self._path.copy_into, follow_symlinks=follow_symlinks, preserve_metadata=preserve_metadata, ) return type(self)( await to_thread.run_sync( func, pathlib.Path(target_dir), limiter=self._limiter ), limiter=self._limiter, )
async def move(self, target: str | os.PathLike[str]) -> Self: # Upstream does not handle anyio.Path properly as a PathLike target = pathlib.Path(target) return type(self)( await to_thread.run_sync( self._path.move, target, limiter=self._limiter ), limiter=self._limiter, )
async def move_into( self, target_dir: str | os.PathLike[str], ) -> Self: return type(self)( await to_thread.run_sync( self._path.move_into, target_dir, limiter=self._limiter ), limiter=self._limiter, )
def is_relative_to(self, other: str | PathLike[str]) -> bool: try: self.relative_to(other) return True except ValueError: return False
async def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None: func = partial(os.chmod, follow_symlinks=follow_symlinks) return await to_thread.run_sync(func, self._path, mode, limiter=self._limiter)
@classmethod async def cwd(cls, *, limiter: CapacityLimiter | None = None) -> Self: path = await to_thread.run_sync(pathlib.Path.cwd, limiter=limiter) return cls(path, limiter=limiter)
async def exists(self) -> bool: return await to_thread.run_sync( self._path.exists, abandon_on_cancel=True, limiter=self._limiter )
async def expanduser(self) -> Self: return type(self)( await to_thread.run_sync( self._path.expanduser, abandon_on_cancel=True, limiter=self._limiter ), limiter=self._limiter, )
if sys.version_info < (3, 12): # Python 3.11 and earlier def glob(self, pattern: str) -> AsyncIterator[Self]: gen = self._path.glob(pattern) return _PathIterator(gen, self._limiter, type(self)) elif (3, 12) <= sys.version_info < (3, 13): # changed in Python 3.12: # - The case_sensitive parameter was added. def glob( self, pattern: str, *, case_sensitive: bool | None = None, ) -> AsyncIterator[Self]: gen = self._path.glob(pattern, case_sensitive=case_sensitive) return _PathIterator(gen, self._limiter, type(self)) elif sys.version_info >= (3, 13): # Changed in Python 3.13: # - The recurse_symlinks parameter was added. # - The pattern parameter accepts a path-like object. def glob( # type: ignore[misc] # mypy doesn't allow for differing signatures in a conditional block self, pattern: str | PathLike[str], *, case_sensitive: bool | None = None, recurse_symlinks: bool = False, ) -> AsyncIterator[Self]: gen = self._path.glob( pattern, # type: ignore[arg-type] case_sensitive=case_sensitive, recurse_symlinks=recurse_symlinks, ) return _PathIterator(gen, self._limiter, type(self))
async def group(self) -> str: return await to_thread.run_sync( self._path.group, abandon_on_cancel=True, limiter=self._limiter )
async def hardlink_to( self, target: str | bytes | PathLike[str] | PathLike[bytes] ) -> None: if isinstance(target, Path): target = target._path
await to_thread.run_sync(os.link, target, self, limiter=self._limiter)
@classmethod async def home(cls, *, limiter: CapacityLimiter | None = None) -> Self: home_path = await to_thread.run_sync(pathlib.Path.home, limiter=limiter) return cls(home_path, limiter=limiter)
def is_absolute(self) -> bool: return self._path.is_absolute()
async def is_block_device(self) -> bool: return await to_thread.run_sync( self._path.is_block_device, abandon_on_cancel=True, limiter=self._limiter )
async def is_char_device(self) -> bool: return await to_thread.run_sync( self._path.is_char_device, abandon_on_cancel=True, limiter=self._limiter )
async def is_dir(self) -> bool: return await to_thread.run_sync( self._path.is_dir, abandon_on_cancel=True, limiter=self._limiter )
async def is_fifo(self) -> bool: return await to_thread.run_sync( self._path.is_fifo, abandon_on_cancel=True, limiter=self._limiter )
async def is_file(self) -> bool: return await to_thread.run_sync( self._path.is_file, abandon_on_cancel=True, limiter=self._limiter )
if sys.version_info >= (3, 12):
async def is_junction(self) -> bool: return await to_thread.run_sync( self._path.is_junction, limiter=self._limiter )
async def is_mount(self) -> bool: return await to_thread.run_sync( os.path.ismount, self._path, abandon_on_cancel=True, limiter=self._limiter )
if sys.version_info < (3, 15):
def is_reserved(self) -> bool: return self._path.is_reserved()
async def is_socket(self) -> bool: return await to_thread.run_sync( self._path.is_socket, abandon_on_cancel=True, limiter=self._limiter )
async def is_symlink(self) -> bool: return await to_thread.run_sync( self._path.is_symlink, abandon_on_cancel=True, limiter=self._limiter )
async def iterdir(self) -> AsyncIterator[Self]: gen = ( self._path.iterdir() if sys.version_info < (3, 13) else await to_thread.run_sync( self._path.iterdir, abandon_on_cancel=True, limiter=self._limiter ) ) async for path in _PathIterator(gen, self._limiter, type(self)): yield path
def joinpath(self, *args: str | PathLike[str]) -> Self: return type(self)(self._path.joinpath(*args), limiter=self._limiter)
async def lchmod(self, mode: int) -> None: await to_thread.run_sync(self._path.lchmod, mode, limiter=self._limiter)
async def lstat(self) -> os.stat_result: return await to_thread.run_sync( self._path.lstat, abandon_on_cancel=True, limiter=self._limiter )
async def mkdir( self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False ) -> None: await to_thread.run_sync( self._path.mkdir, mode, parents, exist_ok, limiter=self._limiter )
@overload async def open( self, mode: OpenBinaryMode, buffering: int = ..., encoding: str | None = ..., errors: str | None = ..., newline: str | None = ..., ) -> AsyncFile[bytes]: ...
@overload async def open( self, mode: OpenTextMode = ..., buffering: int = ..., encoding: str | None = ..., errors: str | None = ..., newline: str | None = ..., ) -> AsyncFile[str]: ...
async def open( self, mode: str = "r", buffering: int = -1, encoding: str | None = None, errors: str | None = None, newline: str | None = None, ) -> AsyncFile[Any]: fp = await to_thread.run_sync( self._path.open, mode, buffering, encoding, errors, newline, limiter=self._limiter, ) return AsyncFile(fp, limiter=self._limiter)
async def owner(self) -> str: return await to_thread.run_sync( self._path.owner, abandon_on_cancel=True, limiter=self._limiter )
async def read_bytes(self) -> bytes: return await to_thread.run_sync(self._path.read_bytes, limiter=self._limiter)
async def read_text( self, encoding: str | None = None, errors: str | None = None ) -> str: return await to_thread.run_sync( self._path.read_text, encoding, errors, limiter=self._limiter )
if sys.version_info >= (3, 12):
def relative_to( self, *other: str | PathLike[str], walk_up: bool = False ) -> Self: # relative_to() should work with any PathLike but it doesn't others = [pathlib.Path(other) for other in other] return type(self)( self._path.relative_to(*others, walk_up=walk_up), limiter=self._limiter )
else:
def relative_to(self, *other: str | PathLike[str]) -> Self: return type(self)(self._path.relative_to(*other), limiter=self._limiter)
async def readlink(self) -> Self: target = await to_thread.run_sync( os.readlink, self._path, limiter=self._limiter ) return type(self)(target, limiter=self._limiter)
async def rename(self, target: str | pathlib.PurePath | Path) -> Self: if isinstance(target, Path): target = target._path
await to_thread.run_sync(self._path.rename, target, limiter=self._limiter) return type(self)(target, limiter=self._limiter)
async def replace(self, target: str | pathlib.PurePath | Path) -> Self: if isinstance(target, Path): target = target._path
await to_thread.run_sync(self._path.replace, target, limiter=self._limiter) return type(self)(target, limiter=self._limiter)
async def resolve(self, strict: bool = False) -> Self: func = partial(self._path.resolve, strict=strict) return type(self)( await to_thread.run_sync( func, abandon_on_cancel=True, limiter=self._limiter ), limiter=self._limiter, )
if sys.version_info < (3, 12): # Pre Python 3.12 def rglob(self, pattern: str) -> AsyncIterator[Self]: gen = self._path.rglob(pattern) return _PathIterator(gen, self._limiter, type(self)) elif (3, 12) <= sys.version_info < (3, 13): # Changed in Python 3.12: # - The case_sensitive parameter was added. def rglob( self, pattern: str, *, case_sensitive: bool | None = None ) -> AsyncIterator[Self]: gen = self._path.rglob(pattern, case_sensitive=case_sensitive) return _PathIterator(gen, self._limiter, type(self)) elif sys.version_info >= (3, 13): # Changed in Python 3.13: # - The recurse_symlinks parameter was added. # - The pattern parameter accepts a path-like object. def rglob( # type: ignore[misc] # mypy doesn't allow for differing signatures in a conditional block self, pattern: str | PathLike[str], *, case_sensitive: bool | None = None, recurse_symlinks: bool = False, ) -> AsyncIterator[Self]: gen = self._path.rglob( pattern, # type: ignore[arg-type] case_sensitive=case_sensitive, recurse_symlinks=recurse_symlinks, ) return _PathIterator(gen, self._limiter, type(self))
async def rmdir(self) -> None: await to_thread.run_sync(self._path.rmdir, limiter=self._limiter)
async def samefile(self, other_path: str | PathLike[str]) -> bool: if isinstance(other_path, Path): other_path = other_path._path
return await to_thread.run_sync( self._path.samefile, other_path, abandon_on_cancel=True, limiter=self._limiter, )
async def stat(self, *, follow_symlinks: bool = True) -> os.stat_result: func = partial(os.stat, follow_symlinks=follow_symlinks) return await to_thread.run_sync( func, self._path, abandon_on_cancel=True, limiter=self._limiter )
async def symlink_to( self, target: str | bytes | PathLike[str] | PathLike[bytes], target_is_directory: bool = False, ) -> None: if isinstance(target, Path): target = target._path
await to_thread.run_sync( self._path.symlink_to, target, target_is_directory, limiter=self._limiter )
async def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: await to_thread.run_sync( self._path.touch, mode, exist_ok, limiter=self._limiter )
async def unlink(self, missing_ok: bool = False) -> None: try: await to_thread.run_sync(self._path.unlink, limiter=self._limiter) except FileNotFoundError: if not missing_ok: raise
if sys.version_info >= (3, 12):
async def walk( self, top_down: bool = True, on_error: Callable[[OSError], object] | None = None, follow_symlinks: bool = False, ) -> AsyncIterator[tuple[Self, list[str], list[str]]]: def get_next_value() -> tuple[pathlib.Path, list[str], list[str]] | None: try: return next(gen) except StopIteration: return None
gen = self._path.walk(top_down, on_error, follow_symlinks) while True: value = await to_thread.run_sync(get_next_value, limiter=self._limiter) if value is None: return
root, dirs, paths = value yield type(self)(root, limiter=self._limiter), dirs, paths
def with_name(self, name: str) -> Self: return type(self)(self._path.with_name(name), limiter=self._limiter)
def with_stem(self, stem: str) -> Self: return type(self)( self._path.with_name(stem + self._path.suffix), limiter=self._limiter )
def with_suffix(self, suffix: str) -> Self: return type(self)(self._path.with_suffix(suffix), limiter=self._limiter)
def with_segments(self, *pathsegments: str | PathLike[str]) -> Self: return type(self)(*pathsegments, limiter=self._limiter)
async def write_bytes(self, data: ReadableBuffer) -> int: return await to_thread.run_sync( self._path.write_bytes, data, limiter=self._limiter )
async def write_text( self, data: str, encoding: str | None = None, errors: str | None = None, newline: str | None = None, ) -> int: return await to_thread.run_sync( self._path.write_text, data, encoding, errors, newline, limiter=self._limiter, )
PathLike.register(Path)123456789101112131415161718from __future__ import annotations
from ..abc import AsyncResourcefrom ._tasks import CancelScope
async def aclose_forcefully(resource: AsyncResource) -> None: """ Close an asynchronous resource in a cancelled scope.
Doing this closes the resource without waiting on anything.
:param resource: the resource to close
""" with CancelScope() as scope: scope.cancel() await resource.aclose()1234567891011121314151617181920212223242526272829from __future__ import annotations
from collections.abc import AsyncIteratorfrom contextlib import AbstractContextManagerfrom signal import Signals
from ._eventloop import get_async_backend
def open_signal_receiver( *signals: Signals,) -> AbstractContextManager[AsyncIterator[Signals]]: """ Start receiving operating system signals.
:param signals: signals to receive (e.g. ``signal.SIGINT``) :return: an asynchronous context manager for an asynchronous iterator which yields signal numbers :raises NoEventLoopError: if no supported asynchronous event loop is running in the current thread
.. warning:: Windows does not support signals natively so it is best to avoid relying on this in cross-platform applications.
.. warning:: On asyncio, this permanently replaces any previous signal handler for the given signals, as set via :meth:`~asyncio.loop.add_signal_handler`.
""" return get_async_backend().open_signal_receiver(*signals)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011from __future__ import annotations
import errnoimport osimport socketimport sslimport statimport sysfrom collections.abc import Awaitablefrom dataclasses import dataclassfrom ipaddress import IPv4Address, IPv6Address, ip_addressfrom os import PathLike, chmodfrom socket import AddressFamily, SocketKindfrom typing import TYPE_CHECKING, Any, Literal, cast, overload
from .. import ConnectionFailed, to_threadfrom ..abc import ( ByteStreamConnectable, ConnectedUDPSocket, ConnectedUNIXDatagramSocket, IPAddressType, IPSockAddrType, SocketListener, SocketStream, UDPSocket, UNIXDatagramSocket, UNIXSocketStream,)from ..streams.stapled import MultiListenerfrom ..streams.tls import TLSConnectable, TLSStreamfrom ._eventloop import get_async_backendfrom ._resources import aclose_forcefullyfrom ._synchronization import Eventfrom ._tasks import create_task_group, move_on_after
if TYPE_CHECKING: from _typeshed import FileDescriptorLikeelse: FileDescriptorLike = object
if sys.version_info < (3, 11): from exceptiongroup import ExceptionGroup
if sys.version_info >= (3, 12): from typing import overrideelse: from typing_extensions import override
if sys.version_info < (3, 13): from typing_extensions import deprecatedelse: from warnings import deprecated
IPPROTO_IPV6 = getattr(socket, "IPPROTO_IPV6", 41) # https://bugs.python.org/issue29515
AnyIPAddressFamily = Literal[ AddressFamily.AF_UNSPEC, AddressFamily.AF_INET, AddressFamily.AF_INET6]IPAddressFamily = Literal[AddressFamily.AF_INET, AddressFamily.AF_INET6]
def idna2008_resolve(host: str) -> bytes: try: return host.encode("ascii") except UnicodeEncodeError: import idna
return idna.encode(host, uts46=True)
# tls_hostname given@overloadasync def connect_tcp( remote_host: IPAddressType, remote_port: int, *, local_host: IPAddressType | None = ..., local_port: int | None = ..., ssl_context: ssl.SSLContext | None = ..., tls_standard_compatible: bool = ..., tls_hostname: str, happy_eyeballs_delay: float = ...,) -> TLSStream: ...
# ssl_context given@overloadasync def connect_tcp( remote_host: IPAddressType, remote_port: int, *, local_host: IPAddressType | None = ..., local_port: int | None = ..., ssl_context: ssl.SSLContext, tls_standard_compatible: bool = ..., tls_hostname: str | None = ..., happy_eyeballs_delay: float = ...,) -> TLSStream: ...
# tls=True@overloadasync def connect_tcp( remote_host: IPAddressType, remote_port: int, *, local_host: IPAddressType | None = ..., local_port: int | None = ..., tls: Literal[True], ssl_context: ssl.SSLContext | None = ..., tls_standard_compatible: bool = ..., tls_hostname: str | None = ..., happy_eyeballs_delay: float = ...,) -> TLSStream: ...
# tls=False@overloadasync def connect_tcp( remote_host: IPAddressType, remote_port: int, *, local_host: IPAddressType | None = ..., local_port: int | None = ..., tls: Literal[False], ssl_context: ssl.SSLContext | None = ..., tls_standard_compatible: bool = ..., tls_hostname: str | None = ..., happy_eyeballs_delay: float = ...,) -> SocketStream: ...
# No TLS arguments@overloadasync def connect_tcp( remote_host: IPAddressType, remote_port: int, *, local_host: IPAddressType | None = ..., local_port: int | None = ..., happy_eyeballs_delay: float = ...,) -> SocketStream: ...
async def connect_tcp( remote_host: IPAddressType, remote_port: int, *, local_host: IPAddressType | None = None, local_port: int | None = None, tls: bool = False, ssl_context: ssl.SSLContext | None = None, tls_standard_compatible: bool = True, tls_hostname: str | None = None, happy_eyeballs_delay: float = 0.25,) -> SocketStream | TLSStream: """ Connect to a host using the TCP protocol.
This function implements the stateless version of the Happy Eyeballs algorithm (RFC 6555). If ``remote_host`` is a host name that resolves to multiple IP addresses, each one is tried until one connection attempt succeeds. If the first attempt does not connected within 250 milliseconds, a second attempt is started using the next address in the list, and so on. On IPv6 enabled systems, an IPv6 address (if available) is tried first.
When the connection has been established, a TLS handshake will be done if either ``ssl_context`` or ``tls_hostname`` is not ``None``, or if ``tls`` is ``True``.
:param remote_host: the IP address or host name to connect to :param remote_port: port on the target host to connect to :param local_host: the interface address or name to bind the socket to before connecting :param local_port: the local port to bind to (requires ``local_host`` to also be set) :param tls: ``True`` to do a TLS handshake with the connected stream and return a :class:`~anyio.streams.tls.TLSStream` instead :param ssl_context: the SSL context object to use (if omitted, a default context is created) :param tls_standard_compatible: If ``True``, performs the TLS shutdown handshake before closing the stream and requires that the server does this as well. Otherwise, :exc:`~ssl.SSLEOFError` may be raised during reads from the stream. Some protocols, such as HTTP, require this option to be ``False``. See :meth:`~ssl.SSLContext.wrap_socket` for details. :param tls_hostname: host name to check the server certificate against (defaults to the value of ``remote_host``) :param happy_eyeballs_delay: delay (in seconds) before starting the next connection attempt :return: a socket stream object if no TLS handshake was done, otherwise a TLS stream :raises ConnectionFailed: if the connection fails
""" # Placed here due to https://github.com/python/mypy/issues/7057 connected_stream: SocketStream | None = None
async def try_connect(remote_host: str, event: Event) -> None: nonlocal connected_stream try: stream = await asynclib.connect_tcp(remote_host, remote_port, local_address) except OSError as exc: oserrors.append(exc) return else: if connected_stream is None: connected_stream = stream tg.cancel_scope.cancel() else: await stream.aclose() finally: event.set()
asynclib = get_async_backend() local_address: IPSockAddrType | None = None family = socket.AF_UNSPEC if local_host: gai_res = await getaddrinfo(str(local_host), local_port) family, *_, local_address = gai_res[0]
target_host = str(remote_host) try: addr_obj = ip_address(remote_host) except ValueError: addr_obj = None
if addr_obj is not None: if isinstance(addr_obj, IPv6Address): target_addrs = [(socket.AF_INET6, addr_obj.compressed)] else: target_addrs = [(socket.AF_INET, addr_obj.compressed)] else: # getaddrinfo() will raise an exception if name resolution fails gai_res = await getaddrinfo( target_host, remote_port, family=family, type=socket.SOCK_STREAM )
# Organize the list so that the first address is an IPv6 address (if available) # and the second one is an IPv4 addresses. The rest can be in whatever order. v6_found = v4_found = False target_addrs = [] for af, *_, sa in gai_res: if af == socket.AF_INET6 and not v6_found: v6_found = True target_addrs.insert(0, (af, sa[0])) elif af == socket.AF_INET and not v4_found and v6_found: v4_found = True target_addrs.insert(1, (af, sa[0])) else: target_addrs.append((af, sa[0]))
oserrors: list[OSError] = [] try: async with create_task_group() as tg: for _af, addr in target_addrs: event = Event() tg.start_soon(try_connect, addr, event) with move_on_after(happy_eyeballs_delay): await event.wait()
if connected_stream is None: cause = ( oserrors[0] if len(oserrors) == 1 else ExceptionGroup("multiple connection attempts failed", oserrors) ) raise OSError("All connection attempts failed") from cause finally: oserrors.clear()
if tls or tls_hostname or ssl_context: try: return await TLSStream.wrap( connected_stream, server_side=False, hostname=tls_hostname or str(remote_host), ssl_context=ssl_context, standard_compatible=tls_standard_compatible, ) except BaseException: await aclose_forcefully(connected_stream) raise
return connected_stream
async def connect_unix(path: str | bytes | PathLike[Any]) -> UNIXSocketStream: """ Connect to the given UNIX socket.
Not available on Windows.
:param path: path to the socket :return: a socket stream object :raises ConnectionFailed: if the connection fails
""" path = os.fspath(path) return await get_async_backend().connect_unix(path)
async def create_tcp_listener( *, local_host: IPAddressType | None = None, local_port: int = 0, family: AnyIPAddressFamily = socket.AddressFamily.AF_UNSPEC, backlog: int = 65536, reuse_port: bool = False,) -> MultiListener[SocketStream]: """ Create a TCP socket listener.
:param local_port: port number to listen on :param local_host: IP address of the interface to listen on. If omitted, listen on all IPv4 and IPv6 interfaces. To listen on all interfaces on a specific address family, use ``0.0.0.0`` for IPv4 or ``::`` for IPv6. :param family: address family (used if ``local_host`` was omitted) :param backlog: maximum number of queued incoming connections (up to a maximum of 2**16, or 65536) :param reuse_port: ``True`` to allow multiple sockets to bind to the same address/port (not supported on Windows) :return: a multi-listener object containing one or more socket listeners :raises OSError: if there's an error creating a socket, or binding to one or more interfaces failed
""" asynclib = get_async_backend() backlog = min(backlog, 65536) local_host = str(local_host) if local_host is not None else None
def setup_raw_socket( fam: AddressFamily, bind_addr: tuple[str, int] | tuple[str, int, int, int], *, v6only: bool = True, ) -> socket.socket: sock = socket.socket(fam) try: sock.setblocking(False)
if fam == AddressFamily.AF_INET6: sock.setsockopt(IPPROTO_IPV6, socket.IPV6_V6ONLY, v6only)
# For Windows, enable exclusive address use. For others, enable address # reuse. if sys.platform == "win32": sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) else: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if reuse_port: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
# Workaround for #554 if fam == socket.AF_INET6 and "%" in bind_addr[0]: addr, scope_id = bind_addr[0].split("%", 1) bind_addr = (addr, bind_addr[1], 0, int(scope_id))
sock.bind(bind_addr) sock.listen(backlog) except BaseException: sock.close() raise
return sock
# We passing type=0 on non-Windows platforms as a workaround for a uvloop bug # where we don't get the correct scope ID for IPv6 link-local addresses when passing # type=socket.SOCK_STREAM to getaddrinfo(): # https://github.com/MagicStack/uvloop/issues/539 gai_res = await getaddrinfo( local_host, local_port, family=family, type=socket.SOCK_STREAM if sys.platform == "win32" else 0, flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, )
# The set comprehension is here to work around a glibc bug: # https://sourceware.org/bugzilla/show_bug.cgi?id=14969 sockaddrs = sorted({res for res in gai_res if res[1] == SocketKind.SOCK_STREAM})
# Special case for dual-stack binding on the "any" interface if ( local_host is None and family == AddressFamily.AF_UNSPEC and socket.has_dualstack_ipv6() and any(fam == AddressFamily.AF_INET6 for fam, *_ in gai_res) ): raw_socket = setup_raw_socket( AddressFamily.AF_INET6, ("::", local_port), v6only=False ) listener = asynclib.create_tcp_listener(raw_socket) return MultiListener([listener])
errors: list[OSError] = [] try: for _ in range(len(sockaddrs)): listeners: list[SocketListener] = [] bound_ephemeral_port = local_port try: for fam, *_, sockaddr in sockaddrs: sockaddr = sockaddr[0], bound_ephemeral_port, *sockaddr[2:] raw_socket = setup_raw_socket(fam, sockaddr)
# Store the assigned port if an ephemeral port was requested, so # we'll bind to the same port on all interfaces if local_port == 0 and len(gai_res) > 1: bound_ephemeral_port = raw_socket.getsockname()[1]
listeners.append(asynclib.create_tcp_listener(raw_socket)) except BaseException as exc: for listener in listeners: await listener.aclose()
# If an ephemeral port was requested but binding the assigned port # failed for another interface, rotate the address list and try again if ( isinstance(exc, OSError) and exc.errno == errno.EADDRINUSE and local_port == 0 and bound_ephemeral_port ): errors.append(exc) sockaddrs.append(sockaddrs.pop(0)) continue
raise
return MultiListener(listeners)
raise OSError( f"Could not create {len(sockaddrs)} listeners with a consistent port" ) from ExceptionGroup("Several bind attempts failed", errors) finally: del errors # Prevent reference cycles
async def create_unix_listener( path: str | bytes | PathLike[Any], *, mode: int | None = None, backlog: int = 65536,) -> SocketListener: """ Create a UNIX socket listener.
Not available on Windows.
:param path: path of the socket :param mode: permissions to set on the socket :param backlog: maximum number of queued incoming connections (up to a maximum of 2**16, or 65536) :return: a listener object
.. versionchanged:: 3.0 If a socket already exists on the file system in the given path, it will be removed first.
""" backlog = min(backlog, 65536) raw_socket = await setup_unix_local_socket(path, mode, socket.SOCK_STREAM) try: raw_socket.listen(backlog) return get_async_backend().create_unix_listener(raw_socket) except BaseException: raw_socket.close() raise
async def create_udp_socket( family: AnyIPAddressFamily = AddressFamily.AF_UNSPEC, *, local_host: IPAddressType | None = None, local_port: int = 0, reuse_port: bool = False,) -> UDPSocket: """ Create a UDP socket.
If ``port`` has been given, the socket will be bound to this port on the local machine, making this socket suitable for providing UDP based services.
:param family: address family (``AF_INET`` or ``AF_INET6``) – automatically determined from ``local_host`` if omitted :param local_host: IP address or host name of the local interface to bind to :param local_port: local port to bind to :param reuse_port: ``True`` to allow multiple sockets to bind to the same address/port (not supported on Windows) :return: a UDP socket
""" if family is AddressFamily.AF_UNSPEC and not local_host: raise ValueError('Either "family" or "local_host" must be given')
if local_host: gai_res = await getaddrinfo( str(local_host), local_port, family=family, type=socket.SOCK_DGRAM, flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, ) family = cast(AnyIPAddressFamily, gai_res[0][0]) local_address = gai_res[0][-1] elif family is AddressFamily.AF_INET6: local_address = ("::", 0) else: local_address = ("0.0.0.0", 0)
sock = await get_async_backend().create_udp_socket( family, local_address, None, reuse_port ) return cast(UDPSocket, sock)
async def create_connected_udp_socket( remote_host: IPAddressType, remote_port: int, *, family: AnyIPAddressFamily = AddressFamily.AF_UNSPEC, local_host: IPAddressType | None = None, local_port: int = 0, reuse_port: bool = False,) -> ConnectedUDPSocket: """ Create a connected UDP socket.
Connected UDP sockets can only communicate with the specified remote host/port, an any packets sent from other sources are dropped.
:param remote_host: remote host to set as the default target :param remote_port: port on the remote host to set as the default target :param family: address family (``AF_INET`` or ``AF_INET6``) – automatically determined from ``local_host`` or ``remote_host`` if omitted :param local_host: IP address or host name of the local interface to bind to :param local_port: local port to bind to :param reuse_port: ``True`` to allow multiple sockets to bind to the same address/port (not supported on Windows) :return: a connected UDP socket
""" local_address = None if local_host: gai_res = await getaddrinfo( str(local_host), local_port, family=family, type=socket.SOCK_DGRAM, flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, ) family = cast(AnyIPAddressFamily, gai_res[0][0]) local_address = gai_res[0][-1]
gai_res = await getaddrinfo( str(remote_host), remote_port, family=family, type=socket.SOCK_DGRAM ) family = cast(AnyIPAddressFamily, gai_res[0][0]) remote_address = gai_res[0][-1]
sock = await get_async_backend().create_udp_socket( family, local_address, remote_address, reuse_port ) return cast(ConnectedUDPSocket, sock)
async def create_unix_datagram_socket( *, local_path: None | str | bytes | PathLike[Any] = None, local_mode: int | None = None,) -> UNIXDatagramSocket: """ Create a UNIX datagram socket.
Not available on Windows.
If ``local_path`` has been given, the socket will be bound to this path, making this socket suitable for receiving datagrams from other processes. Other processes can send datagrams to this socket only if ``local_path`` is set.
If a socket already exists on the file system in the ``local_path``, it will be removed first.
:param local_path: the path on which to bind to :param local_mode: permissions to set on the local socket :return: a UNIX datagram socket
""" raw_socket = await setup_unix_local_socket( local_path, local_mode, socket.SOCK_DGRAM ) return await get_async_backend().create_unix_datagram_socket(raw_socket, None)
async def create_connected_unix_datagram_socket( remote_path: str | bytes | PathLike[Any], *, local_path: None | str | bytes | PathLike[Any] = None, local_mode: int | None = None,) -> ConnectedUNIXDatagramSocket: """ Create a connected UNIX datagram socket.
Connected datagram sockets can only communicate with the specified remote path.
If ``local_path`` has been given, the socket will be bound to this path, making this socket suitable for receiving datagrams from other processes. Other processes can send datagrams to this socket only if ``local_path`` is set.
If a socket already exists on the file system in the ``local_path``, it will be removed first.
:param remote_path: the path to set as the default target :param local_path: the path on which to bind to :param local_mode: permissions to set on the local socket :return: a connected UNIX datagram socket
""" remote_path = os.fspath(remote_path) raw_socket = await setup_unix_local_socket( local_path, local_mode, socket.SOCK_DGRAM ) return await get_async_backend().create_unix_datagram_socket( raw_socket, remote_path )
async def getaddrinfo( host: bytes | str | None, port: str | int | None, *, family: int | AddressFamily = 0, type: int | SocketKind = 0, proto: int = 0, flags: int = 0,) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int]]]: """ Look up a numeric IP address given a host name.
Internationalized domain names are translated according to the (non-transitional) IDNA 2008 standard.
.. note:: 4-tuple IPv6 socket addresses are automatically converted to 2-tuples of (host, port), unlike what :func:`socket.getaddrinfo` does.
:param host: host name :param port: port number :param family: socket family (`'AF_INET``, ...) :param type: socket type (``SOCK_STREAM``, ...) :param proto: protocol number :param flags: flags to pass to upstream ``getaddrinfo()`` :return: list of tuples containing (family, type, proto, canonname, sockaddr)
.. seealso:: :func:`socket.getaddrinfo`
""" # Handle unicode hostnames encoded_host = idna2008_resolve(host) if isinstance(host, str) else host gai_res = await get_async_backend().getaddrinfo( encoded_host, port, family=family, type=type, proto=proto, flags=flags ) return [ (family, type, proto, canonname, convert_ipv6_sockaddr(sockaddr)) for family, type, proto, canonname, sockaddr in gai_res # filter out IPv6 results when IPv6 is disabled if not isinstance(sockaddr[0], int) ]
def getnameinfo(sockaddr: IPSockAddrType, flags: int = 0) -> Awaitable[tuple[str, str]]: """ Look up the host name of an IP address.
:param sockaddr: socket address (e.g. (ipaddress, port) for IPv4) :param flags: flags to pass to upstream ``getnameinfo()`` :return: a tuple of (host name, service name) :raises NoEventLoopError: if no supported asynchronous event loop is running in the current thread
.. seealso:: :func:`socket.getnameinfo`
""" return get_async_backend().getnameinfo(sockaddr, flags)
@deprecated("This function is deprecated; use `wait_readable` instead")def wait_socket_readable(sock: socket.socket) -> Awaitable[None]: """ .. deprecated:: 4.7.0 Use :func:`wait_readable` instead.
Wait until the given socket has data to be read.
.. warning:: Only use this on raw sockets that have not been wrapped by any higher level constructs like socket streams!
:param sock: a socket object :raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the socket to become readable :raises ~anyio.BusyResourceError: if another task is already waiting for the socket to become readable :raises NoEventLoopError: if no supported asynchronous event loop is running in the current thread
""" return get_async_backend().wait_readable(sock.fileno())
@deprecated("This function is deprecated; use `wait_writable` instead")def wait_socket_writable(sock: socket.socket) -> Awaitable[None]: """ .. deprecated:: 4.7.0 Use :func:`wait_writable` instead.
Wait until the given socket can be written to.
This does **NOT** work on Windows when using the asyncio backend with a proactor event loop (default on py3.8+).
.. warning:: Only use this on raw sockets that have not been wrapped by any higher level constructs like socket streams!
:param sock: a socket object :raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the socket to become writable :raises ~anyio.BusyResourceError: if another task is already waiting for the socket to become writable :raises NoEventLoopError: if no supported asynchronous event loop is running in the current thread
""" return get_async_backend().wait_writable(sock.fileno())
def wait_readable(obj: FileDescriptorLike) -> Awaitable[None]: """ Wait until the given object has data to be read.
On Unix systems, ``obj`` must either be an integer file descriptor, or else an object with a ``.fileno()`` method which returns an integer file descriptor. Any kind of file descriptor can be passed, though the exact semantics will depend on your kernel. For example, this probably won't do anything useful for on-disk files.
On Windows systems, ``obj`` must either be an integer ``SOCKET`` handle, or else an object with a ``.fileno()`` method which returns an integer ``SOCKET`` handle. File descriptors aren't supported, and neither are handles that refer to anything besides a ``SOCKET``.
On backends where this functionality is not natively provided (asyncio ``ProactorEventLoop`` on Windows), it is provided using a separate selector thread which is set to shut down when the interpreter shuts down.
.. warning:: Don't use this on raw sockets that have been wrapped by any higher level constructs like socket streams!
:param obj: an object with a ``.fileno()`` method or an integer handle :raises ~anyio.ClosedResourceError: if the object was closed while waiting for the object to become readable :raises ~anyio.BusyResourceError: if another task is already waiting for the object to become readable :raises NoEventLoopError: if no supported asynchronous event loop is running in the current thread
""" return get_async_backend().wait_readable(obj)
def wait_writable(obj: FileDescriptorLike) -> Awaitable[None]: """ Wait until the given object can be written to.
:param obj: an object with a ``.fileno()`` method or an integer handle :raises ~anyio.ClosedResourceError: if the object was closed while waiting for the object to become writable :raises ~anyio.BusyResourceError: if another task is already waiting for the object to become writable :raises NoEventLoopError: if no supported asynchronous event loop is running in the current thread
.. seealso:: See the documentation of :func:`wait_readable` for the definition of ``obj`` and notes on backend compatibility.
.. warning:: Don't use this on raw sockets that have been wrapped by any higher level constructs like socket streams!
""" return get_async_backend().wait_writable(obj)
def notify_closing(obj: FileDescriptorLike) -> None: """ Call this before closing a file descriptor (on Unix) or socket (on Windows). This will cause any `wait_readable` or `wait_writable` calls on the given object to immediately wake up and raise `~anyio.ClosedResourceError`.
This doesn't actually close the object – you still have to do that yourself afterwards. Also, you want to be careful to make sure no new tasks start waiting on the object in between when you call this and when it's actually closed. So to close something properly, you usually want to do these steps in order:
1. Explicitly mark the object as closed, so that any new attempts to use it will abort before they start. 2. Call `notify_closing` to wake up any already-existing users. 3. Actually close the object.
It's also possible to do them in a different order if that's more convenient, *but only if* you make sure not to have any checkpoints in between the steps. This way they all happen in a single atomic step, so other tasks won't be able to tell what order they happened in anyway.
:param obj: an object with a ``.fileno()`` method or an integer handle :raises NoEventLoopError: if no supported asynchronous event loop is running in the current thread
""" get_async_backend().notify_closing(obj)
## Private API#
def convert_ipv6_sockaddr( sockaddr: tuple[str, int, int, int] | tuple[str, int],) -> tuple[str, int]: """ Convert a 4-tuple IPv6 socket address to a 2-tuple (address, port) format.
If the scope ID is nonzero, it is added to the address, separated with ``%``. Otherwise the flow id and scope id are simply cut off from the tuple. Any other kinds of socket addresses are returned as-is.
:param sockaddr: the result of :meth:`~socket.socket.getsockname` :return: the converted socket address
""" # This is more complicated than it should be because of MyPy if isinstance(sockaddr, tuple) and len(sockaddr) == 4: host, port, flowinfo, scope_id = sockaddr if scope_id: # PyPy (as of v7.3.11) leaves the interface name in the result, so # we discard it and only get the scope ID from the end # (https://foss.heptapod.net/pypy/pypy/-/issues/3938) host = host.split("%")[0]
# Add scope_id to the address return f"{host}%{scope_id}", port else: return host, port else: return sockaddr
async def setup_unix_local_socket( path: None | str | bytes | PathLike[Any], mode: int | None, socktype: int,) -> socket.socket: """ Create a UNIX local socket object, deleting the socket at the given path if it exists.
Not available on Windows.
:param path: path of the socket :param mode: permissions to set on the socket :param socktype: socket.SOCK_STREAM or socket.SOCK_DGRAM
""" path_str: str | None if path is not None: path_str = os.fsdecode(path)
# Linux abstract namespace sockets aren't backed by a concrete file so skip stat call if not path_str.startswith("\0"): # Copied from pathlib... try: stat_result = os.stat(path) except OSError as e: if e.errno not in ( errno.ENOENT, errno.ENOTDIR, errno.EBADF, errno.ELOOP, ): raise else: if stat.S_ISSOCK(stat_result.st_mode): os.unlink(path) else: path_str = None
raw_socket = socket.socket(socket.AF_UNIX, socktype) raw_socket.setblocking(False)
if path_str is not None: try: await to_thread.run_sync(raw_socket.bind, path_str, abandon_on_cancel=True) if mode is not None: await to_thread.run_sync(chmod, path_str, mode, abandon_on_cancel=True) except BaseException: raw_socket.close() raise
return raw_socket
@dataclassclass TCPConnectable(ByteStreamConnectable): """ Connects to a TCP server at the given host and port.
:param host: host name or IP address of the server :param port: TCP port number of the server """
host: str | IPv4Address | IPv6Address port: int
def __post_init__(self) -> None: if self.port < 1 or self.port > 65535: raise ValueError("TCP port number out of range")
@override async def connect(self) -> SocketStream: try: return await connect_tcp(self.host, self.port) except OSError as exc: raise ConnectionFailed( f"error connecting to {self.host}:{self.port}: {exc}" ) from exc
@dataclassclass UNIXConnectable(ByteStreamConnectable): """ Connects to a UNIX domain socket at the given path.
:param path: the file system path of the socket """
path: str | bytes | PathLike[str] | PathLike[bytes]
@override async def connect(self) -> UNIXSocketStream: try: return await connect_unix(self.path) except OSError as exc: raise ConnectionFailed(f"error connecting to {self.path!r}: {exc}") from exc
def as_connectable( remote: ByteStreamConnectable | tuple[str | IPv4Address | IPv6Address, int] | str | bytes | PathLike[str], /, *, tls: bool = False, ssl_context: ssl.SSLContext | None = None, tls_hostname: str | None = None, tls_standard_compatible: bool = True,) -> ByteStreamConnectable: """ Return a byte stream connectable from the given object.
If a bytestream connectable is given, it is returned unchanged. If a tuple of (host, port) is given, a TCP connectable is returned. If a string or bytes path is given, a UNIX connectable is returned.
If ``tls=True``, the connectable will be wrapped in a :class:`~.streams.tls.TLSConnectable`.
:param remote: a connectable, a tuple of (host, port) or a path to a UNIX socket :param tls: if ``True``, wrap the plaintext connectable in a :class:`~.streams.tls.TLSConnectable`, using the provided TLS settings) :param ssl_context: if ``tls=True``, the SSLContext object to use (if not provided, a secure default will be created) :param tls_hostname: if ``tls=True``, host name of the server to use for checking the server certificate (defaults to the host portion of the address for TCP connectables) :param tls_standard_compatible: if ``False`` and ``tls=True``, makes the TLS stream skip the closing handshake when closing the connection, so it won't raise an exception if the server does the same
""" connectable: TCPConnectable | UNIXConnectable | TLSConnectable if isinstance(remote, ByteStreamConnectable): return remote elif isinstance(remote, tuple) and len(remote) == 2: connectable = TCPConnectable(*remote) elif isinstance(remote, (str, bytes, PathLike)): connectable = UNIXConnectable(remote) else: raise TypeError(f"cannot convert {remote!r} to a connectable")
if tls: if not tls_hostname and isinstance(connectable, TCPConnectable): tls_hostname = str(connectable.host)
connectable = TLSConnectable( connectable, ssl_context=ssl_context, hostname=tls_hostname, standard_compatible=tls_standard_compatible, )
return connectable12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152from __future__ import annotations
import mathfrom typing import TypeVarfrom warnings import warn
from ..streams.memory import ( MemoryObjectReceiveStream, MemoryObjectSendStream, _MemoryObjectStreamState,)
T_Item = TypeVar("T_Item")
class create_memory_object_stream( tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]],): """ Create a memory object stream.
The stream's item type can be annotated like :func:`create_memory_object_stream[T_Item]`.
:param max_buffer_size: number of items held in the buffer until ``send()`` starts blocking :param item_type: old way of marking the streams with the right generic type for static typing (does nothing on AnyIO 4)
.. deprecated:: 4.0 Use ``create_memory_object_stream[YourItemType](...)`` instead. :return: a tuple of (send stream, receive stream)
"""
def __new__( # type: ignore[misc] cls, max_buffer_size: float = 0, item_type: object = None ) -> tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]]: if max_buffer_size != math.inf and not isinstance(max_buffer_size, int): raise ValueError("max_buffer_size must be either an integer or math.inf") if max_buffer_size < 0: raise ValueError("max_buffer_size cannot be negative") if item_type is not None: warn( "The item_type argument has been deprecated in AnyIO 4.0. " "Use create_memory_object_stream[YourItemType](...) instead.", DeprecationWarning, stacklevel=2, )
state = _MemoryObjectStreamState[T_Item](max_buffer_size) return (MemoryObjectSendStream(state), MemoryObjectReceiveStream(state))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196from __future__ import annotations
from collections.abc import AsyncIterable, Iterable, Mapping, Sequencefrom io import BytesIOfrom os import PathLikefrom subprocess import PIPE, CalledProcessError, CompletedProcessfrom typing import IO, Any, TypeAlias, cast
from ..abc import Processfrom ._eventloop import get_async_backendfrom ._tasks import create_task_group
StrOrBytesPath: TypeAlias = str | bytes | PathLike[str] | PathLike[bytes]
async def run_process( command: StrOrBytesPath | Sequence[StrOrBytesPath], *, input: bytes | None = None, stdin: int | IO[Any] | None = None, stdout: int | IO[Any] | None = PIPE, stderr: int | IO[Any] | None = PIPE, check: bool = True, cwd: StrOrBytesPath | None = None, env: Mapping[str, str] | None = None, startupinfo: Any = None, creationflags: int = 0, start_new_session: bool = False, pass_fds: Sequence[int] = (), user: str | int | None = None, group: str | int | None = None, extra_groups: Iterable[str | int] | None = None, umask: int = -1,) -> CompletedProcess[bytes]: """ Run an external command in a subprocess and wait until it completes.
.. seealso:: :func:`subprocess.run`
:param command: either a string to pass to the shell, or an iterable of strings containing the executable name or path and its arguments :param input: bytes passed to the standard input of the subprocess :param stdin: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, a file-like object, or `None`; ``input`` overrides this :param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, a file-like object, or `None` :param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, :data:`subprocess.STDOUT`, a file-like object, or `None` :param check: if ``True``, raise :exc:`~subprocess.CalledProcessError` if the process terminates with a return code other than 0 :param cwd: If not ``None``, change the working directory to this before running the command :param env: if not ``None``, this mapping replaces the inherited environment variables from the parent process :param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used to specify process startup parameters (Windows only) :param creationflags: flags that can be used to control the creation of the subprocess (see :class:`subprocess.Popen` for the specifics) :param start_new_session: if ``true`` the setsid() system call will be made in the child process prior to the execution of the subprocess. (POSIX only) :param pass_fds: sequence of file descriptors to keep open between the parent and child processes. (POSIX only) :param user: effective user to run the process as (Python >= 3.9, POSIX only) :param group: effective group to run the process as (Python >= 3.9, POSIX only) :param extra_groups: supplementary groups to set in the subprocess (Python >= 3.9, POSIX only) :param umask: if not negative, this umask is applied in the child process before running the given command (Python >= 3.9, POSIX only) :return: an object representing the completed process :raises ~subprocess.CalledProcessError: if ``check`` is ``True`` and the process exits with a nonzero return code
"""
async def drain_stream(stream: AsyncIterable[bytes], index: int) -> None: buffer = BytesIO() async for chunk in stream: buffer.write(chunk)
stream_contents[index] = buffer.getvalue()
if stdin is not None and input is not None: raise ValueError("only one of stdin and input is allowed")
async with await open_process( command, stdin=PIPE if input else stdin, stdout=stdout, stderr=stderr, cwd=cwd, env=env, startupinfo=startupinfo, creationflags=creationflags, start_new_session=start_new_session, pass_fds=pass_fds, user=user, group=group, extra_groups=extra_groups, umask=umask, ) as process: stream_contents: list[bytes | None] = [None, None] async with create_task_group() as tg: if process.stdout: tg.start_soon(drain_stream, process.stdout, 0)
if process.stderr: tg.start_soon(drain_stream, process.stderr, 1)
if process.stdin and input: await process.stdin.send(input) await process.stdin.aclose()
await process.wait()
output, errors = stream_contents if check and process.returncode != 0: raise CalledProcessError(cast(int, process.returncode), command, output, errors)
return CompletedProcess(command, cast(int, process.returncode), output, errors)
async def open_process( command: StrOrBytesPath | Sequence[StrOrBytesPath], *, stdin: int | IO[Any] | None = PIPE, stdout: int | IO[Any] | None = PIPE, stderr: int | IO[Any] | None = PIPE, cwd: StrOrBytesPath | None = None, env: Mapping[str, str] | None = None, startupinfo: Any = None, creationflags: int = 0, start_new_session: bool = False, pass_fds: Sequence[int] = (), user: str | int | None = None, group: str | int | None = None, extra_groups: Iterable[str | int] | None = None, umask: int = -1,) -> Process: """ Start an external command in a subprocess.
.. seealso:: :class:`subprocess.Popen`
:param command: either a string to pass to the shell, or an iterable of strings containing the executable name or path and its arguments :param stdin: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, a file-like object, or ``None`` :param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, a file-like object, or ``None`` :param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, :data:`subprocess.STDOUT`, a file-like object, or ``None`` :param cwd: If not ``None``, the working directory is changed before executing :param env: If env is not ``None``, it must be a mapping that defines the environment variables for the new process :param creationflags: flags that can be used to control the creation of the subprocess (see :class:`subprocess.Popen` for the specifics) :param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used to specify process startup parameters (Windows only) :param start_new_session: if ``true`` the setsid() system call will be made in the child process prior to the execution of the subprocess. (POSIX only) :param pass_fds: sequence of file descriptors to keep open between the parent and child processes. (POSIX only) :param user: effective user to run the process as (POSIX only) :param group: effective group to run the process as (POSIX only) :param extra_groups: supplementary groups to set in the subprocess (POSIX only) :param umask: if not negative, this umask is applied in the child process before running the given command (POSIX only) :return: an asynchronous process object
""" kwargs: dict[str, Any] = {} if user is not None: kwargs["user"] = user
if group is not None: kwargs["group"] = group
if extra_groups is not None: kwargs["extra_groups"] = extra_groups
if umask >= 0: kwargs["umask"] = umask
return await get_async_backend().open_process( command, stdin=stdin, stdout=stdout, stderr=stderr, cwd=cwd, env=env, startupinfo=startupinfo, creationflags=creationflags, start_new_session=start_new_session, pass_fds=pass_fds, **kwargs, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772from __future__ import annotations
import mathfrom collections import dequefrom collections.abc import Callablefrom dataclasses import dataclassfrom types import TracebackTypefrom typing import TypeVar
from ..lowlevel import checkpoint_if_cancelledfrom ._eventloop import get_async_backendfrom ._exceptions import BusyResourceError, NoEventLoopErrorfrom ._tasks import CancelScopefrom ._testing import TaskInfo, get_current_task
T = TypeVar("T")
@dataclass(frozen=True)class EventStatistics: """ :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Event.wait` """
tasks_waiting: int
@dataclass(frozen=True)class CapacityLimiterStatistics: """ :ivar int borrowed_tokens: number of tokens currently borrowed by tasks :ivar float total_tokens: total number of available tokens :ivar tuple borrowers: tasks or other objects currently holding tokens borrowed from this limiter :ivar int tasks_waiting: number of tasks waiting on :meth:`~.CapacityLimiter.acquire` or :meth:`~.CapacityLimiter.acquire_on_behalf_of` """
borrowed_tokens: int total_tokens: float borrowers: tuple[object, ...] tasks_waiting: int
@dataclass(frozen=True)class LockStatistics: """ :ivar bool locked: flag indicating if this lock is locked or not :ivar ~anyio.TaskInfo owner: task currently holding the lock (or ``None`` if the lock is not held by any task) :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Lock.acquire` """
locked: bool owner: TaskInfo | None tasks_waiting: int
@dataclass(frozen=True)class ConditionStatistics: """ :ivar int tasks_waiting: number of tasks blocked on :meth:`~.Condition.wait` :ivar ~anyio.LockStatistics lock_statistics: statistics of the underlying :class:`~.Lock` """
tasks_waiting: int lock_statistics: LockStatistics
@dataclass(frozen=True)class SemaphoreStatistics: """ :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Semaphore.acquire`
"""
tasks_waiting: int
class Event: __slots__ = ("__weakref__",)
def __new__(cls) -> Event: try: return get_async_backend().create_event() except NoEventLoopError: return EventAdapter()
def set(self) -> None: """Set the flag, notifying all listeners.""" raise NotImplementedError
def is_set(self) -> bool: """Return ``True`` if the flag is set, ``False`` if not.""" raise NotImplementedError
async def wait(self) -> None: """ Wait until the flag has been set.
If the flag has already been set when this method is called, it returns immediately.
""" raise NotImplementedError
def statistics(self) -> EventStatistics: """Return statistics about the current state of this event.""" raise NotImplementedError
class EventAdapter(Event): __slots__ = "_internal_event", "_is_set"
def __new__(cls) -> EventAdapter: return object.__new__(cls)
def __init__(self) -> None: self._internal_event: Event | None = None self._is_set = False
@property def _event(self) -> Event: if self._internal_event is None: self._internal_event = get_async_backend().create_event() if self._is_set: self._internal_event.set()
return self._internal_event
def set(self) -> None: if self._internal_event is None: self._is_set = True else: self._event.set()
def is_set(self) -> bool: if self._internal_event is None: return self._is_set
return self._internal_event.is_set()
async def wait(self) -> None: await self._event.wait()
def statistics(self) -> EventStatistics: if self._internal_event is None: return EventStatistics(tasks_waiting=0)
return self._internal_event.statistics()
class Lock: __slots__ = ("__weakref__",)
def __new__(cls, *, fast_acquire: bool = False) -> Lock: try: return get_async_backend().create_lock(fast_acquire=fast_acquire) except NoEventLoopError: return LockAdapter(fast_acquire=fast_acquire)
async def __aenter__(self) -> None: await self.acquire()
async def __aexit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: self.release()
async def acquire(self) -> None: """Acquire the lock.""" raise NotImplementedError
def acquire_nowait(self) -> None: """ Acquire the lock, without blocking.
:raises ~anyio.WouldBlock: if the operation would block
""" raise NotImplementedError
def release(self) -> None: """Release the lock.""" raise NotImplementedError
def locked(self) -> bool: """Return True if the lock is currently held.""" raise NotImplementedError
def statistics(self) -> LockStatistics: """ Return statistics about the current state of this lock.
.. versionadded:: 3.0 """ raise NotImplementedError
class LockAdapter(Lock): __slots__ = "_internal_lock", "_fast_acquire"
def __new__(cls, *, fast_acquire: bool = False) -> LockAdapter: return object.__new__(cls)
def __init__(self, *, fast_acquire: bool = False): self._internal_lock: Lock | None = None self._fast_acquire = fast_acquire
@property def _lock(self) -> Lock: if self._internal_lock is None: self._internal_lock = get_async_backend().create_lock( fast_acquire=self._fast_acquire )
return self._internal_lock
async def __aenter__(self) -> None: await self._lock.acquire()
async def __aexit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: if self._internal_lock is not None: self._internal_lock.release()
async def acquire(self) -> None: """Acquire the lock.""" await self._lock.acquire()
def acquire_nowait(self) -> None: """ Acquire the lock, without blocking.
:raises ~anyio.WouldBlock: if the operation would block
""" self._lock.acquire_nowait()
def release(self) -> None: """Release the lock.""" self._lock.release()
def locked(self) -> bool: """Return True if the lock is currently held.""" return self._lock.locked()
def statistics(self) -> LockStatistics: """ Return statistics about the current state of this lock.
.. versionadded:: 3.0
""" if self._internal_lock is None: return LockStatistics(False, None, 0)
return self._internal_lock.statistics()
class Condition: __slots__ = "__weakref__", "_owner_task", "_lock", "_waiters"
def __init__(self, lock: Lock | None = None): self._owner_task: TaskInfo | None = None self._lock = lock or Lock() self._waiters: deque[Event] = deque()
async def __aenter__(self) -> None: await self.acquire()
async def __aexit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: self.release()
def _check_acquired(self) -> None: if self._owner_task != get_current_task(): raise RuntimeError("The current task is not holding the underlying lock")
async def acquire(self) -> None: """Acquire the underlying lock.""" await self._lock.acquire() self._owner_task = get_current_task()
def acquire_nowait(self) -> None: """ Acquire the underlying lock, without blocking.
:raises ~anyio.WouldBlock: if the operation would block
""" self._lock.acquire_nowait() self._owner_task = get_current_task()
def release(self) -> None: """Release the underlying lock.""" self._lock.release()
def locked(self) -> bool: """Return True if the lock is set.""" return self._lock.locked()
def notify(self, n: int = 1) -> None: """Notify exactly n listeners.""" self._check_acquired() for _ in range(n): try: event = self._waiters.popleft() except IndexError: break
event.set()
def notify_all(self) -> None: """Notify all the listeners.""" self._check_acquired() for event in self._waiters: event.set()
self._waiters.clear()
async def wait(self) -> None: """Wait for a notification.""" await checkpoint_if_cancelled() self._check_acquired() event = Event() self._waiters.append(event) self.release() try: await event.wait() except BaseException: if not event.is_set(): self._waiters.remove(event) elif self._waiters: # This task was notified by could not act on it, so pass # it on to the next task self._waiters.popleft().set()
raise finally: with CancelScope(shield=True): await self.acquire()
async def wait_for(self, predicate: Callable[[], T]) -> T: """ Wait until a predicate becomes true.
:param predicate: a callable that returns a truthy value when the condition is met :return: the result of the predicate
.. versionadded:: 4.11.0
""" while not (result := predicate()): await self.wait()
return result
def statistics(self) -> ConditionStatistics: """ Return statistics about the current state of this condition.
.. versionadded:: 3.0 """ return ConditionStatistics(len(self._waiters), self._lock.statistics())
class Semaphore: __slots__ = "__weakref__", "_fast_acquire"
def __new__( cls, initial_value: int, *, max_value: int | None = None, fast_acquire: bool = False, ) -> Semaphore: try: return get_async_backend().create_semaphore( initial_value, max_value=max_value, fast_acquire=fast_acquire ) except NoEventLoopError: return SemaphoreAdapter(initial_value, max_value=max_value)
def __init__( self, initial_value: int, *, max_value: int | None = None, fast_acquire: bool = False, ): if not isinstance(initial_value, int): raise TypeError("initial_value must be an integer") if initial_value < 0: raise ValueError("initial_value must be >= 0") if max_value is not None: if not isinstance(max_value, int): raise TypeError("max_value must be an integer or None") if max_value < initial_value: raise ValueError( "max_value must be equal to or higher than initial_value" )
self._fast_acquire = fast_acquire
async def __aenter__(self) -> Semaphore: await self.acquire() return self
async def __aexit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: self.release()
async def acquire(self) -> None: """Decrement the semaphore value, blocking if necessary.""" raise NotImplementedError
def acquire_nowait(self) -> None: """ Acquire the underlying lock, without blocking.
:raises ~anyio.WouldBlock: if the operation would block
""" raise NotImplementedError
def release(self) -> None: """Increment the semaphore value.""" raise NotImplementedError
@property def value(self) -> int: """The current value of the semaphore.""" raise NotImplementedError
@property def max_value(self) -> int | None: """The maximum value of the semaphore.""" raise NotImplementedError
def statistics(self) -> SemaphoreStatistics: """ Return statistics about the current state of this semaphore.
.. versionadded:: 3.0 """ raise NotImplementedError
class SemaphoreAdapter(Semaphore): __slots__ = "_internal_semaphore", "_initial_value", "_max_value"
def __new__( cls, initial_value: int, *, max_value: int | None = None, fast_acquire: bool = False, ) -> SemaphoreAdapter: return object.__new__(cls)
def __init__( self, initial_value: int, *, max_value: int | None = None, fast_acquire: bool = False, ) -> None: super().__init__(initial_value, max_value=max_value, fast_acquire=fast_acquire) self._internal_semaphore: Semaphore | None = None self._initial_value = initial_value self._max_value = max_value
@property def _semaphore(self) -> Semaphore: if self._internal_semaphore is None: self._internal_semaphore = get_async_backend().create_semaphore( self._initial_value, max_value=self._max_value )
return self._internal_semaphore
async def acquire(self) -> None: await self._semaphore.acquire()
def acquire_nowait(self) -> None: self._semaphore.acquire_nowait()
def release(self) -> None: self._semaphore.release()
@property def value(self) -> int: if self._internal_semaphore is None: return self._initial_value
return self._semaphore.value
@property def max_value(self) -> int | None: return self._max_value
def statistics(self) -> SemaphoreStatistics: if self._internal_semaphore is None: return SemaphoreStatistics(tasks_waiting=0)
return self._semaphore.statistics()
class CapacityLimiter: __slots__ = ("__weakref__",)
def __new__(cls, total_tokens: float) -> CapacityLimiter: try: return get_async_backend().create_capacity_limiter(total_tokens) except NoEventLoopError: return CapacityLimiterAdapter(total_tokens)
async def __aenter__(self) -> None: raise NotImplementedError
async def __aexit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: raise NotImplementedError
@property def total_tokens(self) -> float: """ The total number of tokens available for borrowing.
This is a read-write property. If the total number of tokens is increased, the proportionate number of tasks waiting on this limiter will be granted their tokens.
.. versionchanged:: 3.0 The property is now writable. .. versionchanged:: 4.12 The value can now be set to 0.
""" raise NotImplementedError
@total_tokens.setter def total_tokens(self, value: float) -> None: raise NotImplementedError
@property def borrowed_tokens(self) -> int: """The number of tokens that have currently been borrowed.""" raise NotImplementedError
@property def available_tokens(self) -> float: """The number of tokens currently available to be borrowed""" raise NotImplementedError
def acquire_nowait(self) -> None: """ Acquire a token for the current task without waiting for one to become available.
:raises ~anyio.WouldBlock: if there are no tokens available for borrowing
""" raise NotImplementedError
def acquire_on_behalf_of_nowait(self, borrower: object) -> None: """ Acquire a token without waiting for one to become available.
:param borrower: the entity borrowing a token :raises ~anyio.WouldBlock: if there are no tokens available for borrowing
""" raise NotImplementedError
async def acquire(self) -> None: """ Acquire a token for the current task, waiting if necessary for one to become available.
""" raise NotImplementedError
async def acquire_on_behalf_of(self, borrower: object) -> None: """ Acquire a token, waiting if necessary for one to become available.
:param borrower: the entity borrowing a token
""" raise NotImplementedError
def release(self) -> None: """ Release the token held by the current task.
:raises RuntimeError: if the current task has not borrowed a token from this limiter.
""" raise NotImplementedError
def release_on_behalf_of(self, borrower: object) -> None: """ Release the token held by the given borrower.
:raises RuntimeError: if the borrower has not borrowed a token from this limiter.
""" raise NotImplementedError
def statistics(self) -> CapacityLimiterStatistics: """ Return statistics about the current state of this limiter.
.. versionadded:: 3.0
""" raise NotImplementedError
class CapacityLimiterAdapter(CapacityLimiter): __slots__ = "_internal_limiter", "_total_tokens"
def __new__(cls, total_tokens: float) -> CapacityLimiterAdapter: return object.__new__(cls)
def __init__(self, total_tokens: float) -> None: self._internal_limiter: CapacityLimiter | None = None self.total_tokens = total_tokens
@property def _limiter(self) -> CapacityLimiter: if self._internal_limiter is None: self._internal_limiter = get_async_backend().create_capacity_limiter( self._total_tokens )
return self._internal_limiter
async def __aenter__(self) -> None: await self._limiter.__aenter__()
async def __aexit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: return await self._limiter.__aexit__(exc_type, exc_val, exc_tb)
@property def total_tokens(self) -> float: if self._internal_limiter is None: return self._total_tokens
return self._internal_limiter.total_tokens
@total_tokens.setter def total_tokens(self, value: float) -> None: if not isinstance(value, int) and not math.isinf(value): raise TypeError("total_tokens must be an int or math.inf") elif value < 0: raise ValueError("total_tokens must be >= 0")
if self._internal_limiter is None: self._total_tokens = value return
self._limiter.total_tokens = value
@property def borrowed_tokens(self) -> int: if self._internal_limiter is None: return 0
return self._internal_limiter.borrowed_tokens
@property def available_tokens(self) -> float: if self._internal_limiter is None: return self._total_tokens
return self._internal_limiter.available_tokens
def acquire_nowait(self) -> None: self._limiter.acquire_nowait()
def acquire_on_behalf_of_nowait(self, borrower: object) -> None: self._limiter.acquire_on_behalf_of_nowait(borrower)
async def acquire(self) -> None: await self._limiter.acquire()
async def acquire_on_behalf_of(self, borrower: object) -> None: await self._limiter.acquire_on_behalf_of(borrower)
def release(self) -> None: self._limiter.release()
def release_on_behalf_of(self, borrower: object) -> None: self._limiter.release_on_behalf_of(borrower)
def statistics(self) -> CapacityLimiterStatistics: if self._internal_limiter is None: return CapacityLimiterStatistics( borrowed_tokens=0, total_tokens=self.total_tokens, borrowers=(), tasks_waiting=0, )
return self._internal_limiter.statistics()
class ResourceGuard: """ A context manager for ensuring that a resource is only used by a single task at a time.
Entering this context manager while the previous has not exited it yet will trigger :exc:`BusyResourceError`.
:param action: the action to guard against (visible in the :exc:`BusyResourceError` when triggered, e.g. "Another task is already {action} this resource")
.. versionadded:: 4.1 """
__slots__ = "__weakref__", "action", "_guarded"
def __init__(self, action: str = "using"): self.action: str = action self._guarded = False
def __enter__(self) -> None: if self._guarded: raise BusyResourceError(self.action)
self._guarded = True
def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: self._guarded = False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412from __future__ import annotations
import mathimport sysfrom collections.abc import ( Coroutine, Generator,)from contextlib import ( contextmanager,)from enum import Enum, autofrom inspect import iscoroutinefrom types import TracebackTypefrom typing import Any, Generic, final
from ..abc import TaskGroup, TaskStatusfrom ._eventloop import get_async_backend, get_cancelled_exc_classfrom ._exceptions import TaskCancelled, TaskFailed, TaskNotFinished
if sys.version_info >= (3, 13): from typing import TypeVarelse: from typing_extensions import TypeVar
if sys.version_info >= (3, 11): from typing import Never, TypeVarTupleelse: from typing_extensions import Never, TypeVarTuple
T = TypeVar("T")T_co = TypeVar("T_co", covariant=True)T_startval = TypeVar("T_startval", covariant=True, default=Never)PosArgsT = TypeVarTuple("PosArgsT")
class _IgnoredTaskStatus(TaskStatus[object]): def started(self, value: object = None) -> None: pass
TASK_STATUS_IGNORED = _IgnoredTaskStatus()
class CancelScope: """ Wraps a unit of work that can be made separately cancellable.
:param deadline: The time (clock value) when this scope is cancelled automatically :param shield: ``True`` to shield the cancel scope from external cancellation :raises NoEventLoopError: if no supported asynchronous event loop is running in the current thread """
__slots__ = ("__weakref__",)
def __new__( cls, *, deadline: float = math.inf, shield: bool = False ) -> CancelScope: return get_async_backend().create_cancel_scope(shield=shield, deadline=deadline)
def cancel(self, reason: str | None = None) -> None: """ Cancel this scope immediately.
:param reason: a message describing the reason for the cancellation
""" raise NotImplementedError
@property def deadline(self) -> float: """ The time (clock value) when this scope is cancelled automatically.
Will be ``float('inf')`` if no timeout has been set.
""" raise NotImplementedError
@deadline.setter def deadline(self, value: float) -> None: raise NotImplementedError
@property def cancel_called(self) -> bool: """``True`` if :meth:`cancel` has been called.""" raise NotImplementedError
@property def cancelled_caught(self) -> bool: """ ``True`` if this scope suppressed a cancellation exception it itself raised.
This is typically used to check if any work was interrupted, or to see if the scope was cancelled due to its deadline being reached. The value will, however, only be ``True`` if the cancellation was triggered by the scope itself (and not an outer scope).
""" raise NotImplementedError
@property def shield(self) -> bool: """ ``True`` if this scope is shielded from external cancellation.
While a scope is shielded, it will not receive cancellations from outside.
""" raise NotImplementedError
@shield.setter def shield(self, value: bool) -> None: raise NotImplementedError
def __enter__(self) -> CancelScope: raise NotImplementedError
def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> bool: raise NotImplementedError
@contextmanagerdef fail_after( delay: float | None, shield: bool = False) -> Generator[CancelScope, None, None]: """ Create a context manager which raises a :class:`TimeoutError` if does not finish in time.
:param delay: maximum allowed time (in seconds) before raising the exception, or ``None`` to disable the timeout :param shield: ``True`` to shield the cancel scope from external cancellation :return: a context manager that yields a cancel scope :rtype: :class:`~typing.ContextManager`\\[:class:`~anyio.CancelScope`\\] :raises NoEventLoopError: if no supported asynchronous event loop is running in the current thread
""" current_time = get_async_backend().current_time deadline = (current_time() + delay) if delay is not None else math.inf with get_async_backend().create_cancel_scope( deadline=deadline, shield=shield ) as cancel_scope: yield cancel_scope
if cancel_scope.cancelled_caught and current_time() >= cancel_scope.deadline: raise TimeoutError
def move_on_after(delay: float | None, shield: bool = False) -> CancelScope: """ Create a cancel scope with a deadline that expires after the given delay.
:param delay: maximum allowed time (in seconds) before exiting the context block, or ``None`` to disable the timeout :param shield: ``True`` to shield the cancel scope from external cancellation :return: a cancel scope :raises NoEventLoopError: if no supported asynchronous event loop is running in the current thread
""" deadline = ( (get_async_backend().current_time() + delay) if delay is not None else math.inf ) return get_async_backend().create_cancel_scope(deadline=deadline, shield=shield)
def current_effective_deadline() -> float: """ Return the nearest deadline among all the cancel scopes effective for the current task.
:return: a clock value from the event loop's internal clock (or ``float('inf')`` if there is no deadline in effect, or ``float('-inf')`` if the current scope has been cancelled) :rtype: float :raises NoEventLoopError: if no supported asynchronous event loop is running in the current thread
""" return get_async_backend().current_effective_deadline()
def create_task_group() -> TaskGroup: """ Create a task group.
:return: a task group :raises NoEventLoopError: if no supported asynchronous event loop is running in the current thread
""" return get_async_backend().create_task_group()
@finalclass TaskHandle(Generic[T_co, T_startval]): """ Returned from the task-spawning methods of :class:`TaskGroup`. Can be awaited on to get the return value of the task (or the raised exception). If the task was terminated by a :exc:`BaseException`, :exc:`TaskFailed` will be raised (or its subclass :exc:`TaskCancelled` if the task was cancelled).
.. versionadded:: 4.14.0 """
class Status(Enum): """ The status of a task handle.
.. attribute:: PENDING
The task has not finished yet. .. attribute:: FINISHED
The task has finished with a return value. .. attribute:: CANCELLING
The task has been cancelled but has not finished yet. .. attribute:: CANCELLED
The task was cancelled and has finished since. .. attribute:: FAILED
The task raised an exception. """
PENDING = auto() FINISHED = auto() CANCELLING = auto() CANCELLED = auto() FAILED = auto()
__slots__ = ( "__weakref__", "_coro", "_name", "_cancel_scope", "_finished_event", "_return_value", "_start_value", "_exception", )
_return_value: T_co _start_value: T_startval
def __init__(self, coro: Coroutine[Any, Any, T_co], name: object) -> None: from ._synchronization import Event
self._coro = coro self._cancel_scope = CancelScope() self._finished_event = Event() self._exception: BaseException | None = None
if name is not None: self._name = str(name) elif iscoroutine(coro): self._name = coro.__qualname__ else: self._name = str(coro) # coroutine-like object (e.g. asend() objects)
async def _run_coro(self) -> None: __tracebackhide__ = True
with self._cancel_scope: try: retval = await self._coro except BaseException as exc: self._exception = exc raise else: self._return_value = retval finally: self._finished_event.set() del self # Break the reference cycle
def cancel(self) -> None: """ Set the task to a cancelled state.
This will interrupt any interruptible asynchronous operation, and will cause any further awaits on this task to get immediately cancelled, unless done in a shielded cancel scope.
If the task has already finished, this method has no effect. """ if not self._finished_event.is_set(): self._cancel_scope.cancel()
@property def coro(self) -> Coroutine[Any, Any, T_co]: """ The coroutine object that was passed to one of the task-spawning methods in :class:`TaskGroup`. """ return self._coro
@property def status(self) -> TaskHandle.Status: """ The current status of the task.
Every task starts in the :attr:`~TaskHandle.Status.PENDING` state. If a task is cancelled while in this state, it will transition to the :attr:`~TaskHandle.Status.CANCELLING` state. When the task finishes, it will transition to one of the three final states ( :attr:`~TaskHandle.Status.FINISHED`, :attr:`~TaskHandle.Status.FAILED`, or :attr:`~TaskHandle.Status.CANCELLING`) depending on the exception the task raised, if any. No other status transitions will happen. """ if not self._finished_event.is_set(): if self._cancel_scope.cancel_called: return TaskHandle.Status.CANCELLING else: return TaskHandle.Status.PENDING elif self._exception is not None: if isinstance(self._exception, get_cancelled_exc_class()): return TaskHandle.Status.CANCELLED else: return TaskHandle.Status.FAILED else: return TaskHandle.Status.FINISHED
@property def name(self) -> str: """The name of the task.""" return self._name
@property def exception(self) -> BaseException | None: """ The exception raised by the task, or ``None`` if it finished without raising.
:raises TaskNotFinished: if the task has not finished yet :raises TaskCancelled: if the task was cancelled
""" match self.status: case TaskHandle.Status.PENDING: raise TaskNotFinished("the task has not finished yet") case TaskHandle.Status.FINISHED: return None case TaskHandle.Status.CANCELLING: raise TaskCancelled("the task was cancelled") case TaskHandle.Status.CANCELLED: raise TaskCancelled("the task was cancelled") from self._exception case TaskHandle.Status.FAILED: return self._exception
@property def return_value(self) -> T_co: """ The return value of the task.
:raises TaskNotFinished: if the task has not finished yet :raises TaskCancelled: if the task was cancelled :raises TaskFailed: if the task raised an exception
""" match self.status: case TaskHandle.Status.PENDING: raise TaskNotFinished("the task has not finished yet") case TaskHandle.Status.FINISHED: return self._return_value case TaskHandle.Status.CANCELLING: raise TaskCancelled("the task was cancelled") case TaskHandle.Status.CANCELLED: raise TaskCancelled("the task was cancelled") from self._exception case TaskHandle.Status.FAILED: raise TaskFailed("the task raised an exception") from self._exception
@property def start_value(self) -> T_startval: """ The value passed to :meth:`task_status.started() <.abc.TaskStatus.started>`,
:raises RuntimeError: if the task was not started with :meth:`TaskGroup.start() <.abc.TaskGroup.start>` """ try: return self._start_value except AttributeError: raise RuntimeError( "the task was not started with TaskGroup.start()" ) from None
async def wait(self) -> None: """ Wait for the task to finish.
This method will return as soon as the task has finished, no matter how it happened. """ await self._finished_event.wait()
def __await__(self) -> Generator[Any, Any, T_co]: yield from self._finished_event.wait().__await__() return self.return_value
def __repr__(self) -> str: return ( f"<{self.__class__.__name__} {self.status.name.lower()} " f"name={self._name!r} coro={self._coro!r}>" )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613from __future__ import annotations
import osimport sysimport tempfilefrom collections.abc import Iterablefrom io import BytesIO, TextIOWrapperfrom types import TracebackTypefrom typing import ( TYPE_CHECKING, Any, AnyStr, Generic, overload,)
from .. import to_threadfrom .._core._fileio import AsyncFilefrom ..lowlevel import checkpoint_if_cancelled
if TYPE_CHECKING: from _typeshed import OpenBinaryMode, OpenTextMode, ReadableBuffer, WriteableBuffer
class TemporaryFile(Generic[AnyStr]): """ An asynchronous temporary file that is automatically created and cleaned up.
This class provides an asynchronous context manager interface to a temporary file. The file is created using Python's standard `tempfile.TemporaryFile` function in a background thread, and is wrapped as an asynchronous file using `AsyncFile`.
:param mode: The mode in which the file is opened. Defaults to "w+b". :param buffering: The buffering policy (-1 means the default buffering). :param encoding: The encoding used to decode or encode the file. Only applicable in text mode. :param newline: Controls how universal newlines mode works (only applicable in text mode). :param suffix: The suffix for the temporary file name. :param prefix: The prefix for the temporary file name. :param dir: The directory in which the temporary file is created. :param errors: The error handling scheme used for encoding/decoding errors. """
_async_file: AsyncFile[AnyStr]
@overload def __init__( self: TemporaryFile[bytes], mode: OpenBinaryMode = ..., buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., suffix: str | None = ..., prefix: str | None = ..., dir: str | None = ..., *, errors: str | None = ..., ): ... @overload def __init__( self: TemporaryFile[str], mode: OpenTextMode, buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., suffix: str | None = ..., prefix: str | None = ..., dir: str | None = ..., *, errors: str | None = ..., ): ...
def __init__( self, mode: OpenTextMode | OpenBinaryMode = "w+b", buffering: int = -1, encoding: str | None = None, newline: str | None = None, suffix: str | None = None, prefix: str | None = None, dir: str | None = None, *, errors: str | None = None, ) -> None: self.mode = mode self.buffering = buffering self.encoding = encoding self.newline = newline self.suffix: str | None = suffix self.prefix: str | None = prefix self.dir: str | None = dir self.errors = errors
async def __aenter__(self) -> AsyncFile[AnyStr]: fp = await to_thread.run_sync( lambda: tempfile.TemporaryFile( self.mode, self.buffering, self.encoding, self.newline, self.suffix, self.prefix, self.dir, errors=self.errors, ) ) self._async_file = AsyncFile(fp) return self._async_file
async def __aexit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: await self._async_file.aclose()
class NamedTemporaryFile(Generic[AnyStr]): """ An asynchronous named temporary file that is automatically created and cleaned up.
This class provides an asynchronous context manager for a temporary file with a visible name in the file system. It uses Python's standard :func:`~tempfile.NamedTemporaryFile` function and wraps the file object with :class:`AsyncFile` for asynchronous operations.
:param mode: The mode in which the file is opened. Defaults to "w+b". :param buffering: The buffering policy (-1 means the default buffering). :param encoding: The encoding used to decode or encode the file. Only applicable in text mode. :param newline: Controls how universal newlines mode works (only applicable in text mode). :param suffix: The suffix for the temporary file name. :param prefix: The prefix for the temporary file name. :param dir: The directory in which the temporary file is created. :param delete: Whether to delete the file when it is closed. :param errors: The error handling scheme used for encoding/decoding errors. :param delete_on_close: (Python 3.12+) Whether to delete the file on close. """
_async_file: AsyncFile[AnyStr]
@overload def __init__( self: NamedTemporaryFile[bytes], mode: OpenBinaryMode = ..., buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., suffix: str | None = ..., prefix: str | None = ..., dir: str | None = ..., delete: bool = ..., *, errors: str | None = ..., delete_on_close: bool = ..., ): ... @overload def __init__( self: NamedTemporaryFile[str], mode: OpenTextMode, buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., suffix: str | None = ..., prefix: str | None = ..., dir: str | None = ..., delete: bool = ..., *, errors: str | None = ..., delete_on_close: bool = ..., ): ...
def __init__( self, mode: OpenBinaryMode | OpenTextMode = "w+b", buffering: int = -1, encoding: str | None = None, newline: str | None = None, suffix: str | None = None, prefix: str | None = None, dir: str | None = None, delete: bool = True, *, errors: str | None = None, delete_on_close: bool = True, ) -> None: self._params: dict[str, Any] = { "mode": mode, "buffering": buffering, "encoding": encoding, "newline": newline, "suffix": suffix, "prefix": prefix, "dir": dir, "delete": delete, "errors": errors, } if sys.version_info >= (3, 12): self._params["delete_on_close"] = delete_on_close
async def __aenter__(self) -> AsyncFile[AnyStr]: fp = await to_thread.run_sync( lambda: tempfile.NamedTemporaryFile(**self._params) ) self._async_file = AsyncFile(fp) return self._async_file
async def __aexit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: await self._async_file.aclose()
class SpooledTemporaryFile(AsyncFile[AnyStr]): """ An asynchronous spooled temporary file that starts in memory and is spooled to disk.
This class provides an asynchronous interface to a spooled temporary file, much like Python's standard :class:`~tempfile.SpooledTemporaryFile`. It supports asynchronous write operations and provides a method to force a rollover to disk.
:param max_size: Maximum size in bytes before the file is rolled over to disk. :param mode: The mode in which the file is opened. Defaults to "w+b". :param buffering: The buffering policy (-1 means the default buffering). :param encoding: The encoding used to decode or encode the file (text mode only). :param newline: Controls how universal newlines mode works (text mode only). :param suffix: The suffix for the temporary file name. :param prefix: The prefix for the temporary file name. :param dir: The directory in which the temporary file is created. :param errors: The error handling scheme used for encoding/decoding errors. """
_rolled: bool = False
@overload def __init__( self: SpooledTemporaryFile[bytes], max_size: int = ..., mode: OpenBinaryMode = ..., buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., suffix: str | None = ..., prefix: str | None = ..., dir: str | None = ..., *, errors: str | None = ..., ): ... @overload def __init__( self: SpooledTemporaryFile[str], max_size: int = ..., mode: OpenTextMode = ..., buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., suffix: str | None = ..., prefix: str | None = ..., dir: str | None = ..., *, errors: str | None = ..., ): ...
def __init__( self, max_size: int = 0, mode: OpenBinaryMode | OpenTextMode = "w+b", buffering: int = -1, encoding: str | None = None, newline: str | None = None, suffix: str | None = None, prefix: str | None = None, dir: str | None = None, *, errors: str | None = None, ) -> None: self._tempfile_params: dict[str, Any] = { "mode": mode, "buffering": buffering, "encoding": encoding, "newline": newline, "suffix": suffix, "prefix": prefix, "dir": dir, "errors": errors, } self._max_size = max_size if "b" in mode: super().__init__(BytesIO()) # type: ignore[arg-type] else: super().__init__( TextIOWrapper( # type: ignore[arg-type] BytesIO(), encoding=encoding, errors=errors, newline=newline, write_through=True, ) )
async def aclose(self) -> None: if not self._rolled: self._fp.close() return
await super().aclose()
async def _check(self) -> None: if self._rolled or self._fp.tell() <= self._max_size: return
await self.rollover()
async def rollover(self) -> None: if self._rolled: return
self._rolled = True buffer = self._fp buffer.seek(0) self._fp = await to_thread.run_sync( lambda: tempfile.TemporaryFile(**self._tempfile_params) ) await self.write(buffer.read()) buffer.close()
@property def closed(self) -> bool: return self._fp.closed
async def read(self, size: int = -1) -> AnyStr: if not self._rolled: await checkpoint_if_cancelled() return self._fp.read(size)
return await super().read(size) # type: ignore[return-value]
async def read1(self: SpooledTemporaryFile[bytes], size: int = -1) -> bytes: if not self._rolled: await checkpoint_if_cancelled() return self._fp.read1(size)
return await super().read1(size)
async def readline(self) -> AnyStr: if not self._rolled: await checkpoint_if_cancelled() return self._fp.readline()
return await super().readline() # type: ignore[return-value]
async def readlines(self) -> list[AnyStr]: if not self._rolled: await checkpoint_if_cancelled() return self._fp.readlines()
return await super().readlines() # type: ignore[return-value]
async def readinto(self: SpooledTemporaryFile[bytes], b: WriteableBuffer) -> int: if not self._rolled: await checkpoint_if_cancelled() self._fp.readinto(b)
return await super().readinto(b)
async def readinto1(self: SpooledTemporaryFile[bytes], b: WriteableBuffer) -> int: if not self._rolled: await checkpoint_if_cancelled() self._fp.readinto(b)
return await super().readinto1(b)
async def seek(self, offset: int, whence: int | None = os.SEEK_SET) -> int: if not self._rolled: await checkpoint_if_cancelled() return self._fp.seek(offset, whence)
return await super().seek(offset, whence)
async def tell(self) -> int: if not self._rolled: await checkpoint_if_cancelled() return self._fp.tell()
return await super().tell()
async def truncate(self, size: int | None = None) -> int: if not self._rolled: await checkpoint_if_cancelled() return self._fp.truncate(size)
return await super().truncate(size)
@overload async def write(self: SpooledTemporaryFile[bytes], b: ReadableBuffer) -> int: ... @overload async def write(self: SpooledTemporaryFile[str], b: str) -> int: ...
async def write(self, b: ReadableBuffer | str) -> int: """ Asynchronously write data to the spooled temporary file.
If the file has not yet been rolled over, the data is written synchronously, and a rollover is triggered if the size exceeds the maximum size.
:param s: The data to write. :return: The number of bytes written. :raises RuntimeError: If the underlying file is not initialized.
""" if not self._rolled: await checkpoint_if_cancelled() result = self._fp.write(b) await self._check() return result
return await super().write(b) # type: ignore[misc]
@overload async def writelines( self: SpooledTemporaryFile[bytes], lines: Iterable[ReadableBuffer] ) -> None: ... @overload async def writelines( self: SpooledTemporaryFile[str], lines: Iterable[str] ) -> None: ...
async def writelines(self, lines: Iterable[str] | Iterable[ReadableBuffer]) -> None: """ Asynchronously write a list of lines to the spooled temporary file.
If the file has not yet been rolled over, the lines are written synchronously, and a rollover is triggered if the size exceeds the maximum size.
:param lines: An iterable of lines to write. :raises RuntimeError: If the underlying file is not initialized.
""" if not self._rolled: await checkpoint_if_cancelled() result = self._fp.writelines(lines) await self._check() return result
return await super().writelines(lines) # type: ignore[misc]
class TemporaryDirectory(Generic[AnyStr]): """ An asynchronous temporary directory that is created and cleaned up automatically.
This class provides an asynchronous context manager for creating a temporary directory. It wraps Python's standard :class:`~tempfile.TemporaryDirectory` to perform directory creation and cleanup operations in a background thread.
:param suffix: Suffix to be added to the temporary directory name. :param prefix: Prefix to be added to the temporary directory name. :param dir: The parent directory where the temporary directory is created. :param ignore_cleanup_errors: Whether to ignore errors during cleanup :param delete: Whether to delete the directory upon closing (Python 3.12+). """
def __init__( self, suffix: AnyStr | None = None, prefix: AnyStr | None = None, dir: AnyStr | None = None, *, ignore_cleanup_errors: bool = False, delete: bool = True, ) -> None: self.suffix: AnyStr | None = suffix self.prefix: AnyStr | None = prefix self.dir: AnyStr | None = dir self.ignore_cleanup_errors = ignore_cleanup_errors self.delete = delete
self._tempdir: tempfile.TemporaryDirectory | None = None
async def __aenter__(self) -> str: params: dict[str, Any] = { "suffix": self.suffix, "prefix": self.prefix, "dir": self.dir, "ignore_cleanup_errors": self.ignore_cleanup_errors, } if sys.version_info >= (3, 12): params["delete"] = self.delete
self._tempdir = await to_thread.run_sync( lambda: tempfile.TemporaryDirectory(**params) ) return await to_thread.run_sync(self._tempdir.__enter__)
async def __aexit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: if self._tempdir is not None: await to_thread.run_sync( self._tempdir.__exit__, exc_type, exc_value, traceback )
async def cleanup(self) -> None: if self._tempdir is not None: await to_thread.run_sync(self._tempdir.cleanup)
@overloadasync def mkstemp( suffix: str | None = None, prefix: str | None = None, dir: str | None = None, text: bool = False,) -> tuple[int, str]: ...
@overloadasync def mkstemp( suffix: bytes | None = None, prefix: bytes | None = None, dir: bytes | None = None, text: bool = False,) -> tuple[int, bytes]: ...
async def mkstemp( suffix: AnyStr | None = None, prefix: AnyStr | None = None, dir: AnyStr | None = None, text: bool = False,) -> tuple[int, str | bytes]: """ Asynchronously create a temporary file and return an OS-level handle and the file name.
This function wraps `tempfile.mkstemp` and executes it in a background thread.
:param suffix: Suffix to be added to the file name. :param prefix: Prefix to be added to the file name. :param dir: Directory in which the temporary file is created. :param text: Whether the file is opened in text mode. :return: A tuple containing the file descriptor and the file name.
""" return await to_thread.run_sync(tempfile.mkstemp, suffix, prefix, dir, text)
@overloadasync def mkdtemp( suffix: str | None = None, prefix: str | None = None, dir: str | None = None,) -> str: ...
@overloadasync def mkdtemp( suffix: bytes | None = None, prefix: bytes | None = None, dir: bytes | None = None,) -> bytes: ...
async def mkdtemp( suffix: AnyStr | None = None, prefix: AnyStr | None = None, dir: AnyStr | None = None,) -> str | bytes: """ Asynchronously create a temporary directory and return its path.
This function wraps `tempfile.mkdtemp` and executes it in a background thread.
:param suffix: Suffix to be added to the directory name. :param prefix: Prefix to be added to the directory name. :param dir: Parent directory where the temporary directory is created. :return: The path of the created temporary directory.
""" return await to_thread.run_sync(tempfile.mkdtemp, suffix, prefix, dir)
async def gettempdir() -> str: """ Asynchronously return the name of the directory used for temporary files.
This function wraps `tempfile.gettempdir` and executes it in a background thread.
:return: The path of the temporary directory as a string.
""" return await to_thread.run_sync(tempfile.gettempdir)
async def gettempdirb() -> bytes: """ Asynchronously return the name of the directory used for temporary files in bytes.
This function wraps `tempfile.gettempdirb` and executes it in a background thread.
:return: The path of the temporary directory as bytes.
""" return await to_thread.run_sync(tempfile.gettempdirb)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182from __future__ import annotations
from collections.abc import Awaitable, Generatorfrom typing import Any, cast
from ._eventloop import get_async_backend
class TaskInfo: """ Represents an asynchronous task.
:ivar int id: the unique identifier of the task :ivar parent_id: the identifier of the parent task, if any :vartype parent_id: Optional[int] :ivar str name: the description of the task (if any) :ivar ~collections.abc.Coroutine coro: the coroutine object of the task """
__slots__ = "_name", "id", "parent_id", "name", "coro"
def __init__( self, id: int, parent_id: int | None, name: str | None, coro: Generator[Any, Any, Any] | Awaitable[Any], ): func = get_current_task self._name = f"{func.__module__}.{func.__qualname__}" self.id: int = id self.parent_id: int | None = parent_id self.name: str | None = name self.coro: Generator[Any, Any, Any] | Awaitable[Any] = coro
def __eq__(self, other: object) -> bool: if isinstance(other, TaskInfo): return self.id == other.id
return NotImplemented
def __hash__(self) -> int: return hash(self.id)
def __repr__(self) -> str: return f"{self.__class__.__name__}(id={self.id!r}, name={self.name!r})"
def has_pending_cancellation(self) -> bool: """ Return ``True`` if the task has a cancellation pending, ``False`` otherwise.
""" return False
def get_current_task() -> TaskInfo: """ Return the current task.
:return: a representation of the current task :raises NoEventLoopError: if no supported asynchronous event loop is running in the current thread
""" return get_async_backend().get_current_task()
def get_running_tasks() -> list[TaskInfo]: """ Return a list of running tasks in the current event loop.
:return: a list of task info objects :raises NoEventLoopError: if no supported asynchronous event loop is running in the current thread
""" return cast("list[TaskInfo]", get_async_backend().get_running_tasks())
async def wait_all_tasks_blocked() -> None: """Wait until all other tasks are waiting for something.""" await get_async_backend().wait_all_tasks_blocked()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081from __future__ import annotations
from collections.abc import Callable, Mappingfrom typing import Any, TypeVar, final, overload
from ._exceptions import TypedAttributeLookupError
T_Attr = TypeVar("T_Attr")T_Default = TypeVar("T_Default")undefined = object()
def typed_attribute() -> Any: """Return a unique object, used to mark typed attributes.""" return object()
class TypedAttributeSet: """ Superclass for typed attribute collections.
Checks that every public attribute of every subclass has a type annotation. """
def __init_subclass__(cls) -> None: annotations: dict[str, Any] = getattr(cls, "__annotations__", {}) for attrname in dir(cls): if not attrname.startswith("_") and attrname not in annotations: raise TypeError( f"Attribute {attrname!r} is missing its type annotation" )
super().__init_subclass__()
class TypedAttributeProvider: """Base class for classes that wish to provide typed extra attributes."""
@property def extra_attributes(self) -> Mapping[T_Attr, Callable[[], T_Attr]]: """ A mapping of the extra attributes to callables that return the corresponding values.
If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).
""" return {}
@overload def extra(self, attribute: T_Attr) -> T_Attr: ...
@overload def extra(self, attribute: T_Attr, default: T_Default) -> T_Attr | T_Default: ...
@final def extra(self, attribute: Any, default: object = undefined) -> object: """ extra(attribute, default=undefined)
Return the value of the given typed extra attribute.
:param attribute: the attribute (member of a :class:`~TypedAttributeSet`) to look for :param default: the value that should be returned if no value is found for the attribute :raises ~anyio.TypedAttributeLookupError: if the search failed and no default value was given
""" try: getter = self.extra_attributes[attribute] except KeyError: if default is undefined: raise TypedAttributeLookupError("Attribute not found") from None else: return default
return getter()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758from __future__ import annotations
from ._eventloop import AsyncBackend as AsyncBackendfrom ._resources import AsyncResource as AsyncResourcefrom ._sockets import ConnectedUDPSocket as ConnectedUDPSocketfrom ._sockets import ConnectedUNIXDatagramSocket as ConnectedUNIXDatagramSocketfrom ._sockets import IPAddressType as IPAddressTypefrom ._sockets import IPSockAddrType as IPSockAddrTypefrom ._sockets import SocketAttribute as SocketAttributefrom ._sockets import SocketListener as SocketListenerfrom ._sockets import SocketStream as SocketStreamfrom ._sockets import UDPPacketType as UDPPacketTypefrom ._sockets import UDPSocket as UDPSocketfrom ._sockets import UNIXDatagramPacketType as UNIXDatagramPacketTypefrom ._sockets import UNIXDatagramSocket as UNIXDatagramSocketfrom ._sockets import UNIXSocketStream as UNIXSocketStreamfrom ._streams import AnyByteReceiveStream as AnyByteReceiveStreamfrom ._streams import AnyByteSendStream as AnyByteSendStreamfrom ._streams import AnyByteStream as AnyByteStreamfrom ._streams import AnyByteStreamConnectable as AnyByteStreamConnectablefrom ._streams import AnyUnreliableByteReceiveStream as AnyUnreliableByteReceiveStreamfrom ._streams import AnyUnreliableByteSendStream as AnyUnreliableByteSendStreamfrom ._streams import AnyUnreliableByteStream as AnyUnreliableByteStreamfrom ._streams import ByteReceiveStream as ByteReceiveStreamfrom ._streams import ByteSendStream as ByteSendStreamfrom ._streams import ByteStream as ByteStreamfrom ._streams import ByteStreamConnectable as ByteStreamConnectablefrom ._streams import Listener as Listenerfrom ._streams import ObjectReceiveStream as ObjectReceiveStreamfrom ._streams import ObjectSendStream as ObjectSendStreamfrom ._streams import ObjectStream as ObjectStreamfrom ._streams import ObjectStreamConnectable as ObjectStreamConnectablefrom ._streams import UnreliableObjectReceiveStream as UnreliableObjectReceiveStreamfrom ._streams import UnreliableObjectSendStream as UnreliableObjectSendStreamfrom ._streams import UnreliableObjectStream as UnreliableObjectStreamfrom ._subprocesses import Process as Processfrom ._tasks import TaskGroup as TaskGroupfrom ._tasks import TaskStatus as TaskStatusfrom ._testing import TestRunner as TestRunner
# Re-exported here, for backwards compatibility# isort: offfrom .._core._synchronization import ( CapacityLimiter as CapacityLimiter, Condition as Condition, Event as Event, Lock as Lock, Semaphore as Semaphore,)from .._core._tasks import CancelScope as CancelScopefrom ..from_thread import BlockingPortal as BlockingPortal
# Re-export imports so they look like they live directly in this packagefor __value in list(locals().values()): if getattr(__value, "__module__", "").startswith("anyio.abc."): __value.__module__ = __name__
del __value123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410from __future__ import annotations
import mathimport sysfrom abc import ABCMeta, abstractmethodfrom collections.abc import AsyncIterator, Awaitable, Callable, Coroutine, Sequencefrom contextlib import AbstractContextManagerfrom os import PathLikefrom signal import Signalsfrom socket import AddressFamily, SocketKind, socketfrom typing import ( IO, TYPE_CHECKING, Any, TypeAlias, TypeVar, overload,)
if sys.version_info >= (3, 11): from typing import TypeVarTuple, Unpackelse: from typing_extensions import TypeVarTuple, Unpack
if TYPE_CHECKING: from _typeshed import FileDescriptorLike
from .._core._synchronization import CapacityLimiter, Event, Lock, Semaphore from .._core._tasks import CancelScope from .._core._testing import TaskInfo from ._sockets import ( ConnectedUDPSocket, ConnectedUNIXDatagramSocket, IPSockAddrType, SocketListener, SocketStream, UDPSocket, UNIXDatagramSocket, UNIXSocketStream, ) from ._subprocesses import Process from ._tasks import TaskGroup from ._testing import TestRunner
T_Retval = TypeVar("T_Retval")T_co = TypeVar("T_co", covariant=True)PosArgsT = TypeVarTuple("PosArgsT")StrOrBytesPath: TypeAlias = str | bytes | PathLike[str] | PathLike[bytes]
class AsyncBackend(metaclass=ABCMeta): @classmethod @abstractmethod def run( cls, func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], args: tuple[Unpack[PosArgsT]], kwargs: dict[str, Any], options: dict[str, Any], ) -> T_Retval: """ Run the given coroutine function in an asynchronous event loop.
The current thread must not be already running an event loop.
:param func: a coroutine function :param args: positional arguments to ``func`` :param kwargs: positional arguments to ``func`` :param options: keyword arguments to call the backend ``run()`` implementation with :return: the return value of the coroutine function """
@classmethod @abstractmethod def current_token(cls) -> object: """ Return an object that allows other threads to run code inside the event loop.
:return: a token object, specific to the event loop running in the current thread """
@classmethod @abstractmethod def current_time(cls) -> float: """ Return the current value of the event loop's internal clock.
:return: the clock value (seconds) """
@classmethod @abstractmethod def cancelled_exception_class(cls) -> type[BaseException]: """Return the exception class that is raised in a task if it's cancelled."""
@classmethod @abstractmethod async def checkpoint(cls) -> None: """ Check if the task has been cancelled, and allow rescheduling of other tasks.
This is effectively the same as running :meth:`checkpoint_if_cancelled` and then :meth:`cancel_shielded_checkpoint`. """
@classmethod async def checkpoint_if_cancelled(cls) -> None: """ Check if the current task group has been cancelled.
This will check if the task has been cancelled, but will not allow other tasks to be scheduled if not.
""" if cls.current_effective_deadline() == -math.inf: await cls.checkpoint()
@classmethod async def cancel_shielded_checkpoint(cls) -> None: """ Allow the rescheduling of other tasks.
This will give other tasks the opportunity to run, but without checking if the current task group has been cancelled, unlike with :meth:`checkpoint`.
""" with cls.create_cancel_scope(shield=True): await cls.sleep(0)
@classmethod @abstractmethod async def sleep(cls, delay: float) -> None: """ Pause the current task for the specified duration.
:param delay: the duration, in seconds """
@classmethod @abstractmethod def create_cancel_scope( cls, *, deadline: float = math.inf, shield: bool = False ) -> CancelScope: pass
@classmethod @abstractmethod def current_effective_deadline(cls) -> float: """ Return the nearest deadline among all the cancel scopes effective for the current task.
:return: - a clock value from the event loop's internal clock - ``inf`` if there is no deadline in effect - ``-inf`` if the current scope has been cancelled :rtype: float """
@classmethod @abstractmethod def create_task_group(cls) -> TaskGroup: pass
@classmethod @abstractmethod def create_event(cls) -> Event: pass
@classmethod @abstractmethod def create_lock(cls, *, fast_acquire: bool) -> Lock: pass
@classmethod @abstractmethod def create_semaphore( cls, initial_value: int, *, max_value: int | None = None, fast_acquire: bool = False, ) -> Semaphore: pass
@classmethod @abstractmethod def create_capacity_limiter(cls, total_tokens: float) -> CapacityLimiter: pass
@classmethod @abstractmethod async def run_sync_in_worker_thread( cls, func: Callable[[Unpack[PosArgsT]], T_Retval], args: tuple[Unpack[PosArgsT]], abandon_on_cancel: bool = False, limiter: CapacityLimiter | None = None, ) -> T_Retval: pass
@classmethod @abstractmethod def check_cancelled(cls) -> None: pass
@classmethod @abstractmethod def run_async_from_thread( cls, func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]], args: tuple[Unpack[PosArgsT]], token: object, ) -> T_co: pass
@classmethod @abstractmethod def run_sync_from_thread( cls, func: Callable[[Unpack[PosArgsT]], T_Retval], args: tuple[Unpack[PosArgsT]], token: object, ) -> T_Retval: pass
@classmethod @abstractmethod async def open_process( cls, command: StrOrBytesPath | Sequence[StrOrBytesPath], *, stdin: int | IO[Any] | None, stdout: int | IO[Any] | None, stderr: int | IO[Any] | None, **kwargs: Any, ) -> Process: pass
@classmethod @abstractmethod def setup_process_pool_exit_at_shutdown(cls, workers: set[Process]) -> None: pass
@classmethod @abstractmethod async def connect_tcp( cls, host: str, port: int, local_address: IPSockAddrType | None = None ) -> SocketStream: pass
@classmethod @abstractmethod async def connect_unix(cls, path: str | bytes) -> UNIXSocketStream: pass
@classmethod @abstractmethod def create_tcp_listener(cls, sock: socket) -> SocketListener: pass
@classmethod @abstractmethod def create_unix_listener(cls, sock: socket) -> SocketListener: pass
@classmethod @abstractmethod async def create_udp_socket( cls, family: AddressFamily, local_address: IPSockAddrType | None, remote_address: IPSockAddrType | None, reuse_port: bool, ) -> UDPSocket | ConnectedUDPSocket: pass
@classmethod @overload async def create_unix_datagram_socket( cls, raw_socket: socket, remote_path: None ) -> UNIXDatagramSocket: ...
@classmethod @overload async def create_unix_datagram_socket( cls, raw_socket: socket, remote_path: str | bytes ) -> ConnectedUNIXDatagramSocket: ...
@classmethod @abstractmethod async def create_unix_datagram_socket( cls, raw_socket: socket, remote_path: str | bytes | None ) -> UNIXDatagramSocket | ConnectedUNIXDatagramSocket: pass
@classmethod @abstractmethod async def getaddrinfo( cls, host: bytes | str | None, port: str | int | None, *, family: int | AddressFamily = 0, type: int | SocketKind = 0, proto: int = 0, flags: int = 0, ) -> Sequence[ tuple[ AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], ] ]: pass
@classmethod @abstractmethod async def getnameinfo( cls, sockaddr: IPSockAddrType, flags: int = 0 ) -> tuple[str, str]: pass
@classmethod @abstractmethod async def wait_readable(cls, obj: FileDescriptorLike) -> None: pass
@classmethod @abstractmethod async def wait_writable(cls, obj: FileDescriptorLike) -> None: pass
@classmethod @abstractmethod def notify_closing(cls, obj: FileDescriptorLike) -> None: pass
@classmethod @abstractmethod async def wrap_listener_socket(cls, sock: socket) -> SocketListener: pass
@classmethod @abstractmethod async def wrap_stream_socket(cls, sock: socket) -> SocketStream: pass
@classmethod @abstractmethod async def wrap_unix_stream_socket(cls, sock: socket) -> UNIXSocketStream: pass
@classmethod @abstractmethod async def wrap_udp_socket(cls, sock: socket) -> UDPSocket: pass
@classmethod @abstractmethod async def wrap_connected_udp_socket(cls, sock: socket) -> ConnectedUDPSocket: pass
@classmethod @abstractmethod async def wrap_unix_datagram_socket(cls, sock: socket) -> UNIXDatagramSocket: pass
@classmethod @abstractmethod async def wrap_connected_unix_datagram_socket( cls, sock: socket ) -> ConnectedUNIXDatagramSocket: pass
@classmethod @abstractmethod def current_default_thread_limiter(cls) -> CapacityLimiter: pass
@classmethod @abstractmethod def open_signal_receiver( cls, *signals: Signals ) -> AbstractContextManager[AsyncIterator[Signals]]: pass
@classmethod @abstractmethod def get_current_task(cls) -> TaskInfo: pass
@classmethod @abstractmethod def get_running_tasks(cls) -> Sequence[TaskInfo]: pass
@classmethod @abstractmethod async def wait_all_tasks_blocked(cls) -> None: pass
@classmethod @abstractmethod def create_test_runner(cls, options: dict[str, Any]) -> TestRunner: pass.venv-deploy/.gitignoreAdded+2
.venv-deploy/bin/Activate.ps1Added+248
.venv-deploy/bin/activateAdded+76
.venv-deploy/bin/activate.cshAdded+27
.venv-deploy/bin/activate.fishAdded+69
.venv-deploy/bin/hfAdded+8
.venv-deploy/bin/httpxAdded+8
.venv-deploy/bin/huggingface-cliAdded+8
.venv-deploy/bin/idnaAdded+8
.venv-deploy/bin/pipAdded+8
.venv-deploy/bin/pip3Added+8
.venv-deploy/bin/pip3.14Added+8
.venv-deploy/bin/pythonAdded
.venv-deploy/bin/python3Added
.venv-deploy/bin/python3.14Added
.venv-deploy/bin/tiny-agentsAdded+8
.venv-deploy/bin/tqdmAdded+8
.venv-deploy/bin/𝜋thonAdded
.venv-deploy/lib/python3.14/site-packages/_yaml/__init__.pyAdded+33
.venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/INSTALLERAdded+1
.venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/METADATAAdded+107
.venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/RECORDAdded+96
.venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/WHEELAdded+5
.venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/entry_points.txtAdded+2
.venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/licenses/LICENSEAdded+20
.venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/scm_file_list.jsonAdded+119
.venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/scm_version.jsonAdded+8
.venv-deploy/lib/python3.14/site-packages/anyio-4.14.2.dist-info/top_level.txtAdded+1
.venv-deploy/lib/python3.14/site-packages/anyio/__init__.pyAdded+115
.venv-deploy/lib/python3.14/site-packages/anyio/_backends/__init__.pyAdded
.venv-deploy/lib/python3.14/site-packages/anyio/_backends/_asyncio.pyAdded
.venv-deploy/lib/python3.14/site-packages/anyio/_backends/_trio.pyAdded+1468
.venv-deploy/lib/python3.14/site-packages/anyio/_core/__init__.pyAdded
.venv-deploy/lib/python3.14/site-packages/anyio/_core/_asyncio_selector_thread.pyAdded+167
.venv-deploy/lib/python3.14/site-packages/anyio/_core/_contextmanagers.pyAdded+200
.venv-deploy/lib/python3.14/site-packages/anyio/_core/_eventloop.pyAdded+240
.venv-deploy/lib/python3.14/site-packages/anyio/_core/_exceptions.pyAdded+177
.venv-deploy/lib/python3.14/site-packages/anyio/_core/_fileio.pyAdded+960
.venv-deploy/lib/python3.14/site-packages/anyio/_core/_resources.pyAdded+18
.venv-deploy/lib/python3.14/site-packages/anyio/_core/_signals.pyAdded+29
.venv-deploy/lib/python3.14/site-packages/anyio/_core/_sockets.pyAdded+1011
.venv-deploy/lib/python3.14/site-packages/anyio/_core/_streams.pyAdded+52
.venv-deploy/lib/python3.14/site-packages/anyio/_core/_subprocesses.pyAdded+196
.venv-deploy/lib/python3.14/site-packages/anyio/_core/_synchronization.pyAdded+772
.venv-deploy/lib/python3.14/site-packages/anyio/_core/_tasks.pyAdded+412
.venv-deploy/lib/python3.14/site-packages/anyio/_core/_tempfile.pyAdded+613
.venv-deploy/lib/python3.14/site-packages/anyio/_core/_testing.pyAdded+82
.venv-deploy/lib/python3.14/site-packages/anyio/_core/_typedattr.pyAdded+81
.venv-deploy/lib/python3.14/site-packages/anyio/abc/__init__.pyAdded+58
.venv-deploy/lib/python3.14/site-packages/anyio/abc/_eventloop.pyAdded+410