Spaces:
Sleeping
Sleeping
Bell Operations Copilot: copilot route, reservations, tokens, webhook parser, menu availability
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .envAdded+13
- .env.exampleAdded+15
- .gitattributes+22
- .venv/bin/Activate.ps1Added+247
- .venv/bin/activateAdded+70
- .venv/bin/activate.cshAdded+27
- .venv/bin/activate.fishAdded+69
- .venv/bin/dotenvAdded+8
- .venv/bin/fastapiAdded+8
- .venv/bin/hfAdded+8
- .venv/bin/httpxAdded+8
- .venv/bin/huggingface-cliAdded+8
- .venv/bin/idnaAdded+8
- .venv/bin/markdown-itAdded+8
- .venv/bin/pipAdded+8
- .venv/bin/pip3Added+8
- .venv/bin/pip3.12Added+8
- .venv/bin/pygmentizeAdded+8
- .venv/bin/pythonAdded+3
- .venv/bin/python3Added+3
- .venv/bin/python3.12Added+3
- .venv/bin/tiny-agentsAdded+8
- .venv/bin/tqdmAdded+8
- .venv/bin/typerAdded+8
- .venv/bin/uvicornAdded+8
- .venv/bin/watchfilesAdded+8
- .venv/bin/websocketsAdded+8
- .venv/lib/python3.12/site-packages/StrEnum-0.4.15.dist-info/INSTALLERAdded+1
- .venv/lib/python3.12/site-packages/StrEnum-0.4.15.dist-info/LICENSEAdded+21
- .venv/lib/python3.12/site-packages/StrEnum-0.4.15.dist-info/METADATAAdded+211
- .venv/lib/python3.12/site-packages/StrEnum-0.4.15.dist-info/RECORDAdded+18
- .venv/lib/python3.12/site-packages/StrEnum-0.4.15.dist-info/WHEELAdded+5
- .venv/lib/python3.12/site-packages/StrEnum-0.4.15.dist-info/top_level.txtAdded+1
- .venv/lib/python3.12/site-packages/_cffi_backend.cpython-312-x86_64-linux-gnu.soAdded+3
- .venv/lib/python3.12/site-packages/_yaml/__init__.pyAdded+33
- .venv/lib/python3.12/site-packages/annotated_doc-0.0.4.dist-info/INSTALLERAdded+1
- .venv/lib/python3.12/site-packages/annotated_doc-0.0.4.dist-info/METADATAAdded+145
- .venv/lib/python3.12/site-packages/annotated_doc-0.0.4.dist-info/RECORDAdded+11
- .venv/lib/python3.12/site-packages/annotated_doc-0.0.4.dist-info/WHEELAdded+4
- .venv/lib/python3.12/site-packages/annotated_doc-0.0.4.dist-info/entry_points.txtAdded+4
- .venv/lib/python3.12/site-packages/annotated_doc-0.0.4.dist-info/licenses/LICENSEAdded+21
- .venv/lib/python3.12/site-packages/annotated_doc/__init__.pyAdded+3
- .venv/lib/python3.12/site-packages/annotated_doc/main.pyAdded+36
- .venv/lib/python3.12/site-packages/annotated_doc/py.typedAdded
- .venv/lib/python3.12/site-packages/annotated_types-0.7.0.dist-info/INSTALLERAdded+1
- .venv/lib/python3.12/site-packages/annotated_types-0.7.0.dist-info/METADATAAdded+295
- .venv/lib/python3.12/site-packages/annotated_types-0.7.0.dist-info/RECORDAdded+10
- .venv/lib/python3.12/site-packages/annotated_types-0.7.0.dist-info/WHEELAdded+4
- .venv/lib/python3.12/site-packages/annotated_types-0.7.0.dist-info/licenses/LICENSEAdded+21
- .venv/lib/python3.12/site-packages/annotated_types/__init__.pyAdded+432
12345678910111213# Supabase (not configured yet — backend runs in memory mode)SUPABASE_URL=SUPABASE_SERVICE_KEY=
# Bolna — test key (user will revoke later)BOLNA_API_KEY=bn-89beb3e956e84ab7b8ce40af3ec0d9caBOLNA_AGENT_ID=d17fd45b-e743-488a-99c5-4653af6ca04fBOLNA_WS_HOST=wss://ws.bolna.dev
# Auth disabled for local testingBACKEND_API_TOKEN=
CORS_ORIGINS=http://localhost:3000123456789101112131415# --- Supabase (optional locally — without it the backend runs in memory mode) ---SUPABASE_URL=SUPABASE_SERVICE_KEY=
# --- Bolna ---BOLNA_API_KEY= # platform.bolna.ai → API keysBOLNA_AGENT_ID= # your Bell agent idBOLNA_WS_HOST= # web-call websocket host, e.g. wss://ws.bolna.ai (ask Bolna team)# BOLNA_API_HOST=https://api.bolna.ai
# --- Security ---BACKEND_API_TOKEN= # Bearer token Bolna tools send; empty disables auth (dev only)
# --- CORS (comma separated) ---CORS_ORIGINS=http://localhost:300032 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353637383940414243444546474849505152535455565732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text.venv/bin/python filter=lfs diff=lfs merge=lfs -text.venv/bin/python3 filter=lfs diff=lfs merge=lfs -text.venv/bin/python3.12 filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/_cffi_backend.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust.abi3.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/hf_xet/hf_xet.abi3.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/httptools/parser/parser.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/httptools/parser/url_parser.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/multidict/_multidict.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/propcache/_helpers_c.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pydantic_core/_pydantic_core.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/rapidfuzz/distance/_initialize_cpp.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/rapidfuzz/distance/metrics_cpp.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/rapidfuzz/distance/metrics_cpp_avx2.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/rapidfuzz/fuzz_cpp.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/rapidfuzz/fuzz_cpp_avx2.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/rapidfuzz/process_cpp_impl.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/rapidfuzz/utils_cpp.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/uvloop/loop.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/watchfiles/_rust_notify.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/yaml/_yaml.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/yarl/_quoting_c.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247<#
.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
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
}
$env:VIRTUAL_ENV_PROMPT = $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"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970# 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 commands. Without forgetting # past commands the $PATH changes we made may not be respected 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:if [ "${OSTYPE:-}" = "cygwin" ] || [ "${OSTYPE:-}" = "msys" ] ; then # transform D:\path\to\venv to /d/path/to/venv on MSYS # and to /cygdrive/d/path/to/venv on Cygwin export VIRTUAL_ENV=$(cygpath /home/charan/Documents/bell/backend/.venv)else # use the path as-is export VIRTUAL_ENV=/home/charan/Documents/bell/backend/.venvfi
_OLD_VIRTUAL_PATH="$PATH"PATH="$VIRTUAL_ENV/"bin":$PATH"export PATH
# 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) '"${PS1:-}" export PS1 VIRTUAL_ENV_PROMPT='(.venv) ' export VIRTUAL_ENV_PROMPTfi
# 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 /home/charan/Documents/bell/backend/.venv
set _OLD_VIRTUAL_PATH="$PATH"setenv PATH "$VIRTUAL_ENV/"bin":$PATH"
set _OLD_VIRTUAL_PROMPT="$prompt"
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then set prompt = '(.venv) '"$prompt" setenv VIRTUAL_ENV_PROMPT '(.venv) '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 /home/charan/Documents/bell/backend/.venv
set -gx _OLD_VIRTUAL_PATH $PATHset -gx PATH "$VIRTUAL_ENV/"bin $PATH
# 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) ' (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" set -gx VIRTUAL_ENV_PROMPT '(.venv) 'end12345678#!/home/charan/Documents/bell/backend/.venv/bin/python3# -*- coding: utf-8 -*-import reimport sysfrom dotenv.__main__ import cliif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(cli())12345678#!/home/charan/Documents/bell/backend/.venv/bin/python3# -*- coding: utf-8 -*-import reimport sysfrom fastapi.cli import mainif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())12345678#!/home/charan/Documents/bell/backend/.venv/bin/python3# -*- coding: utf-8 -*-import reimport sysfrom huggingface_hub.cli.hf import mainif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())12345678#!/home/charan/Documents/bell/backend/.venv/bin/python3# -*- coding: utf-8 -*-import reimport sysfrom httpx import mainif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())12345678#!/home/charan/Documents/bell/backend/.venv/bin/python3# -*- coding: utf-8 -*-import reimport sysfrom huggingface_hub.cli.deprecated_cli import mainif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())12345678#!/home/charan/Documents/bell/backend/.venv/bin/python3# -*- coding: utf-8 -*-import reimport sysfrom idna.cli import mainif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())12345678#!/home/charan/Documents/bell/backend/.venv/bin/python3# -*- coding: utf-8 -*-import reimport sysfrom markdown_it.cli.parse import mainif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())12345678#!/home/charan/Documents/bell/backend/.venv/bin/python3# -*- coding: utf-8 -*-import reimport sysfrom pip._internal.cli.main import mainif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())12345678#!/home/charan/Documents/bell/backend/.venv/bin/python3# -*- coding: utf-8 -*-import reimport sysfrom pip._internal.cli.main import mainif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())12345678#!/home/charan/Documents/bell/backend/.venv/bin/python3# -*- coding: utf-8 -*-import reimport sysfrom pip._internal.cli.main import mainif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())12345678#!/home/charan/Documents/bell/backend/.venv/bin/python3# -*- coding: utf-8 -*-import reimport sysfrom pygments.cmdline import mainif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())123version https://git-lfs.github.com/spec/v1oid sha256:e1efa562c2cc2e35521a5c9c9b9939921001ff8ca9708a13ef15ace68cc2ccd7size 8020928123version https://git-lfs.github.com/spec/v1oid sha256:e1efa562c2cc2e35521a5c9c9b9939921001ff8ca9708a13ef15ace68cc2ccd7size 8020928123version https://git-lfs.github.com/spec/v1oid sha256:e1efa562c2cc2e35521a5c9c9b9939921001ff8ca9708a13ef15ace68cc2ccd7size 802092812345678#!/home/charan/Documents/bell/backend/.venv/bin/python3# -*- coding: utf-8 -*-import reimport sysfrom huggingface_hub.inference._mcp.cli import appif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(app())12345678#!/home/charan/Documents/bell/backend/.venv/bin/python3# -*- coding: utf-8 -*-import reimport sysfrom tqdm.cli import mainif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())12345678#!/home/charan/Documents/bell/backend/.venv/bin/python3# -*- coding: utf-8 -*-import reimport sysfrom typer.cli import mainif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())12345678#!/home/charan/Documents/bell/backend/.venv/bin/python3# -*- coding: utf-8 -*-import reimport sysfrom uvicorn.main import mainif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())12345678#!/home/charan/Documents/bell/backend/.venv/bin/python3# -*- coding: utf-8 -*-import reimport sysfrom watchfiles.cli import cliif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(cli())12345678#!/home/charan/Documents/bell/backend/.venv/bin/python3# -*- coding: utf-8 -*-import reimport sysfrom websockets.cli import mainif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())1pip123456789101112131415161718192021MIT License
Copyright (c) 2019 James C Sinclair
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished 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,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211Metadata-Version: 2.1Name: StrEnumVersion: 0.4.15Summary: An Enum that inherits from str.Home-page: https://github.com/irgeek/StrEnumAuthor: James SinclairAuthor-email: james@nurfherder.comClassifier: Development Status :: 5 - Production/StableClassifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.7Classifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: License :: OSI Approved :: MIT LicenseClassifier: Operating System :: OS IndependentDescription-Content-Type: text/markdownLicense-File: LICENSEProvides-Extra: docsRequires-Dist: sphinx ; extra == 'docs'Requires-Dist: sphinx-rtd-theme ; extra == 'docs'Requires-Dist: myst-parser[linkify] ; extra == 'docs'Provides-Extra: releaseRequires-Dist: twine ; extra == 'release'Provides-Extra: testRequires-Dist: pytest ; extra == 'test'Requires-Dist: pytest-black ; extra == 'test'Requires-Dist: pytest-cov ; extra == 'test'Requires-Dist: pytest-pylint ; extra == 'test'Requires-Dist: pylint ; extra == 'test'
# StrEnum
[](https://github.com/irgeek/StrEnum/actions)
StrEnum is a Python `enum.Enum` that inherits from `str` to complement`enum.IntEnum` in the standard library. Supports python 3.7+.
## Installation
You can use [pip](https://pip.pypa.io/en/stable/) to install.
```bashpip install StrEnum```
## Usage
```pythonfrom enum import autofrom strenum import StrEnum
class HttpMethod(StrEnum): GET = auto() HEAD = auto() POST = auto() PUT = auto() DELETE = auto() CONNECT = auto() OPTIONS = auto() TRACE = auto() PATCH = auto()
assert HttpMethod.GET == "GET"
# You can use StrEnum values just like strings:
import urllib.request
req = urllib.request.Request('https://www.python.org/', method=HttpMethod.HEAD)with urllib.request.urlopen(req) as response: html = response.read()
assert len(html) == 0 # HEAD requests do not (usually) include a body```
There are classes whose `auto()` value folds each member name to upper or lowercase:
```pythonfrom enum import autofrom strenum import LowercaseStrEnum, UppercaseStrEnum
class Tag(LowercaseStrEnum): Head = auto() Body = auto() Div = auto()
assert Tag.Head == "head"assert Tag.Body == "body"assert Tag.Div == "div"
class HttpMethod(UppercaseStrEnum): Get = auto() Head = auto() Post = auto()
assert HttpMethod.Get == "GET"assert HttpMethod.Head == "HEAD"assert HttpMethod.Post == "POST"```
As well as classes whose `auto()` value converts each member name to camelCase,PascalCase, kebab-case, snake_case and MACRO_CASE:
```pythonfrom enum import autofrom strenum import CamelCaseStrEnum, PascalCaseStrEnumfrom strenum import KebabCaseStrEnum, SnakeCaseStrEnumfrom strenum import MacroCaseStrEnum
class CamelTestEnum(CamelCaseStrEnum): OneTwoThree = auto()
class PascalTestEnum(PascalCaseStrEnum): OneTwoThree = auto()
class KebabTestEnum(KebabCaseStrEnum): OneTwoThree = auto()
class SnakeTestEnum(SnakeCaseStrEnum): OneTwoThree = auto()
class MacroTestEnum(MacroCaseStrEnum): OneTwoThree = auto()
assert CamelTestEnum.OneTwoThree == "oneTwoThree"assert PascalTestEnum.OneTwoThree == "OneTwoThree"assert KebabTestEnum.OneTwoThree == "one-two-three"assert SnakeTestEnum.OneTwoThree == "one_two_three"assert MacroTestEnum.OneTwoThree == "ONE_TWO_THREE"```
As with any Enum you can, of course, manually assign values.
```pythonfrom strenum import StrEnum
class Shape(StrEnum): CIRCLE = "Circle"
assert Shape.CIRCLE == "Circle"```
Doing this with the case-changing classes, though, won't manipulatevalues--whatever you assign is the value they end up with.
```pythonfrom strenum import KebabCaseStrEnum
class Shape(KebabCaseStrEnum): CIRCLE = "Circle"
# This will raise an AssertionError because the value wasn't converted to kebab-case.assert Shape.CIRCLE == "circle"```
## Contributing
Pull requests are welcome. For major changes, please open an issue first todiscuss what you would like to change.
Please ensure tests pass before submitting a PR. This repository uses[Black](https://black.readthedocs.io/en/stable/) and[Pylint](https://www.pylint.org/) for consistency. Both are run automaticallyas part of the test suite.
## Running the tests
Tests can be run using `make`:
```make test```
This will create a virutal environment, install the module and its testdependencies and run the tests. Alternatively you can do the same thingmanually:
```python3 -m venv .venv.venv/bin/pip install .[test].venv/bin/pytest```
## License
[MIT](https://choosealicense.com/licenses/mit/)
**N.B. Starting with Python 3.11, `enum.StrEnum` is available in the standardlibrary. This implementation is _not_ a drop-in replacement for the standardlibrary implementation. Specifically, the Python devs have decided to case foldname to lowercase by default when `auto()` is used which I think violates theprinciple of least surprise.**123456789101112131415161718StrEnum-0.4.15.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
StrEnum-0.4.15.dist-info/LICENSE,sha256=vNcz0KRlIhYrldurYffNwcPjaGHfoSfWikQ1JA02rTY,1073
StrEnum-0.4.15.dist-info/METADATA,sha256=xLhPNsn2ieV9BR8L-FvFTMMhG6x99Rj536PM2hf1KII,5290
StrEnum-0.4.15.dist-info/RECORD,,
StrEnum-0.4.15.dist-info/WHEEL,sha256=pkctZYzUS4AYVn6dJ-7367OJZivF2e8RA9b_ZBjif18,92
StrEnum-0.4.15.dist-info/top_level.txt,sha256=lsVIlgvvAAG9MBoLNwpPgG5wMT33blIUUoJo215Y-N0,8
strenum/__init__.py,sha256=oOsokqYYQVwTBbjrnXdR89RMcx8q6aGmWl--dlf2VCE,8530
strenum/__init__.pyi,sha256=-qJs9THlVGY3_o_bVeE7jUevjWteU_zOy7cZkp3MGzA,1415
strenum/__pycache__/__init__.cpython-312.pyc,,
strenum/__pycache__/_name_mangler.cpython-312.pyc,,
strenum/__pycache__/_version.cpython-312.pyc,,
strenum/__pycache__/mixins.cpython-312.pyc,,
strenum/_name_mangler.py,sha256=o11M5-bURW2RBvRTYXFQIPNeqLzburdoWLIqk8X3ydw,3397
strenum/_name_mangler.pyi,sha256=91p30d_kMAFsX5r9pqvSeordIf4VONDymQhcEvot2XA,551
strenum/_version.py,sha256=ylMBlzCLrUBhNvBnKtzTqGzDqHnEmoQkm3K6p5Gx5ms,498
strenum/mixins.py,sha256=BtOEx1hrAZ1YhDURDjLTrunKVneVtezSfkBq3sZXqxE,2042
strenum/mixins.pyi,sha256=lV6wiQAxZMvMSUUtnxzV1QSsyBDzgpobywiGCwRwm30,387
strenum/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,012345Wheel-Version: 1.0Generator: bdist_wheel (0.40.0)Root-Is-Purelib: trueTag: py3-none-any
1strenum123version https://git-lfs.github.com/spec/v1oid sha256:0062edc397e7f6ee029b093705b1a5b171bb55912f41e90004cc841ae45999c1size 348808123456789101112131415161718192021222324252627282930313233# 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__ = ''1pip123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145Metadata-Version: 2.4Name: annotated-docVersion: 0.0.4Summary: Document parameters, class attributes, return types, and variables inline, with Annotated.Author-Email: =?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?= <tiangolo@gmail.com>License-Expression: MITLicense-File: LICENSEClassifier: Intended Audience :: Information TechnologyClassifier: Intended Audience :: System AdministratorsClassifier: Operating System :: OS IndependentClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: PythonClassifier: Topic :: InternetClassifier: Topic :: Software Development :: Libraries :: Application FrameworksClassifier: Topic :: Software Development :: Libraries :: Python ModulesClassifier: Topic :: Software Development :: LibrariesClassifier: Topic :: Software DevelopmentClassifier: Typing :: TypedClassifier: Development Status :: 4 - BetaClassifier: Intended Audience :: DevelopersClassifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Project-URL: Homepage, https://github.com/fastapi/annotated-docProject-URL: Documentation, https://github.com/fastapi/annotated-docProject-URL: Repository, https://github.com/fastapi/annotated-docProject-URL: Issues, https://github.com/fastapi/annotated-doc/issuesProject-URL: Changelog, https://github.com/fastapi/annotated-doc/release-notes.mdRequires-Python: >=3.8Description-Content-Type: text/markdown
# Annotated Doc
Document parameters, class attributes, return types, and variables inline, with `Annotated`.
<a href="https://github.com/fastapi/annotated-doc/actions?query=workflow%3ATest+event%3Apush+branch%3Amain" target="_blank"> <img src="https://github.com/fastapi/annotated-doc/actions/workflows/test.yml/badge.svg?event=push&branch=main" alt="Test"></a><a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/annotated-doc" target="_blank"> <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/annotated-doc.svg" alt="Coverage"></a><a href="https://pypi.org/project/annotated-doc" target="_blank"> <img src="https://img.shields.io/pypi/v/annotated-doc?color=%2334D058&label=pypi%20package" alt="Package version"></a><a href="https://pypi.org/project/annotated-doc" target="_blank"> <img src="https://img.shields.io/pypi/pyversions/annotated-doc.svg?color=%2334D058" alt="Supported Python versions"></a>
## Installation
```bashpip install annotated-doc```
Or with `uv`:
```Pythonuv add annotated-doc```
## Usage
Import `Doc` and pass a single literal string with the documentation for the specific parameter, class attribute, return type, or variable.
For example, to document a parameter `name` in a function `hi` you could do:
```Pythonfrom typing import Annotated
from annotated_doc import Doc
def hi(name: Annotated[str, Doc("Who to say hi to")]) -> None: print(f"Hi, {name}!")```
You can also use it to document class attributes:
```Pythonfrom typing import Annotated
from annotated_doc import Doc
class User: name: Annotated[str, Doc("The user's name")] age: Annotated[int, Doc("The user's age")]```
The same way, you could document return types and variables, or anything that could have a type annotation with `Annotated`.
## Who Uses This
`annotated-doc` was made for:
* [FastAPI](https://fastapi.tiangolo.com/)* [Typer](https://typer.tiangolo.com/)* [SQLModel](https://sqlmodel.tiangolo.com/)* [Asyncer](https://asyncer.tiangolo.com/)
`annotated-doc` is supported by [griffe-typingdoc](https://github.com/mkdocstrings/griffe-typingdoc), which powers reference documentation like the one in the [FastAPI Reference](https://fastapi.tiangolo.com/reference/).
## Reasons not to use `annotated-doc`
You are already comfortable with one of the existing docstring formats, like:
* Sphinx* numpydoc* Google* Keras
Your team is already comfortable using them.
You prefer having the documentation about parameters all together in a docstring, separated from the code defining them.
You care about a specific set of users, using one specific editor, and that editor already has support for the specific docstring format you use.
## Reasons to use `annotated-doc`
* No micro-syntax to learn for newcomers, it’s **just Python** syntax.* **Editing** would be already fully supported by default by any editor (current or future) supporting Python syntax, including syntax errors, syntax highlighting, etc.* **Rendering** would be relatively straightforward to implement by static tools (tools that don't need runtime execution), as the information can be extracted from the AST they normally already create.* **Deduplication of information**: the name of a parameter would be defined in a single place, not duplicated inside of a docstring.* **Elimination** of the possibility of having **inconsistencies** when removing a parameter or class variable and **forgetting to remove** its documentation.* **Minimization** of the probability of adding a new parameter or class variable and **forgetting to add its documentation**.* **Elimination** of the possibility of having **inconsistencies** between the **name** of a parameter in the **signature** and the name in the docstring when it is renamed.* **Access** to the documentation string for each symbol at **runtime**, including existing (older) Python versions.* A more formalized way to document other symbols, like type aliases, that could use Annotated.* **Support** for apps using FastAPI, Typer and others.* **AI Accessibility**: AI tools will have an easier way understanding each parameter as the distance from documentation to parameter is much closer.
## History
I ([@tiangolo](https://github.com/tiangolo)) originally wanted for this to be part of the Python standard library (in [PEP 727](https://peps.python.org/pep-0727/)), but the proposal was withdrawn as there was a fair amount of negative feedback and opposition.
The conclusion was that this was better done as an external effort, in a third-party library.
So, here it is, with a simpler approach, as a third-party library, in a way that can be used by others, starting with FastAPI and friends.
## License
This project is licensed under the terms of the MIT license.1234567891011annotated_doc-0.0.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
annotated_doc-0.0.4.dist-info/METADATA,sha256=Irm5KJua33dY2qKKAjJ-OhKaVBVIfwFGej_dSe3Z1TU,6566
annotated_doc-0.0.4.dist-info/RECORD,,
annotated_doc-0.0.4.dist-info/WHEEL,sha256=9P2ygRxDrTJz3gsagc0Z96ukrxjr-LFBGOgv3AuKlCA,90
annotated_doc-0.0.4.dist-info/entry_points.txt,sha256=6OYgBcLyFCUgeqLgnvMyOJxPCWzgy7se4rLPKtNonMs,34
annotated_doc-0.0.4.dist-info/licenses/LICENSE,sha256=__Fwd5pqy_ZavbQFwIfxzuF4ZpHkqWpANFF-SlBKDN8,1086
annotated_doc/__init__.py,sha256=VuyxxUe80kfEyWnOrCx_Bk8hybo3aKo6RYBlkBBYW8k,52
annotated_doc/__pycache__/__init__.cpython-312.pyc,,
annotated_doc/__pycache__/main.cpython-312.pyc,,
annotated_doc/main.py,sha256=5Zfvxv80SwwLqpRW73AZyZyiM4bWma9QWRbp_cgD20s,1075
annotated_doc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,01234Wheel-Version: 1.0Generator: pdm-backend (2.4.5)Root-Is-Purelib: trueTag: py3-none-any1234[console_scripts]
[gui_scripts]
123456789101112131415161718192021The MIT License (MIT)
Copyright (c) 2025 Sebastián Ramírez
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included inall copies 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,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.123from .main import Doc as Doc
__version__ = "0.0.4"123456789101112131415161718192021222324252627282930313233343536class Doc: """Define the documentation of a type annotation using `Annotated`, to be used in class attributes, function and method parameters, return values, and variables.
The value should be a positional-only string literal to allow static tools like editors and documentation generators to use it.
This complements docstrings.
The string value passed is available in the attribute `documentation`.
Example:
```Python from typing import Annotated from annotated_doc import Doc
def hi(name: Annotated[str, Doc("Who to say hi to")]) -> None: print(f"Hi, {name}!") ``` """
def __init__(self, documentation: str, /) -> None: self.documentation = documentation
def __repr__(self) -> str: return f"Doc({self.documentation!r})"
def __hash__(self) -> int: return hash(self.documentation)
def __eq__(self, other: object) -> bool: if not isinstance(other, Doc): return NotImplemented return self.documentation == other.documentation1pip123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295Metadata-Version: 2.3Name: annotated-typesVersion: 0.7.0Summary: Reusable constraint types to use with typing.AnnotatedProject-URL: Homepage, https://github.com/annotated-types/annotated-typesProject-URL: Source, https://github.com/annotated-types/annotated-typesProject-URL: Changelog, https://github.com/annotated-types/annotated-types/releasesAuthor-email: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>, Samuel Colvin <s@muelcolvin.com>, Zac Hatfield-Dodds <zac@zhd.dev>License-File: LICENSEClassifier: Development Status :: 4 - BetaClassifier: Environment :: ConsoleClassifier: Environment :: MacOS XClassifier: Intended Audience :: DevelopersClassifier: Intended Audience :: Information TechnologyClassifier: License :: OSI Approved :: MIT LicenseClassifier: Operating System :: POSIX :: LinuxClassifier: Operating System :: UnixClassifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Topic :: Software Development :: Libraries :: Python ModulesClassifier: Typing :: TypedRequires-Python: >=3.8Requires-Dist: typing-extensions>=4.0.0; python_version < '3.9'Description-Content-Type: text/markdown
# annotated-types
[](https://github.com/annotated-types/annotated-types/actions?query=event%3Apush+branch%3Amain+workflow%3ACI)[](https://pypi.python.org/pypi/annotated-types)[](https://github.com/annotated-types/annotated-types)[](https://github.com/annotated-types/annotated-types/blob/main/LICENSE)
[PEP-593](https://peps.python.org/pep-0593/) added `typing.Annotated` as a way ofadding context-specific metadata to existing types, and specifies that`Annotated[T, x]` _should_ be treated as `T` by any tool or library without speciallogic for `x`.
This package provides metadata objects which can be used to represent commonconstraints such as upper and lower bounds on scalar values and collection sizes,a `Predicate` marker for runtime checks, anddescriptions of how we intend these metadata to be interpreted. In some cases,we also note alternative representations which do not require this package.
## Install
```bashpip install annotated-types```
## Examples
```pythonfrom typing import Annotatedfrom annotated_types import Gt, Len, Predicate
class MyClass: age: Annotated[int, Gt(18)] # Valid: 19, 20, ... # Invalid: 17, 18, "19", 19.0, ... factors: list[Annotated[int, Predicate(is_prime)]] # Valid: 2, 3, 5, 7, 11, ... # Invalid: 4, 8, -2, 5.0, "prime", ...
my_list: Annotated[list[int], Len(0, 10)] # Valid: [], [10, 20, 30, 40, 50] # Invalid: (1, 2), ["abc"], [0] * 20```
## Documentation
_While `annotated-types` avoids runtime checks for performance, users should notconstruct invalid combinations such as `MultipleOf("non-numeric")` or `Annotated[int, Len(3)]`.Downstream implementors may choose to raise an error, emit a warning, silently ignorea metadata item, etc., if the metadata objects described below are used with anincompatible type - or for any other reason!_
### Gt, Ge, Lt, Le
Express inclusive and/or exclusive bounds on orderable values - which may be numbers,dates, times, strings, sets, etc. Note that the boundary value need not be of thesame type that was annotated, so long as they can be compared: `Annotated[int, Gt(1.5)]`is fine, for example, and implies that the value is an integer x such that `x > 1.5`.
We suggest that implementors may also interpret `functools.partial(operator.le, 1.5)`as being equivalent to `Gt(1.5)`, for users who wish to avoid a runtime dependency onthe `annotated-types` package.
To be explicit, these types have the following meanings:
* `Gt(x)` - value must be "Greater Than" `x` - equivalent to exclusive minimum* `Ge(x)` - value must be "Greater than or Equal" to `x` - equivalent to inclusive minimum* `Lt(x)` - value must be "Less Than" `x` - equivalent to exclusive maximum* `Le(x)` - value must be "Less than or Equal" to `x` - equivalent to inclusive maximum
### Interval
`Interval(gt, ge, lt, le)` allows you to specify an upper and lower bound with a singlemetadata object. `None` attributes should be ignored, and non-`None` attributestreated as per the single bounds above.
### MultipleOf
`MultipleOf(multiple_of=x)` might be interpreted in two ways:
1. Python semantics, implying `value % multiple_of == 0`, or2. [JSONschema semantics](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.2.1), where `int(value / multiple_of) == value / multiple_of`.
We encourage users to be aware of these two common interpretations and theirdistinct behaviours, especially since very large or non-integer numbers makeit easy to cause silent data corruption due to floating-point imprecision.
We encourage libraries to carefully document which interpretation they implement.
### MinLen, MaxLen, Len
`Len()` implies that `min_length <= len(value) <= max_length` - lower and upper bounds are inclusive.
As well as `Len()` which can optionally include upper and lower bounds, we alsoprovide `MinLen(x)` and `MaxLen(y)` which are equivalent to `Len(min_length=x)`and `Len(max_length=y)` respectively.
`Len`, `MinLen`, and `MaxLen` may be used with any type which supports `len(value)`.
Examples of usage:
* `Annotated[list, MaxLen(10)]` (or `Annotated[list, Len(max_length=10))`) - list must have a length of 10 or less* `Annotated[str, MaxLen(10)]` - string must have a length of 10 or less* `Annotated[list, MinLen(3))` (or `Annotated[list, Len(min_length=3))`) - list must have a length of 3 or more* `Annotated[list, Len(4, 6)]` - list must have a length of 4, 5, or 6* `Annotated[list, Len(8, 8)]` - list must have a length of exactly 8
#### Changed in v0.4.0
* `min_inclusive` has been renamed to `min_length`, no change in meaning* `max_exclusive` has been renamed to `max_length`, upper bound is now **inclusive** instead of **exclusive*** The recommendation that slices are interpreted as `Len` has been removed due to ambiguity and different semantic meaning of the upper bound in slices vs. `Len`
See [issue #23](https://github.com/annotated-types/annotated-types/issues/23) for discussion.
### Timezone
`Timezone` can be used with a `datetime` or a `time` to express which timezonesare allowed. `Annotated[datetime, Timezone(None)]` must be a naive datetime.`Timezone[...]` ([literal ellipsis](https://docs.python.org/3/library/constants.html#Ellipsis))expresses that any timezone-aware datetime is allowed. You may also pass a specifictimezone string or [`tzinfo`](https://docs.python.org/3/library/datetime.html#tzinfo-objects)object such as `Timezone(timezone.utc)` or `Timezone("Africa/Abidjan")` to express that you onlyallow a specific timezone, though we note that this is often a symptom of fragile design.
#### Changed in v0.x.x
* `Timezone` accepts [`tzinfo`](https://docs.python.org/3/library/datetime.html#tzinfo-objects) objects instead of `timezone`, extending compatibility to [`zoneinfo`](https://docs.python.org/3/library/zoneinfo.html) and third party libraries.
### Unit
`Unit(unit: str)` expresses that the annotated numeric value is the magnitude ofa quantity with the specified unit. For example, `Annotated[float, Unit("m/s")]`would be a float representing a velocity in meters per second.
Please note that `annotated_types` itself makes no attempt to parse or validatethe unit string in any way. That is left entirely to downstream libraries,such as [`pint`](https://pint.readthedocs.io) or[`astropy.units`](https://docs.astropy.org/en/stable/units/).
An example of how a library might use this metadata:
```pythonfrom annotated_types import Unitfrom typing import Annotated, TypeVar, Callable, Any, get_origin, get_args
# given a type annotated with a unit:Meters = Annotated[float, Unit("m")]
# you can cast the annotation to a specific unit type with any# callable that accepts a string and returns the desired typeT = TypeVar("T")def cast_unit(tp: Any, unit_cls: Callable[[str], T]) -> T | None: if get_origin(tp) is Annotated: for arg in get_args(tp): if isinstance(arg, Unit): return unit_cls(arg.unit) return None
# using `pint`import pintpint_unit = cast_unit(Meters, pint.Unit)
# using `astropy.units`import astropy.units as uastropy_unit = cast_unit(Meters, u.Unit)```
### Predicate
`Predicate(func: Callable)` expresses that `func(value)` is truthy for valid values.Users should prefer the statically inspectable metadata above, but if you needthe full power and flexibility of arbitrary runtime predicates... here it is.
For some common constraints, we provide generic types:
* `IsLower = Annotated[T, Predicate(str.islower)]`* `IsUpper = Annotated[T, Predicate(str.isupper)]`* `IsDigit = Annotated[T, Predicate(str.isdigit)]`* `IsFinite = Annotated[T, Predicate(math.isfinite)]`* `IsNotFinite = Annotated[T, Predicate(Not(math.isfinite))]`* `IsNan = Annotated[T, Predicate(math.isnan)]`* `IsNotNan = Annotated[T, Predicate(Not(math.isnan))]`* `IsInfinite = Annotated[T, Predicate(math.isinf)]`* `IsNotInfinite = Annotated[T, Predicate(Not(math.isinf))]`
so that you can write e.g. `x: IsFinite[float] = 2.0` instead of the longer(but exactly equivalent) `x: Annotated[float, Predicate(math.isfinite)] = 2.0`.
Some libraries might have special logic to handle known or understandable predicates,for example by checking for `str.isdigit` and using its presence to both call customlogic to enforce digit-only strings, and customise some generated external schema.Users are therefore encouraged to avoid indirection like `lambda s: s.lower()`, infavor of introspectable methods such as `str.lower` or `re.compile("pattern").search`.
To enable basic negation of commonly used predicates like `math.isnan` without introducing introspection that makes it impossible for implementers to introspect the predicate we provide a `Not` wrapper that simply negates the predicate in an introspectable manner. Several of the predicates listed above are created in this manner.
We do not specify what behaviour should be expected for predicates that raisean exception. For example `Annotated[int, Predicate(str.isdigit)]` might silentlyskip invalid constraints, or statically raise an error; or it might try calling itand then propagate or discard the resulting`TypeError: descriptor 'isdigit' for 'str' objects doesn't apply to a 'int' object`exception. We encourage libraries to document the behaviour they choose.
### Doc
`doc()` can be used to add documentation information in `Annotated`, for function and method parameters, variables, class attributes, return types, and any place where `Annotated` can be used.
It expects a value that can be statically analyzed, as the main use case is for static analysis, editors, documentation generators, and similar tools.
It returns a `DocInfo` class with a single attribute `documentation` containing the value passed to `doc()`.
This is the early adopter's alternative form of the [`typing-doc` proposal](https://github.com/tiangolo/fastapi/blob/typing-doc/typing_doc.md).
### Integrating downstream types with `GroupedMetadata`
Implementers may choose to provide a convenience wrapper that groups multiple pieces of metadata.This can help reduce verbosity and cognitive overhead for users.For example, an implementer like Pydantic might provide a `Field` or `Meta` type that accepts keyword arguments and transforms these into low-level metadata:
```pythonfrom dataclasses import dataclassfrom typing import Iteratorfrom annotated_types import GroupedMetadata, Ge
@dataclassclass Field(GroupedMetadata): ge: int | None = None description: str | None = None
def __iter__(self) -> Iterator[object]: # Iterating over a GroupedMetadata object should yield annotated-types # constraint metadata objects which describe it as fully as possible, # and may include other unknown objects too. if self.ge is not None: yield Ge(self.ge) if self.description is not None: yield Description(self.description)```
Libraries consuming annotated-types constraints should check for `GroupedMetadata` and unpack it by iterating over the object and treating the results as if they had been "unpacked" in the `Annotated` type. The same logic should be applied to the [PEP 646 `Unpack` type](https://peps.python.org/pep-0646/), so that `Annotated[T, Field(...)]`, `Annotated[T, Unpack[Field(...)]]` and `Annotated[T, *Field(...)]` are all treated consistently.
Libraries consuming annotated-types should also ignore any metadata they do not recongize that came from unpacking a `GroupedMetadata`, just like they ignore unrecognized metadata in `Annotated` itself.
Our own `annotated_types.Interval` class is a `GroupedMetadata` which unpacks itself into `Gt`, `Lt`, etc., so this is not an abstract concern. Similarly, `annotated_types.Len` is a `GroupedMetadata` which unpacks itself into `MinLen` (optionally) and `MaxLen`.
### Consuming metadata
We intend to not be prescriptive as to _how_ the metadata and constraints are used, but as an example of how one might parse constraints from types annotations see our [implementation in `test_main.py`](https://github.com/annotated-types/annotated-types/blob/f59cf6d1b5255a0fe359b93896759a180bec30ae/tests/test_main.py#L94-L103).
It is up to the implementer to determine how this metadata is used.You could use the metadata for runtime type checking, for generating schemas or to generate example data, amongst other use cases.
## Design & History
This package was designed at the PyCon 2022 sprints by the maintainers of Pydanticand Hypothesis, with the goal of making it as easy as possible for end-users toprovide more informative annotations for use by runtime libraries.
It is deliberately minimal, and following PEP-593 allows considerable downstreamdiscretion in what (if anything!) they choose to support. Nonetheless, we expectthat staying simple and covering _only_ the most common use-cases will give usersand maintainers the best experience we can. If you'd like more constraints for yourtypes - follow our lead, by defining them and documenting them downstream!12345678910annotated_types-0.7.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
annotated_types-0.7.0.dist-info/METADATA,sha256=7ltqxksJJ0wCYFGBNIQCWTlWQGeAH0hRFdnK3CB895E,15046
annotated_types-0.7.0.dist-info/RECORD,,
annotated_types-0.7.0.dist-info/WHEEL,sha256=zEMcRr9Kr03x1ozGwg5v9NQBKn3kndp6LSoSlVg-jhU,87
annotated_types-0.7.0.dist-info/licenses/LICENSE,sha256=_hBJiEsaDZNCkB6I4H8ykl0ksxIdmXK2poBfuYJLCV0,1083
annotated_types/__init__.py,sha256=RynLsRKUEGI0KimXydlD1fZEfEzWwDo0Uon3zOKhG1Q,13819
annotated_types/__pycache__/__init__.cpython-312.pyc,,
annotated_types/__pycache__/test_cases.cpython-312.pyc,,
annotated_types/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
annotated_types/test_cases.py,sha256=zHFX6EpcMbGJ8FzBYDbO56bPwx_DYIVSKbZM-4B3_lg,64211234Wheel-Version: 1.0Generator: hatchling 1.24.2Root-Is-Purelib: trueTag: py3-none-any123456789101112131415161718192021The MIT License (MIT)
Copyright (c) 2022 the contributors
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished 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,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432import mathimport sysimport typesfrom dataclasses import dataclassfrom datetime import tzinfofrom typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, SupportsFloat, SupportsIndex, TypeVar, Union
if sys.version_info < (3, 8): from typing_extensions import Protocol, runtime_checkableelse: from typing import Protocol, runtime_checkable
if sys.version_info < (3, 9): from typing_extensions import Annotated, Literalelse: from typing import Annotated, Literal
if sys.version_info < (3, 10): EllipsisType = type(Ellipsis) KW_ONLY = {} SLOTS = {}else: from types import EllipsisType
KW_ONLY = {"kw_only": True} SLOTS = {"slots": True}
__all__ = ( 'BaseMetadata', 'GroupedMetadata', 'Gt', 'Ge', 'Lt', 'Le', 'Interval', 'MultipleOf', 'MinLen', 'MaxLen', 'Len', 'Timezone', 'Predicate', 'LowerCase', 'UpperCase', 'IsDigits', 'IsFinite', 'IsNotFinite', 'IsNan', 'IsNotNan', 'IsInfinite', 'IsNotInfinite', 'doc', 'DocInfo', '__version__',)
__version__ = '0.7.0'
T = TypeVar('T')
# arguments that start with __ are considered# positional only# see https://peps.python.org/pep-0484/#positional-only-arguments
class SupportsGt(Protocol): def __gt__(self: T, __other: T) -> bool: ...
class SupportsGe(Protocol): def __ge__(self: T, __other: T) -> bool: ...
class SupportsLt(Protocol): def __lt__(self: T, __other: T) -> bool: ...
class SupportsLe(Protocol): def __le__(self: T, __other: T) -> bool: ...
class SupportsMod(Protocol): def __mod__(self: T, __other: T) -> T: ...
class SupportsDiv(Protocol): def __div__(self: T, __other: T) -> T: ...
class BaseMetadata: """Base class for all metadata.
This exists mainly so that implementers can do `isinstance(..., BaseMetadata)` while traversing field annotations. """
__slots__ = ()
@dataclass(frozen=True, **SLOTS)class Gt(BaseMetadata): """Gt(gt=x) implies that the value must be greater than x.
It can be used with any type that supports the ``>`` operator, including numbers, dates and times, strings, sets, and so on. """
gt: SupportsGt
@dataclass(frozen=True, **SLOTS)class Ge(BaseMetadata): """Ge(ge=x) implies that the value must be greater than or equal to x.
It can be used with any type that supports the ``>=`` operator, including numbers, dates and times, strings, sets, and so on. """
ge: SupportsGe
@dataclass(frozen=True, **SLOTS)class Lt(BaseMetadata): """Lt(lt=x) implies that the value must be less than x.
It can be used with any type that supports the ``<`` operator, including numbers, dates and times, strings, sets, and so on. """
lt: SupportsLt
@dataclass(frozen=True, **SLOTS)class Le(BaseMetadata): """Le(le=x) implies that the value must be less than or equal to x.
It can be used with any type that supports the ``<=`` operator, including numbers, dates and times, strings, sets, and so on. """
le: SupportsLe
@runtime_checkableclass GroupedMetadata(Protocol): """A grouping of multiple objects, like typing.Unpack.
`GroupedMetadata` on its own is not metadata and has no meaning. All of the constraints and metadata should be fully expressable in terms of the `BaseMetadata`'s returned by `GroupedMetadata.__iter__()`.
Concrete implementations should override `GroupedMetadata.__iter__()` to add their own metadata. For example:
>>> @dataclass >>> class Field(GroupedMetadata): >>> gt: float | None = None >>> description: str | None = None ... >>> def __iter__(self) -> Iterable[object]: >>> if self.gt is not None: >>> yield Gt(self.gt) >>> if self.description is not None: >>> yield Description(self.gt)
Also see the implementation of `Interval` below for an example.
Parsers should recognize this and unpack it so that it can be used both with and without unpacking:
- `Annotated[int, Field(...)]` (parser must unpack Field) - `Annotated[int, *Field(...)]` (PEP-646) """ # noqa: trailing-whitespace
@property def __is_annotated_types_grouped_metadata__(self) -> Literal[True]: return True
def __iter__(self) -> Iterator[object]: ...
if not TYPE_CHECKING: __slots__ = () # allow subclasses to use slots
def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None: # Basic ABC like functionality without the complexity of an ABC super().__init_subclass__(*args, **kwargs) if cls.__iter__ is GroupedMetadata.__iter__: raise TypeError("Can't subclass GroupedMetadata without implementing __iter__")
def __iter__(self) -> Iterator[object]: # noqa: F811 raise NotImplementedError # more helpful than "None has no attribute..." type errors
@dataclass(frozen=True, **KW_ONLY, **SLOTS)class Interval(GroupedMetadata): """Interval can express inclusive or exclusive bounds with a single object.
It accepts keyword arguments ``gt``, ``ge``, ``lt``, and/or ``le``, which are interpreted the same way as the single-bound constraints. """
gt: Union[SupportsGt, None] = None ge: Union[SupportsGe, None] = None lt: Union[SupportsLt, None] = None le: Union[SupportsLe, None] = None
def __iter__(self) -> Iterator[BaseMetadata]: """Unpack an Interval into zero or more single-bounds.""" if self.gt is not None: yield Gt(self.gt) if self.ge is not None: yield Ge(self.ge) if self.lt is not None: yield Lt(self.lt) if self.le is not None: yield Le(self.le)
@dataclass(frozen=True, **SLOTS)class MultipleOf(BaseMetadata): """MultipleOf(multiple_of=x) might be interpreted in two ways:
1. Python semantics, implying ``value % multiple_of == 0``, or 2. JSONschema semantics, where ``int(value / multiple_of) == value / multiple_of``
We encourage users to be aware of these two common interpretations, and libraries to carefully document which they implement. """
multiple_of: Union[SupportsDiv, SupportsMod]
@dataclass(frozen=True, **SLOTS)class MinLen(BaseMetadata): """ MinLen() implies minimum inclusive length, e.g. ``len(value) >= min_length``. """
min_length: Annotated[int, Ge(0)]
@dataclass(frozen=True, **SLOTS)class MaxLen(BaseMetadata): """ MaxLen() implies maximum inclusive length, e.g. ``len(value) <= max_length``. """
max_length: Annotated[int, Ge(0)]
@dataclass(frozen=True, **SLOTS)class Len(GroupedMetadata): """ Len() implies that ``min_length <= len(value) <= max_length``.
Upper bound may be omitted or ``None`` to indicate no upper length bound. """
min_length: Annotated[int, Ge(0)] = 0 max_length: Optional[Annotated[int, Ge(0)]] = None
def __iter__(self) -> Iterator[BaseMetadata]: """Unpack a Len into zone or more single-bounds.""" if self.min_length > 0: yield MinLen(self.min_length) if self.max_length is not None: yield MaxLen(self.max_length)
@dataclass(frozen=True, **SLOTS)class Timezone(BaseMetadata): """Timezone(tz=...) requires a datetime to be aware (or ``tz=None``, naive).
``Annotated[datetime, Timezone(None)]`` must be a naive datetime. ``Timezone[...]`` (the ellipsis literal) expresses that the datetime must be tz-aware but any timezone is allowed.
You may also pass a specific timezone string or tzinfo object such as ``Timezone(timezone.utc)`` or ``Timezone("Africa/Abidjan")`` to express that you only allow a specific timezone, though we note that this is often a symptom of poor design. """
tz: Union[str, tzinfo, EllipsisType, None]
@dataclass(frozen=True, **SLOTS)class Unit(BaseMetadata): """Indicates that the value is a physical quantity with the specified unit.
It is intended for usage with numeric types, where the value represents the magnitude of the quantity. For example, ``distance: Annotated[float, Unit('m')]`` or ``speed: Annotated[float, Unit('m/s')]``.
Interpretation of the unit string is left to the discretion of the consumer. It is suggested to follow conventions established by python libraries that work with physical quantities, such as
- ``pint`` : <https://pint.readthedocs.io/en/stable/> - ``astropy.units``: <https://docs.astropy.org/en/stable/units/>
For indicating a quantity with a certain dimensionality but without a specific unit it is recommended to use square brackets, e.g. `Annotated[float, Unit('[time]')]`. Note, however, ``annotated_types`` itself makes no use of the unit string. """
unit: str
@dataclass(frozen=True, **SLOTS)class Predicate(BaseMetadata): """``Predicate(func: Callable)`` implies `func(value)` is truthy for valid values.
Users should prefer statically inspectable metadata, but if you need the full power and flexibility of arbitrary runtime predicates... here it is.
We provide a few predefined predicates for common string constraints: ``IsLower = Predicate(str.islower)``, ``IsUpper = Predicate(str.isupper)``, and ``IsDigits = Predicate(str.isdigit)``. Users are encouraged to use methods which can be given special handling, and avoid indirection like ``lambda s: s.lower()``.
Some libraries might have special logic to handle certain predicates, e.g. by checking for `str.isdigit` and using its presence to both call custom logic to enforce digit-only strings, and customise some generated external schema.
We do not specify what behaviour should be expected for predicates that raise an exception. For example `Annotated[int, Predicate(str.isdigit)]` might silently skip invalid constraints, or statically raise an error; or it might try calling it and then propagate or discard the resulting exception. """
func: Callable[[Any], bool]
def __repr__(self) -> str: if getattr(self.func, "__name__", "<lambda>") == "<lambda>": return f"{self.__class__.__name__}({self.func!r})" if isinstance(self.func, (types.MethodType, types.BuiltinMethodType)) and ( namespace := getattr(self.func.__self__, "__name__", None) ): return f"{self.__class__.__name__}({namespace}.{self.func.__name__})" if isinstance(self.func, type(str.isascii)): # method descriptor return f"{self.__class__.__name__}({self.func.__qualname__})" return f"{self.__class__.__name__}({self.func.__name__})"
@dataclassclass Not: func: Callable[[Any], bool]
def __call__(self, __v: Any) -> bool: return not self.func(__v)
_StrType = TypeVar("_StrType", bound=str)
LowerCase = Annotated[_StrType, Predicate(str.islower)]"""Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.""" # noqa: E501UpperCase = Annotated[_StrType, Predicate(str.isupper)]"""Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.""" # noqa: E501IsDigit = Annotated[_StrType, Predicate(str.isdigit)]IsDigits = IsDigit # type: ignore # plural for backwards compatibility, see #63"""Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.""" # noqa: E501IsAscii = Annotated[_StrType, Predicate(str.isascii)]"""Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too."""
_NumericType = TypeVar('_NumericType', bound=Union[SupportsFloat, SupportsIndex])IsFinite = Annotated[_NumericType, Predicate(math.isfinite)]"""Return True if x is neither an infinity nor a NaN, and False otherwise."""IsNotFinite = Annotated[_NumericType, Predicate(Not(math.isfinite))]"""Return True if x is one of infinity or NaN, and False otherwise"""IsNan = Annotated[_NumericType, Predicate(math.isnan)]"""Return True if x is a NaN (not a number), and False otherwise."""IsNotNan = Annotated[_NumericType, Predicate(Not(math.isnan))]"""Return True if x is anything but NaN (not a number), and False otherwise."""IsInfinite = Annotated[_NumericType, Predicate(math.isinf)]"""Return True if x is a positive or negative infinity, and False otherwise."""IsNotInfinite = Annotated[_NumericType, Predicate(Not(math.isinf))]"""Return True if x is neither a positive or negative infinity, and False otherwise."""
try: from typing_extensions import DocInfo, doc # type: ignore [attr-defined]except ImportError:
@dataclass(frozen=True, **SLOTS) class DocInfo: # type: ignore [no-redef] """ " The return value of doc(), mainly to be used by tools that want to extract the Annotated documentation at runtime. """
documentation: str """The documentation string passed to doc()."""
def doc( documentation: str, ) -> DocInfo: """ Add documentation to a type annotation inside of Annotated.
For example:
>>> def hi(name: Annotated[int, doc("The name of the user")]) -> None: ... """ return DocInfo(documentation).envAdded+13
.env.exampleAdded+15
.gitattributes+22
.venv/bin/Activate.ps1Added+247
.venv/bin/activateAdded+70
.venv/bin/activate.cshAdded+27
.venv/bin/activate.fishAdded+69
.venv/bin/dotenvAdded+8
.venv/bin/fastapiAdded+8
.venv/bin/hfAdded+8
.venv/bin/httpxAdded+8
.venv/bin/huggingface-cliAdded+8
.venv/bin/idnaAdded+8
.venv/bin/markdown-itAdded+8
.venv/bin/pipAdded+8
.venv/bin/pip3Added+8
.venv/bin/pip3.12Added+8
.venv/bin/pygmentizeAdded+8
.venv/bin/pythonAdded+3
.venv/bin/python3Added+3
.venv/bin/python3.12Added+3
.venv/bin/tiny-agentsAdded+8
.venv/bin/tqdmAdded+8
.venv/bin/typerAdded+8
.venv/bin/uvicornAdded+8
.venv/bin/watchfilesAdded+8
.venv/bin/websocketsAdded+8
.venv/lib/python3.12/site-packages/StrEnum-0.4.15.dist-info/INSTALLERAdded+1
.venv/lib/python3.12/site-packages/StrEnum-0.4.15.dist-info/LICENSEAdded+21
.venv/lib/python3.12/site-packages/StrEnum-0.4.15.dist-info/METADATAAdded+211
.venv/lib/python3.12/site-packages/StrEnum-0.4.15.dist-info/RECORDAdded+18
.venv/lib/python3.12/site-packages/StrEnum-0.4.15.dist-info/WHEELAdded+5
.venv/lib/python3.12/site-packages/StrEnum-0.4.15.dist-info/top_level.txtAdded+1
.venv/lib/python3.12/site-packages/_cffi_backend.cpython-312-x86_64-linux-gnu.soAdded+3
.venv/lib/python3.12/site-packages/_yaml/__init__.pyAdded+33
.venv/lib/python3.12/site-packages/annotated_doc-0.0.4.dist-info/INSTALLERAdded+1
.venv/lib/python3.12/site-packages/annotated_doc-0.0.4.dist-info/METADATAAdded+145
.venv/lib/python3.12/site-packages/annotated_doc-0.0.4.dist-info/RECORDAdded+11
.venv/lib/python3.12/site-packages/annotated_doc-0.0.4.dist-info/WHEELAdded+4
.venv/lib/python3.12/site-packages/annotated_doc-0.0.4.dist-info/entry_points.txtAdded+4
.venv/lib/python3.12/site-packages/annotated_doc-0.0.4.dist-info/licenses/LICENSEAdded+21
.venv/lib/python3.12/site-packages/annotated_doc/__init__.pyAdded+3
.venv/lib/python3.12/site-packages/annotated_doc/main.pyAdded+36
.venv/lib/python3.12/site-packages/annotated_doc/py.typedAdded
.venv/lib/python3.12/site-packages/annotated_types-0.7.0.dist-info/INSTALLERAdded+1
.venv/lib/python3.12/site-packages/annotated_types-0.7.0.dist-info/METADATAAdded+295
.venv/lib/python3.12/site-packages/annotated_types-0.7.0.dist-info/RECORDAdded+10
.venv/lib/python3.12/site-packages/annotated_types-0.7.0.dist-info/WHEELAdded+4
.venv/lib/python3.12/site-packages/annotated_types-0.7.0.dist-info/licenses/LICENSEAdded+21
.venv/lib/python3.12/site-packages/annotated_types/__init__.pyAdded+432