codekingpro commited on
Commit
c808d4b
·
verified ·
1 Parent(s): d73b086

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/__future__.py +147 -0
  2. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/__hello__.py +16 -0
  3. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_aix_support.py +91 -0
  4. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_bootsubprocess.py +97 -0
  5. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_collections_abc.py +1121 -0
  6. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_compat_pickle.py +252 -0
  7. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_compression.py +162 -0
  8. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_markupbase.py +396 -0
  9. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_osx_support.py +579 -0
  10. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_py_abc.py +147 -0
  11. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_pydecimal.py +0 -0
  12. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_pyio.py +2712 -0
  13. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_sitebuiltins.py +103 -0
  14. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_strptime.py +578 -0
  15. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_threading_local.py +242 -0
  16. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_weakrefset.py +205 -0
  17. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/abc.py +188 -0
  18. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/aifc.py +984 -0
  19. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/antigravity.py +17 -0
  20. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/argparse.py +0 -0
  21. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/ast.py +1752 -0
  22. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asynchat.py +314 -0
  23. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/__init__.py +46 -0
  24. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/__main__.py +127 -0
  25. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/base_events.py +1961 -0
  26. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/base_futures.py +68 -0
  27. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/base_subprocess.py +285 -0
  28. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/base_tasks.py +92 -0
  29. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/constants.py +38 -0
  30. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/coroutines.py +111 -0
  31. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/events.py +846 -0
  32. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/exceptions.py +62 -0
  33. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/format_helpers.py +76 -0
  34. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/futures.py +428 -0
  35. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/locks.py +587 -0
  36. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/log.py +7 -0
  37. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/mixins.py +21 -0
  38. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/proactor_events.py +894 -0
  39. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/protocols.py +216 -0
  40. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/queues.py +244 -0
  41. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/runners.py +211 -0
  42. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/selector_events.py +1246 -0
  43. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/sslproto.py +926 -0
  44. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/staggered.py +149 -0
  45. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/streams.py +768 -0
  46. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/subprocess.py +228 -0
  47. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/taskgroups.py +234 -0
  48. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/tasks.py +990 -0
  49. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/threads.py +25 -0
  50. micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/timeouts.py +168 -0
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/__future__.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Record of phased-in incompatible language changes.
2
+
3
+ Each line is of the form:
4
+
5
+ FeatureName = "_Feature(" OptionalRelease "," MandatoryRelease ","
6
+ CompilerFlag ")"
7
+
8
+ where, normally, OptionalRelease < MandatoryRelease, and both are 5-tuples
9
+ of the same form as sys.version_info:
10
+
11
+ (PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int
12
+ PY_MINOR_VERSION, # the 1; an int
13
+ PY_MICRO_VERSION, # the 0; an int
14
+ PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string
15
+ PY_RELEASE_SERIAL # the 3; an int
16
+ )
17
+
18
+ OptionalRelease records the first release in which
19
+
20
+ from __future__ import FeatureName
21
+
22
+ was accepted.
23
+
24
+ In the case of MandatoryReleases that have not yet occurred,
25
+ MandatoryRelease predicts the release in which the feature will become part
26
+ of the language.
27
+
28
+ Else MandatoryRelease records when the feature became part of the language;
29
+ in releases at or after that, modules no longer need
30
+
31
+ from __future__ import FeatureName
32
+
33
+ to use the feature in question, but may continue to use such imports.
34
+
35
+ MandatoryRelease may also be None, meaning that a planned feature got
36
+ dropped or that the release version is undetermined.
37
+
38
+ Instances of class _Feature have two corresponding methods,
39
+ .getOptionalRelease() and .getMandatoryRelease().
40
+
41
+ CompilerFlag is the (bitfield) flag that should be passed in the fourth
42
+ argument to the builtin function compile() to enable the feature in
43
+ dynamically compiled code. This flag is stored in the .compiler_flag
44
+ attribute on _Future instances. These values must match the appropriate
45
+ #defines of CO_xxx flags in Include/cpython/compile.h.
46
+
47
+ No feature line is ever to be deleted from this file.
48
+ """
49
+
50
+ all_feature_names = [
51
+ "nested_scopes",
52
+ "generators",
53
+ "division",
54
+ "absolute_import",
55
+ "with_statement",
56
+ "print_function",
57
+ "unicode_literals",
58
+ "barry_as_FLUFL",
59
+ "generator_stop",
60
+ "annotations",
61
+ ]
62
+
63
+ __all__ = ["all_feature_names"] + all_feature_names
64
+
65
+ # The CO_xxx symbols are defined here under the same names defined in
66
+ # code.h and used by compile.h, so that an editor search will find them here.
67
+ # However, they're not exported in __all__, because they don't really belong to
68
+ # this module.
69
+ CO_NESTED = 0x0010 # nested_scopes
70
+ CO_GENERATOR_ALLOWED = 0 # generators (obsolete, was 0x1000)
71
+ CO_FUTURE_DIVISION = 0x20000 # division
72
+ CO_FUTURE_ABSOLUTE_IMPORT = 0x40000 # perform absolute imports by default
73
+ CO_FUTURE_WITH_STATEMENT = 0x80000 # with statement
74
+ CO_FUTURE_PRINT_FUNCTION = 0x100000 # print function
75
+ CO_FUTURE_UNICODE_LITERALS = 0x200000 # unicode string literals
76
+ CO_FUTURE_BARRY_AS_BDFL = 0x400000
77
+ CO_FUTURE_GENERATOR_STOP = 0x800000 # StopIteration becomes RuntimeError in generators
78
+ CO_FUTURE_ANNOTATIONS = 0x1000000 # annotations become strings at runtime
79
+
80
+
81
+ class _Feature:
82
+
83
+ def __init__(self, optionalRelease, mandatoryRelease, compiler_flag):
84
+ self.optional = optionalRelease
85
+ self.mandatory = mandatoryRelease
86
+ self.compiler_flag = compiler_flag
87
+
88
+ def getOptionalRelease(self):
89
+ """Return first release in which this feature was recognized.
90
+
91
+ This is a 5-tuple, of the same form as sys.version_info.
92
+ """
93
+ return self.optional
94
+
95
+ def getMandatoryRelease(self):
96
+ """Return release in which this feature will become mandatory.
97
+
98
+ This is a 5-tuple, of the same form as sys.version_info, or, if
99
+ the feature was dropped, or the release date is undetermined, is None.
100
+ """
101
+ return self.mandatory
102
+
103
+ def __repr__(self):
104
+ return "_Feature" + repr((self.optional,
105
+ self.mandatory,
106
+ self.compiler_flag))
107
+
108
+
109
+ nested_scopes = _Feature((2, 1, 0, "beta", 1),
110
+ (2, 2, 0, "alpha", 0),
111
+ CO_NESTED)
112
+
113
+ generators = _Feature((2, 2, 0, "alpha", 1),
114
+ (2, 3, 0, "final", 0),
115
+ CO_GENERATOR_ALLOWED)
116
+
117
+ division = _Feature((2, 2, 0, "alpha", 2),
118
+ (3, 0, 0, "alpha", 0),
119
+ CO_FUTURE_DIVISION)
120
+
121
+ absolute_import = _Feature((2, 5, 0, "alpha", 1),
122
+ (3, 0, 0, "alpha", 0),
123
+ CO_FUTURE_ABSOLUTE_IMPORT)
124
+
125
+ with_statement = _Feature((2, 5, 0, "alpha", 1),
126
+ (2, 6, 0, "alpha", 0),
127
+ CO_FUTURE_WITH_STATEMENT)
128
+
129
+ print_function = _Feature((2, 6, 0, "alpha", 2),
130
+ (3, 0, 0, "alpha", 0),
131
+ CO_FUTURE_PRINT_FUNCTION)
132
+
133
+ unicode_literals = _Feature((2, 6, 0, "alpha", 2),
134
+ (3, 0, 0, "alpha", 0),
135
+ CO_FUTURE_UNICODE_LITERALS)
136
+
137
+ barry_as_FLUFL = _Feature((3, 1, 0, "alpha", 2),
138
+ (4, 0, 0, "alpha", 0),
139
+ CO_FUTURE_BARRY_AS_BDFL)
140
+
141
+ generator_stop = _Feature((3, 5, 0, "beta", 1),
142
+ (3, 7, 0, "alpha", 0),
143
+ CO_FUTURE_GENERATOR_STOP)
144
+
145
+ annotations = _Feature((3, 7, 0, "beta", 1),
146
+ None,
147
+ CO_FUTURE_ANNOTATIONS)
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/__hello__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ initialized = True
2
+
3
+ class TestFrozenUtf8_1:
4
+ """\u00b6"""
5
+
6
+ class TestFrozenUtf8_2:
7
+ """\u03c0"""
8
+
9
+ class TestFrozenUtf8_4:
10
+ """\U0001f600"""
11
+
12
+ def main():
13
+ print("Hello world!")
14
+
15
+ if __name__ == '__main__':
16
+ main()
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_aix_support.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared AIX support functions."""
2
+
3
+ import sys
4
+ import sysconfig
5
+
6
+ try:
7
+ import subprocess
8
+ except ImportError: # pragma: no cover
9
+ # _aix_support is used in distutils by setup.py to build C extensions,
10
+ # before subprocess dependencies like _posixsubprocess are available.
11
+ import _bootsubprocess as subprocess
12
+
13
+
14
+ def _aix_tag(vrtl, bd):
15
+ # type: (List[int], int) -> str
16
+ # Infer the ABI bitwidth from maxsize (assuming 64 bit as the default)
17
+ _sz = 32 if sys.maxsize == (2**31-1) else 64
18
+ _bd = bd if bd != 0 else 9988
19
+ # vrtl[version, release, technology_level]
20
+ return "aix-{:1x}{:1d}{:02d}-{:04d}-{}".format(vrtl[0], vrtl[1], vrtl[2], _bd, _sz)
21
+
22
+
23
+ # extract version, release and technology level from a VRMF string
24
+ def _aix_vrtl(vrmf):
25
+ # type: (str) -> List[int]
26
+ v, r, tl = vrmf.split(".")[:3]
27
+ return [int(v[-1]), int(r), int(tl)]
28
+
29
+
30
+ def _aix_bos_rte():
31
+ # type: () -> Tuple[str, int]
32
+ """
33
+ Return a Tuple[str, int] e.g., ['7.1.4.34', 1806]
34
+ The fileset bos.rte represents the current AIX run-time level. It's VRMF and
35
+ builddate reflect the current ABI levels of the runtime environment.
36
+ If no builddate is found give a value that will satisfy pep425 related queries
37
+ """
38
+ # All AIX systems to have lslpp installed in this location
39
+ out = subprocess.check_output(["/usr/bin/lslpp", "-Lqc", "bos.rte"])
40
+ out = out.decode("utf-8")
41
+ out = out.strip().split(":") # type: ignore
42
+ _bd = int(out[-1]) if out[-1] != '' else 9988
43
+ return (str(out[2]), _bd)
44
+
45
+
46
+ def aix_platform():
47
+ # type: () -> str
48
+ """
49
+ AIX filesets are identified by four decimal values: V.R.M.F.
50
+ V (version) and R (release) can be retrieved using ``uname``
51
+ Since 2007, starting with AIX 5.3 TL7, the M value has been
52
+ included with the fileset bos.rte and represents the Technology
53
+ Level (TL) of AIX. The F (Fix) value also increases, but is not
54
+ relevant for comparing releases and binary compatibility.
55
+ For binary compatibility the so-called builddate is needed.
56
+ Again, the builddate of an AIX release is associated with bos.rte.
57
+ AIX ABI compatibility is described as guaranteed at: https://www.ibm.com/\
58
+ support/knowledgecenter/en/ssw_aix_72/install/binary_compatability.html
59
+
60
+ For pep425 purposes the AIX platform tag becomes:
61
+ "aix-{:1x}{:1d}{:02d}-{:04d}-{}".format(v, r, tl, builddate, bitsize)
62
+ e.g., "aix-6107-1415-32" for AIX 6.1 TL7 bd 1415, 32-bit
63
+ and, "aix-6107-1415-64" for AIX 6.1 TL7 bd 1415, 64-bit
64
+ """
65
+ vrmf, bd = _aix_bos_rte()
66
+ return _aix_tag(_aix_vrtl(vrmf), bd)
67
+
68
+
69
+ # extract vrtl from the BUILD_GNU_TYPE as an int
70
+ def _aix_bgt():
71
+ # type: () -> List[int]
72
+ gnu_type = sysconfig.get_config_var("BUILD_GNU_TYPE")
73
+ if not gnu_type:
74
+ raise ValueError("BUILD_GNU_TYPE is not defined")
75
+ return _aix_vrtl(vrmf=gnu_type)
76
+
77
+
78
+ def aix_buildtag():
79
+ # type: () -> str
80
+ """
81
+ Return the platform_tag of the system Python was built on.
82
+ """
83
+ # AIX_BUILDDATE is defined by configure with:
84
+ # lslpp -Lcq bos.rte | awk -F: '{ print $NF }'
85
+ build_date = sysconfig.get_config_var("AIX_BUILDDATE")
86
+ try:
87
+ build_date = int(build_date)
88
+ except (ValueError, TypeError):
89
+ raise ValueError(f"AIX_BUILDDATE is not defined or invalid: "
90
+ f"{build_date!r}")
91
+ return _aix_tag(_aix_bgt(), build_date)
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_bootsubprocess.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Basic subprocess implementation for POSIX which only uses os functions. Only
3
+ implement features required by setup.py to build C extension modules when
4
+ subprocess is unavailable. setup.py is not used on Windows.
5
+ """
6
+ import os
7
+
8
+
9
+ # distutils.spawn used by distutils.command.build_ext
10
+ # calls subprocess.Popen().wait()
11
+ class Popen:
12
+ def __init__(self, cmd, env=None):
13
+ self._cmd = cmd
14
+ self._env = env
15
+ self.returncode = None
16
+
17
+ def wait(self):
18
+ pid = os.fork()
19
+ if pid == 0:
20
+ # Child process
21
+ try:
22
+ if self._env is not None:
23
+ os.execve(self._cmd[0], self._cmd, self._env)
24
+ else:
25
+ os.execv(self._cmd[0], self._cmd)
26
+ finally:
27
+ os._exit(1)
28
+ else:
29
+ # Parent process
30
+ _, status = os.waitpid(pid, 0)
31
+ self.returncode = os.waitstatus_to_exitcode(status)
32
+
33
+ return self.returncode
34
+
35
+
36
+ def _check_cmd(cmd):
37
+ # Use regex [a-zA-Z0-9./-]+: reject empty string, space, etc.
38
+ safe_chars = []
39
+ for first, last in (("a", "z"), ("A", "Z"), ("0", "9")):
40
+ for ch in range(ord(first), ord(last) + 1):
41
+ safe_chars.append(chr(ch))
42
+ safe_chars.append("./-")
43
+ safe_chars = ''.join(safe_chars)
44
+
45
+ if isinstance(cmd, (tuple, list)):
46
+ check_strs = cmd
47
+ elif isinstance(cmd, str):
48
+ check_strs = [cmd]
49
+ else:
50
+ return False
51
+
52
+ for arg in check_strs:
53
+ if not isinstance(arg, str):
54
+ return False
55
+ if not arg:
56
+ # reject empty string
57
+ return False
58
+ for ch in arg:
59
+ if ch not in safe_chars:
60
+ return False
61
+
62
+ return True
63
+
64
+
65
+ # _aix_support used by distutil.util calls subprocess.check_output()
66
+ def check_output(cmd, **kwargs):
67
+ if kwargs:
68
+ raise NotImplementedError(repr(kwargs))
69
+
70
+ if not _check_cmd(cmd):
71
+ raise ValueError(f"unsupported command: {cmd!r}")
72
+
73
+ tmp_filename = "check_output.tmp"
74
+ if not isinstance(cmd, str):
75
+ cmd = " ".join(cmd)
76
+ cmd = f"{cmd} >{tmp_filename}"
77
+
78
+ try:
79
+ # system() spawns a shell
80
+ status = os.system(cmd)
81
+ exitcode = os.waitstatus_to_exitcode(status)
82
+ if exitcode:
83
+ raise ValueError(f"Command {cmd!r} returned non-zero "
84
+ f"exit status {exitcode!r}")
85
+
86
+ try:
87
+ with open(tmp_filename, "rb") as fp:
88
+ stdout = fp.read()
89
+ except FileNotFoundError:
90
+ stdout = b''
91
+ finally:
92
+ try:
93
+ os.unlink(tmp_filename)
94
+ except OSError:
95
+ pass
96
+
97
+ return stdout
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_collections_abc.py ADDED
@@ -0,0 +1,1121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2007 Google, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Abstract Base Classes (ABCs) for collections, according to PEP 3119.
5
+
6
+ Unit tests are in test_collections.
7
+ """
8
+
9
+ from abc import ABCMeta, abstractmethod
10
+ import sys
11
+
12
+ GenericAlias = type(list[int])
13
+ EllipsisType = type(...)
14
+ def _f(): pass
15
+ FunctionType = type(_f)
16
+ del _f
17
+
18
+ __all__ = ["Awaitable", "Coroutine",
19
+ "AsyncIterable", "AsyncIterator", "AsyncGenerator",
20
+ "Hashable", "Iterable", "Iterator", "Generator", "Reversible",
21
+ "Sized", "Container", "Callable", "Collection",
22
+ "Set", "MutableSet",
23
+ "Mapping", "MutableMapping",
24
+ "MappingView", "KeysView", "ItemsView", "ValuesView",
25
+ "Sequence", "MutableSequence",
26
+ "ByteString",
27
+ ]
28
+
29
+ # This module has been renamed from collections.abc to _collections_abc to
30
+ # speed up interpreter startup. Some of the types such as MutableMapping are
31
+ # required early but collections module imports a lot of other modules.
32
+ # See issue #19218
33
+ __name__ = "collections.abc"
34
+
35
+ # Private list of types that we want to register with the various ABCs
36
+ # so that they will pass tests like:
37
+ # it = iter(somebytearray)
38
+ # assert isinstance(it, Iterable)
39
+ # Note: in other implementations, these types might not be distinct
40
+ # and they may have their own implementation specific types that
41
+ # are not included on this list.
42
+ bytes_iterator = type(iter(b''))
43
+ bytearray_iterator = type(iter(bytearray()))
44
+ #callable_iterator = ???
45
+ dict_keyiterator = type(iter({}.keys()))
46
+ dict_valueiterator = type(iter({}.values()))
47
+ dict_itemiterator = type(iter({}.items()))
48
+ list_iterator = type(iter([]))
49
+ list_reverseiterator = type(iter(reversed([])))
50
+ range_iterator = type(iter(range(0)))
51
+ longrange_iterator = type(iter(range(1 << 1000)))
52
+ set_iterator = type(iter(set()))
53
+ str_iterator = type(iter(""))
54
+ tuple_iterator = type(iter(()))
55
+ zip_iterator = type(iter(zip()))
56
+ ## views ##
57
+ dict_keys = type({}.keys())
58
+ dict_values = type({}.values())
59
+ dict_items = type({}.items())
60
+ ## misc ##
61
+ mappingproxy = type(type.__dict__)
62
+ generator = type((lambda: (yield))())
63
+ ## coroutine ##
64
+ async def _coro(): pass
65
+ _coro = _coro()
66
+ coroutine = type(_coro)
67
+ _coro.close() # Prevent ResourceWarning
68
+ del _coro
69
+ ## asynchronous generator ##
70
+ async def _ag(): yield
71
+ _ag = _ag()
72
+ async_generator = type(_ag)
73
+ del _ag
74
+
75
+
76
+ ### ONE-TRICK PONIES ###
77
+
78
+ def _check_methods(C, *methods):
79
+ mro = C.__mro__
80
+ for method in methods:
81
+ for B in mro:
82
+ if method in B.__dict__:
83
+ if B.__dict__[method] is None:
84
+ return NotImplemented
85
+ break
86
+ else:
87
+ return NotImplemented
88
+ return True
89
+
90
+ class Hashable(metaclass=ABCMeta):
91
+
92
+ __slots__ = ()
93
+
94
+ @abstractmethod
95
+ def __hash__(self):
96
+ return 0
97
+
98
+ @classmethod
99
+ def __subclasshook__(cls, C):
100
+ if cls is Hashable:
101
+ return _check_methods(C, "__hash__")
102
+ return NotImplemented
103
+
104
+
105
+ class Awaitable(metaclass=ABCMeta):
106
+
107
+ __slots__ = ()
108
+
109
+ @abstractmethod
110
+ def __await__(self):
111
+ yield
112
+
113
+ @classmethod
114
+ def __subclasshook__(cls, C):
115
+ if cls is Awaitable:
116
+ return _check_methods(C, "__await__")
117
+ return NotImplemented
118
+
119
+ __class_getitem__ = classmethod(GenericAlias)
120
+
121
+
122
+ class Coroutine(Awaitable):
123
+
124
+ __slots__ = ()
125
+
126
+ @abstractmethod
127
+ def send(self, value):
128
+ """Send a value into the coroutine.
129
+ Return next yielded value or raise StopIteration.
130
+ """
131
+ raise StopIteration
132
+
133
+ @abstractmethod
134
+ def throw(self, typ, val=None, tb=None):
135
+ """Raise an exception in the coroutine.
136
+ Return next yielded value or raise StopIteration.
137
+ """
138
+ if val is None:
139
+ if tb is None:
140
+ raise typ
141
+ val = typ()
142
+ if tb is not None:
143
+ val = val.with_traceback(tb)
144
+ raise val
145
+
146
+ def close(self):
147
+ """Raise GeneratorExit inside coroutine.
148
+ """
149
+ try:
150
+ self.throw(GeneratorExit)
151
+ except (GeneratorExit, StopIteration):
152
+ pass
153
+ else:
154
+ raise RuntimeError("coroutine ignored GeneratorExit")
155
+
156
+ @classmethod
157
+ def __subclasshook__(cls, C):
158
+ if cls is Coroutine:
159
+ return _check_methods(C, '__await__', 'send', 'throw', 'close')
160
+ return NotImplemented
161
+
162
+
163
+ Coroutine.register(coroutine)
164
+
165
+
166
+ class AsyncIterable(metaclass=ABCMeta):
167
+
168
+ __slots__ = ()
169
+
170
+ @abstractmethod
171
+ def __aiter__(self):
172
+ return AsyncIterator()
173
+
174
+ @classmethod
175
+ def __subclasshook__(cls, C):
176
+ if cls is AsyncIterable:
177
+ return _check_methods(C, "__aiter__")
178
+ return NotImplemented
179
+
180
+ __class_getitem__ = classmethod(GenericAlias)
181
+
182
+
183
+ class AsyncIterator(AsyncIterable):
184
+
185
+ __slots__ = ()
186
+
187
+ @abstractmethod
188
+ async def __anext__(self):
189
+ """Return the next item or raise StopAsyncIteration when exhausted."""
190
+ raise StopAsyncIteration
191
+
192
+ def __aiter__(self):
193
+ return self
194
+
195
+ @classmethod
196
+ def __subclasshook__(cls, C):
197
+ if cls is AsyncIterator:
198
+ return _check_methods(C, "__anext__", "__aiter__")
199
+ return NotImplemented
200
+
201
+
202
+ class AsyncGenerator(AsyncIterator):
203
+
204
+ __slots__ = ()
205
+
206
+ async def __anext__(self):
207
+ """Return the next item from the asynchronous generator.
208
+ When exhausted, raise StopAsyncIteration.
209
+ """
210
+ return await self.asend(None)
211
+
212
+ @abstractmethod
213
+ async def asend(self, value):
214
+ """Send a value into the asynchronous generator.
215
+ Return next yielded value or raise StopAsyncIteration.
216
+ """
217
+ raise StopAsyncIteration
218
+
219
+ @abstractmethod
220
+ async def athrow(self, typ, val=None, tb=None):
221
+ """Raise an exception in the asynchronous generator.
222
+ Return next yielded value or raise StopAsyncIteration.
223
+ """
224
+ if val is None:
225
+ if tb is None:
226
+ raise typ
227
+ val = typ()
228
+ if tb is not None:
229
+ val = val.with_traceback(tb)
230
+ raise val
231
+
232
+ async def aclose(self):
233
+ """Raise GeneratorExit inside coroutine.
234
+ """
235
+ try:
236
+ await self.athrow(GeneratorExit)
237
+ except (GeneratorExit, StopAsyncIteration):
238
+ pass
239
+ else:
240
+ raise RuntimeError("asynchronous generator ignored GeneratorExit")
241
+
242
+ @classmethod
243
+ def __subclasshook__(cls, C):
244
+ if cls is AsyncGenerator:
245
+ return _check_methods(C, '__aiter__', '__anext__',
246
+ 'asend', 'athrow', 'aclose')
247
+ return NotImplemented
248
+
249
+
250
+ AsyncGenerator.register(async_generator)
251
+
252
+
253
+ class Iterable(metaclass=ABCMeta):
254
+
255
+ __slots__ = ()
256
+
257
+ @abstractmethod
258
+ def __iter__(self):
259
+ while False:
260
+ yield None
261
+
262
+ @classmethod
263
+ def __subclasshook__(cls, C):
264
+ if cls is Iterable:
265
+ return _check_methods(C, "__iter__")
266
+ return NotImplemented
267
+
268
+ __class_getitem__ = classmethod(GenericAlias)
269
+
270
+
271
+ class Iterator(Iterable):
272
+
273
+ __slots__ = ()
274
+
275
+ @abstractmethod
276
+ def __next__(self):
277
+ 'Return the next item from the iterator. When exhausted, raise StopIteration'
278
+ raise StopIteration
279
+
280
+ def __iter__(self):
281
+ return self
282
+
283
+ @classmethod
284
+ def __subclasshook__(cls, C):
285
+ if cls is Iterator:
286
+ return _check_methods(C, '__iter__', '__next__')
287
+ return NotImplemented
288
+
289
+
290
+ Iterator.register(bytes_iterator)
291
+ Iterator.register(bytearray_iterator)
292
+ #Iterator.register(callable_iterator)
293
+ Iterator.register(dict_keyiterator)
294
+ Iterator.register(dict_valueiterator)
295
+ Iterator.register(dict_itemiterator)
296
+ Iterator.register(list_iterator)
297
+ Iterator.register(list_reverseiterator)
298
+ Iterator.register(range_iterator)
299
+ Iterator.register(longrange_iterator)
300
+ Iterator.register(set_iterator)
301
+ Iterator.register(str_iterator)
302
+ Iterator.register(tuple_iterator)
303
+ Iterator.register(zip_iterator)
304
+
305
+
306
+ class Reversible(Iterable):
307
+
308
+ __slots__ = ()
309
+
310
+ @abstractmethod
311
+ def __reversed__(self):
312
+ while False:
313
+ yield None
314
+
315
+ @classmethod
316
+ def __subclasshook__(cls, C):
317
+ if cls is Reversible:
318
+ return _check_methods(C, "__reversed__", "__iter__")
319
+ return NotImplemented
320
+
321
+
322
+ class Generator(Iterator):
323
+
324
+ __slots__ = ()
325
+
326
+ def __next__(self):
327
+ """Return the next item from the generator.
328
+ When exhausted, raise StopIteration.
329
+ """
330
+ return self.send(None)
331
+
332
+ @abstractmethod
333
+ def send(self, value):
334
+ """Send a value into the generator.
335
+ Return next yielded value or raise StopIteration.
336
+ """
337
+ raise StopIteration
338
+
339
+ @abstractmethod
340
+ def throw(self, typ, val=None, tb=None):
341
+ """Raise an exception in the generator.
342
+ Return next yielded value or raise StopIteration.
343
+ """
344
+ if val is None:
345
+ if tb is None:
346
+ raise typ
347
+ val = typ()
348
+ if tb is not None:
349
+ val = val.with_traceback(tb)
350
+ raise val
351
+
352
+ def close(self):
353
+ """Raise GeneratorExit inside generator.
354
+ """
355
+ try:
356
+ self.throw(GeneratorExit)
357
+ except (GeneratorExit, StopIteration):
358
+ pass
359
+ else:
360
+ raise RuntimeError("generator ignored GeneratorExit")
361
+
362
+ @classmethod
363
+ def __subclasshook__(cls, C):
364
+ if cls is Generator:
365
+ return _check_methods(C, '__iter__', '__next__',
366
+ 'send', 'throw', 'close')
367
+ return NotImplemented
368
+
369
+
370
+ Generator.register(generator)
371
+
372
+
373
+ class Sized(metaclass=ABCMeta):
374
+
375
+ __slots__ = ()
376
+
377
+ @abstractmethod
378
+ def __len__(self):
379
+ return 0
380
+
381
+ @classmethod
382
+ def __subclasshook__(cls, C):
383
+ if cls is Sized:
384
+ return _check_methods(C, "__len__")
385
+ return NotImplemented
386
+
387
+
388
+ class Container(metaclass=ABCMeta):
389
+
390
+ __slots__ = ()
391
+
392
+ @abstractmethod
393
+ def __contains__(self, x):
394
+ return False
395
+
396
+ @classmethod
397
+ def __subclasshook__(cls, C):
398
+ if cls is Container:
399
+ return _check_methods(C, "__contains__")
400
+ return NotImplemented
401
+
402
+ __class_getitem__ = classmethod(GenericAlias)
403
+
404
+
405
+ class Collection(Sized, Iterable, Container):
406
+
407
+ __slots__ = ()
408
+
409
+ @classmethod
410
+ def __subclasshook__(cls, C):
411
+ if cls is Collection:
412
+ return _check_methods(C, "__len__", "__iter__", "__contains__")
413
+ return NotImplemented
414
+
415
+
416
+ class _CallableGenericAlias(GenericAlias):
417
+ """ Represent `Callable[argtypes, resulttype]`.
418
+
419
+ This sets ``__args__`` to a tuple containing the flattened ``argtypes``
420
+ followed by ``resulttype``.
421
+
422
+ Example: ``Callable[[int, str], float]`` sets ``__args__`` to
423
+ ``(int, str, float)``.
424
+ """
425
+
426
+ __slots__ = ()
427
+
428
+ def __new__(cls, origin, args):
429
+ if not (isinstance(args, tuple) and len(args) == 2):
430
+ raise TypeError(
431
+ "Callable must be used as Callable[[arg, ...], result].")
432
+ t_args, t_result = args
433
+ if isinstance(t_args, (tuple, list)):
434
+ args = (*t_args, t_result)
435
+ elif not _is_param_expr(t_args):
436
+ raise TypeError(f"Expected a list of types, an ellipsis, "
437
+ f"ParamSpec, or Concatenate. Got {t_args}")
438
+ return super().__new__(cls, origin, args)
439
+
440
+ def __repr__(self):
441
+ if len(self.__args__) == 2 and _is_param_expr(self.__args__[0]):
442
+ return super().__repr__()
443
+ return (f'collections.abc.Callable'
444
+ f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
445
+ f'{_type_repr(self.__args__[-1])}]')
446
+
447
+ def __reduce__(self):
448
+ args = self.__args__
449
+ if not (len(args) == 2 and _is_param_expr(args[0])):
450
+ args = list(args[:-1]), args[-1]
451
+ return _CallableGenericAlias, (Callable, args)
452
+
453
+ def __getitem__(self, item):
454
+ # Called during TypeVar substitution, returns the custom subclass
455
+ # rather than the default types.GenericAlias object. Most of the
456
+ # code is copied from typing's _GenericAlias and the builtin
457
+ # types.GenericAlias.
458
+
459
+ if not isinstance(item, tuple):
460
+ item = (item,)
461
+ # A special case in PEP 612 where if X = Callable[P, int],
462
+ # then X[int, str] == X[[int, str]].
463
+ if (len(self.__parameters__) == 1
464
+ and _is_param_expr(self.__parameters__[0])
465
+ and item and not _is_param_expr(item[0])):
466
+ item = (item,)
467
+
468
+ new_args = super().__getitem__(item).__args__
469
+
470
+ # args[0] occurs due to things like Z[[int, str, bool]] from PEP 612
471
+ if not isinstance(new_args[0], (tuple, list)):
472
+ t_result = new_args[-1]
473
+ t_args = new_args[:-1]
474
+ new_args = (t_args, t_result)
475
+ return _CallableGenericAlias(Callable, tuple(new_args))
476
+
477
+ def _is_param_expr(obj):
478
+ """Checks if obj matches either a list of types, ``...``, ``ParamSpec`` or
479
+ ``_ConcatenateGenericAlias`` from typing.py
480
+ """
481
+ if obj is Ellipsis:
482
+ return True
483
+ if isinstance(obj, list):
484
+ return True
485
+ obj = type(obj)
486
+ names = ('ParamSpec', '_ConcatenateGenericAlias')
487
+ return obj.__module__ == 'typing' and any(obj.__name__ == name for name in names)
488
+
489
+ def _type_repr(obj):
490
+ """Return the repr() of an object, special-casing types (internal helper).
491
+
492
+ Copied from :mod:`typing` since collections.abc
493
+ shouldn't depend on that module.
494
+ """
495
+ if isinstance(obj, GenericAlias):
496
+ return repr(obj)
497
+ if isinstance(obj, type):
498
+ if obj.__module__ == 'builtins':
499
+ return obj.__qualname__
500
+ return f'{obj.__module__}.{obj.__qualname__}'
501
+ if obj is Ellipsis:
502
+ return '...'
503
+ if isinstance(obj, FunctionType):
504
+ return obj.__name__
505
+ return repr(obj)
506
+
507
+
508
+ class Callable(metaclass=ABCMeta):
509
+
510
+ __slots__ = ()
511
+
512
+ @abstractmethod
513
+ def __call__(self, *args, **kwds):
514
+ return False
515
+
516
+ @classmethod
517
+ def __subclasshook__(cls, C):
518
+ if cls is Callable:
519
+ return _check_methods(C, "__call__")
520
+ return NotImplemented
521
+
522
+ __class_getitem__ = classmethod(_CallableGenericAlias)
523
+
524
+
525
+ ### SETS ###
526
+
527
+
528
+ class Set(Collection):
529
+ """A set is a finite, iterable container.
530
+
531
+ This class provides concrete generic implementations of all
532
+ methods except for __contains__, __iter__ and __len__.
533
+
534
+ To override the comparisons (presumably for speed, as the
535
+ semantics are fixed), redefine __le__ and __ge__,
536
+ then the other operations will automatically follow suit.
537
+ """
538
+
539
+ __slots__ = ()
540
+
541
+ def __le__(self, other):
542
+ if not isinstance(other, Set):
543
+ return NotImplemented
544
+ if len(self) > len(other):
545
+ return False
546
+ for elem in self:
547
+ if elem not in other:
548
+ return False
549
+ return True
550
+
551
+ def __lt__(self, other):
552
+ if not isinstance(other, Set):
553
+ return NotImplemented
554
+ return len(self) < len(other) and self.__le__(other)
555
+
556
+ def __gt__(self, other):
557
+ if not isinstance(other, Set):
558
+ return NotImplemented
559
+ return len(self) > len(other) and self.__ge__(other)
560
+
561
+ def __ge__(self, other):
562
+ if not isinstance(other, Set):
563
+ return NotImplemented
564
+ if len(self) < len(other):
565
+ return False
566
+ for elem in other:
567
+ if elem not in self:
568
+ return False
569
+ return True
570
+
571
+ def __eq__(self, other):
572
+ if not isinstance(other, Set):
573
+ return NotImplemented
574
+ return len(self) == len(other) and self.__le__(other)
575
+
576
+ @classmethod
577
+ def _from_iterable(cls, it):
578
+ '''Construct an instance of the class from any iterable input.
579
+
580
+ Must override this method if the class constructor signature
581
+ does not accept an iterable for an input.
582
+ '''
583
+ return cls(it)
584
+
585
+ def __and__(self, other):
586
+ if not isinstance(other, Iterable):
587
+ return NotImplemented
588
+ return self._from_iterable(value for value in other if value in self)
589
+
590
+ __rand__ = __and__
591
+
592
+ def isdisjoint(self, other):
593
+ 'Return True if two sets have a null intersection.'
594
+ for value in other:
595
+ if value in self:
596
+ return False
597
+ return True
598
+
599
+ def __or__(self, other):
600
+ if not isinstance(other, Iterable):
601
+ return NotImplemented
602
+ chain = (e for s in (self, other) for e in s)
603
+ return self._from_iterable(chain)
604
+
605
+ __ror__ = __or__
606
+
607
+ def __sub__(self, other):
608
+ if not isinstance(other, Set):
609
+ if not isinstance(other, Iterable):
610
+ return NotImplemented
611
+ other = self._from_iterable(other)
612
+ return self._from_iterable(value for value in self
613
+ if value not in other)
614
+
615
+ def __rsub__(self, other):
616
+ if not isinstance(other, Set):
617
+ if not isinstance(other, Iterable):
618
+ return NotImplemented
619
+ other = self._from_iterable(other)
620
+ return self._from_iterable(value for value in other
621
+ if value not in self)
622
+
623
+ def __xor__(self, other):
624
+ if not isinstance(other, Set):
625
+ if not isinstance(other, Iterable):
626
+ return NotImplemented
627
+ other = self._from_iterable(other)
628
+ return (self - other) | (other - self)
629
+
630
+ __rxor__ = __xor__
631
+
632
+ def _hash(self):
633
+ """Compute the hash value of a set.
634
+
635
+ Note that we don't define __hash__: not all sets are hashable.
636
+ But if you define a hashable set type, its __hash__ should
637
+ call this function.
638
+
639
+ This must be compatible __eq__.
640
+
641
+ All sets ought to compare equal if they contain the same
642
+ elements, regardless of how they are implemented, and
643
+ regardless of the order of the elements; so there's not much
644
+ freedom for __eq__ or __hash__. We match the algorithm used
645
+ by the built-in frozenset type.
646
+ """
647
+ MAX = sys.maxsize
648
+ MASK = 2 * MAX + 1
649
+ n = len(self)
650
+ h = 1927868237 * (n + 1)
651
+ h &= MASK
652
+ for x in self:
653
+ hx = hash(x)
654
+ h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
655
+ h &= MASK
656
+ h ^= (h >> 11) ^ (h >> 25)
657
+ h = h * 69069 + 907133923
658
+ h &= MASK
659
+ if h > MAX:
660
+ h -= MASK + 1
661
+ if h == -1:
662
+ h = 590923713
663
+ return h
664
+
665
+
666
+ Set.register(frozenset)
667
+
668
+
669
+ class MutableSet(Set):
670
+ """A mutable set is a finite, iterable container.
671
+
672
+ This class provides concrete generic implementations of all
673
+ methods except for __contains__, __iter__, __len__,
674
+ add(), and discard().
675
+
676
+ To override the comparisons (presumably for speed, as the
677
+ semantics are fixed), all you have to do is redefine __le__ and
678
+ then the other operations will automatically follow suit.
679
+ """
680
+
681
+ __slots__ = ()
682
+
683
+ @abstractmethod
684
+ def add(self, value):
685
+ """Add an element."""
686
+ raise NotImplementedError
687
+
688
+ @abstractmethod
689
+ def discard(self, value):
690
+ """Remove an element. Do not raise an exception if absent."""
691
+ raise NotImplementedError
692
+
693
+ def remove(self, value):
694
+ """Remove an element. If not a member, raise a KeyError."""
695
+ if value not in self:
696
+ raise KeyError(value)
697
+ self.discard(value)
698
+
699
+ def pop(self):
700
+ """Return the popped value. Raise KeyError if empty."""
701
+ it = iter(self)
702
+ try:
703
+ value = next(it)
704
+ except StopIteration:
705
+ raise KeyError from None
706
+ self.discard(value)
707
+ return value
708
+
709
+ def clear(self):
710
+ """This is slow (creates N new iterators!) but effective."""
711
+ try:
712
+ while True:
713
+ self.pop()
714
+ except KeyError:
715
+ pass
716
+
717
+ def __ior__(self, it):
718
+ for value in it:
719
+ self.add(value)
720
+ return self
721
+
722
+ def __iand__(self, it):
723
+ for value in (self - it):
724
+ self.discard(value)
725
+ return self
726
+
727
+ def __ixor__(self, it):
728
+ if it is self:
729
+ self.clear()
730
+ else:
731
+ if not isinstance(it, Set):
732
+ it = self._from_iterable(it)
733
+ for value in it:
734
+ if value in self:
735
+ self.discard(value)
736
+ else:
737
+ self.add(value)
738
+ return self
739
+
740
+ def __isub__(self, it):
741
+ if it is self:
742
+ self.clear()
743
+ else:
744
+ for value in it:
745
+ self.discard(value)
746
+ return self
747
+
748
+
749
+ MutableSet.register(set)
750
+
751
+
752
+ ### MAPPINGS ###
753
+
754
+ class Mapping(Collection):
755
+ """A Mapping is a generic container for associating key/value
756
+ pairs.
757
+
758
+ This class provides concrete generic implementations of all
759
+ methods except for __getitem__, __iter__, and __len__.
760
+ """
761
+
762
+ __slots__ = ()
763
+
764
+ # Tell ABCMeta.__new__ that this class should have TPFLAGS_MAPPING set.
765
+ __abc_tpflags__ = 1 << 6 # Py_TPFLAGS_MAPPING
766
+
767
+ @abstractmethod
768
+ def __getitem__(self, key):
769
+ raise KeyError
770
+
771
+ def get(self, key, default=None):
772
+ 'D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.'
773
+ try:
774
+ return self[key]
775
+ except KeyError:
776
+ return default
777
+
778
+ def __contains__(self, key):
779
+ try:
780
+ self[key]
781
+ except KeyError:
782
+ return False
783
+ else:
784
+ return True
785
+
786
+ def keys(self):
787
+ "D.keys() -> a set-like object providing a view on D's keys"
788
+ return KeysView(self)
789
+
790
+ def items(self):
791
+ "D.items() -> a set-like object providing a view on D's items"
792
+ return ItemsView(self)
793
+
794
+ def values(self):
795
+ "D.values() -> an object providing a view on D's values"
796
+ return ValuesView(self)
797
+
798
+ def __eq__(self, other):
799
+ if not isinstance(other, Mapping):
800
+ return NotImplemented
801
+ return dict(self.items()) == dict(other.items())
802
+
803
+ __reversed__ = None
804
+
805
+ Mapping.register(mappingproxy)
806
+
807
+
808
+ class MappingView(Sized):
809
+
810
+ __slots__ = '_mapping',
811
+
812
+ def __init__(self, mapping):
813
+ self._mapping = mapping
814
+
815
+ def __len__(self):
816
+ return len(self._mapping)
817
+
818
+ def __repr__(self):
819
+ return '{0.__class__.__name__}({0._mapping!r})'.format(self)
820
+
821
+ __class_getitem__ = classmethod(GenericAlias)
822
+
823
+
824
+ class KeysView(MappingView, Set):
825
+
826
+ __slots__ = ()
827
+
828
+ @classmethod
829
+ def _from_iterable(cls, it):
830
+ return set(it)
831
+
832
+ def __contains__(self, key):
833
+ return key in self._mapping
834
+
835
+ def __iter__(self):
836
+ yield from self._mapping
837
+
838
+
839
+ KeysView.register(dict_keys)
840
+
841
+
842
+ class ItemsView(MappingView, Set):
843
+
844
+ __slots__ = ()
845
+
846
+ @classmethod
847
+ def _from_iterable(cls, it):
848
+ return set(it)
849
+
850
+ def __contains__(self, item):
851
+ key, value = item
852
+ try:
853
+ v = self._mapping[key]
854
+ except KeyError:
855
+ return False
856
+ else:
857
+ return v is value or v == value
858
+
859
+ def __iter__(self):
860
+ for key in self._mapping:
861
+ yield (key, self._mapping[key])
862
+
863
+
864
+ ItemsView.register(dict_items)
865
+
866
+
867
+ class ValuesView(MappingView, Collection):
868
+
869
+ __slots__ = ()
870
+
871
+ def __contains__(self, value):
872
+ for key in self._mapping:
873
+ v = self._mapping[key]
874
+ if v is value or v == value:
875
+ return True
876
+ return False
877
+
878
+ def __iter__(self):
879
+ for key in self._mapping:
880
+ yield self._mapping[key]
881
+
882
+
883
+ ValuesView.register(dict_values)
884
+
885
+
886
+ class MutableMapping(Mapping):
887
+ """A MutableMapping is a generic container for associating
888
+ key/value pairs.
889
+
890
+ This class provides concrete generic implementations of all
891
+ methods except for __getitem__, __setitem__, __delitem__,
892
+ __iter__, and __len__.
893
+ """
894
+
895
+ __slots__ = ()
896
+
897
+ @abstractmethod
898
+ def __setitem__(self, key, value):
899
+ raise KeyError
900
+
901
+ @abstractmethod
902
+ def __delitem__(self, key):
903
+ raise KeyError
904
+
905
+ __marker = object()
906
+
907
+ def pop(self, key, default=__marker):
908
+ '''D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
909
+ If key is not found, d is returned if given, otherwise KeyError is raised.
910
+ '''
911
+ try:
912
+ value = self[key]
913
+ except KeyError:
914
+ if default is self.__marker:
915
+ raise
916
+ return default
917
+ else:
918
+ del self[key]
919
+ return value
920
+
921
+ def popitem(self):
922
+ '''D.popitem() -> (k, v), remove and return some (key, value) pair
923
+ as a 2-tuple; but raise KeyError if D is empty.
924
+ '''
925
+ try:
926
+ key = next(iter(self))
927
+ except StopIteration:
928
+ raise KeyError from None
929
+ value = self[key]
930
+ del self[key]
931
+ return key, value
932
+
933
+ def clear(self):
934
+ 'D.clear() -> None. Remove all items from D.'
935
+ try:
936
+ while True:
937
+ self.popitem()
938
+ except KeyError:
939
+ pass
940
+
941
+ def update(self, other=(), /, **kwds):
942
+ ''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
943
+ If E present and has a .keys() method, does: for k in E: D[k] = E[k]
944
+ If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
945
+ In either case, this is followed by: for k, v in F.items(): D[k] = v
946
+ '''
947
+ if isinstance(other, Mapping):
948
+ for key in other:
949
+ self[key] = other[key]
950
+ elif hasattr(other, "keys"):
951
+ for key in other.keys():
952
+ self[key] = other[key]
953
+ else:
954
+ for key, value in other:
955
+ self[key] = value
956
+ for key, value in kwds.items():
957
+ self[key] = value
958
+
959
+ def setdefault(self, key, default=None):
960
+ 'D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D'
961
+ try:
962
+ return self[key]
963
+ except KeyError:
964
+ self[key] = default
965
+ return default
966
+
967
+
968
+ MutableMapping.register(dict)
969
+
970
+
971
+ ### SEQUENCES ###
972
+
973
+ class Sequence(Reversible, Collection):
974
+ """All the operations on a read-only sequence.
975
+
976
+ Concrete subclasses must override __new__ or __init__,
977
+ __getitem__, and __len__.
978
+ """
979
+
980
+ __slots__ = ()
981
+
982
+ # Tell ABCMeta.__new__ that this class should have TPFLAGS_SEQUENCE set.
983
+ __abc_tpflags__ = 1 << 5 # Py_TPFLAGS_SEQUENCE
984
+
985
+ @abstractmethod
986
+ def __getitem__(self, index):
987
+ raise IndexError
988
+
989
+ def __iter__(self):
990
+ i = 0
991
+ try:
992
+ while True:
993
+ v = self[i]
994
+ yield v
995
+ i += 1
996
+ except IndexError:
997
+ return
998
+
999
+ def __contains__(self, value):
1000
+ for v in self:
1001
+ if v is value or v == value:
1002
+ return True
1003
+ return False
1004
+
1005
+ def __reversed__(self):
1006
+ for i in reversed(range(len(self))):
1007
+ yield self[i]
1008
+
1009
+ def index(self, value, start=0, stop=None):
1010
+ '''S.index(value, [start, [stop]]) -> integer -- return first index of value.
1011
+ Raises ValueError if the value is not present.
1012
+
1013
+ Supporting start and stop arguments is optional, but
1014
+ recommended.
1015
+ '''
1016
+ if start is not None and start < 0:
1017
+ start = max(len(self) + start, 0)
1018
+ if stop is not None and stop < 0:
1019
+ stop += len(self)
1020
+
1021
+ i = start
1022
+ while stop is None or i < stop:
1023
+ try:
1024
+ v = self[i]
1025
+ except IndexError:
1026
+ break
1027
+ if v is value or v == value:
1028
+ return i
1029
+ i += 1
1030
+ raise ValueError
1031
+
1032
+ def count(self, value):
1033
+ 'S.count(value) -> integer -- return number of occurrences of value'
1034
+ return sum(1 for v in self if v is value or v == value)
1035
+
1036
+ Sequence.register(tuple)
1037
+ Sequence.register(str)
1038
+ Sequence.register(range)
1039
+ Sequence.register(memoryview)
1040
+
1041
+
1042
+ class ByteString(Sequence):
1043
+ """This unifies bytes and bytearray.
1044
+
1045
+ XXX Should add all their methods.
1046
+ """
1047
+
1048
+ __slots__ = ()
1049
+
1050
+ ByteString.register(bytes)
1051
+ ByteString.register(bytearray)
1052
+
1053
+
1054
+ class MutableSequence(Sequence):
1055
+ """All the operations on a read-write sequence.
1056
+
1057
+ Concrete subclasses must provide __new__ or __init__,
1058
+ __getitem__, __setitem__, __delitem__, __len__, and insert().
1059
+ """
1060
+
1061
+ __slots__ = ()
1062
+
1063
+ @abstractmethod
1064
+ def __setitem__(self, index, value):
1065
+ raise IndexError
1066
+
1067
+ @abstractmethod
1068
+ def __delitem__(self, index):
1069
+ raise IndexError
1070
+
1071
+ @abstractmethod
1072
+ def insert(self, index, value):
1073
+ 'S.insert(index, value) -- insert value before index'
1074
+ raise IndexError
1075
+
1076
+ def append(self, value):
1077
+ 'S.append(value) -- append value to the end of the sequence'
1078
+ self.insert(len(self), value)
1079
+
1080
+ def clear(self):
1081
+ 'S.clear() -> None -- remove all items from S'
1082
+ try:
1083
+ while True:
1084
+ self.pop()
1085
+ except IndexError:
1086
+ pass
1087
+
1088
+ def reverse(self):
1089
+ 'S.reverse() -- reverse *IN PLACE*'
1090
+ n = len(self)
1091
+ for i in range(n//2):
1092
+ self[i], self[n-i-1] = self[n-i-1], self[i]
1093
+
1094
+ def extend(self, values):
1095
+ 'S.extend(iterable) -- extend sequence by appending elements from the iterable'
1096
+ if values is self:
1097
+ values = list(values)
1098
+ for v in values:
1099
+ self.append(v)
1100
+
1101
+ def pop(self, index=-1):
1102
+ '''S.pop([index]) -> item -- remove and return item at index (default last).
1103
+ Raise IndexError if list is empty or index is out of range.
1104
+ '''
1105
+ v = self[index]
1106
+ del self[index]
1107
+ return v
1108
+
1109
+ def remove(self, value):
1110
+ '''S.remove(value) -- remove first occurrence of value.
1111
+ Raise ValueError if the value is not present.
1112
+ '''
1113
+ del self[self.index(value)]
1114
+
1115
+ def __iadd__(self, values):
1116
+ self.extend(values)
1117
+ return self
1118
+
1119
+
1120
+ MutableSequence.register(list)
1121
+ MutableSequence.register(bytearray) # Multiply inheriting, see ByteString
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_compat_pickle.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This module is used to map the old Python 2 names to the new names used in
2
+ # Python 3 for the pickle module. This needed to make pickle streams
3
+ # generated with Python 2 loadable by Python 3.
4
+
5
+ # This is a copy of lib2to3.fixes.fix_imports.MAPPING. We cannot import
6
+ # lib2to3 and use the mapping defined there, because lib2to3 uses pickle.
7
+ # Thus, this could cause the module to be imported recursively.
8
+ IMPORT_MAPPING = {
9
+ '__builtin__' : 'builtins',
10
+ 'copy_reg': 'copyreg',
11
+ 'Queue': 'queue',
12
+ 'SocketServer': 'socketserver',
13
+ 'ConfigParser': 'configparser',
14
+ 'repr': 'reprlib',
15
+ 'tkFileDialog': 'tkinter.filedialog',
16
+ 'tkSimpleDialog': 'tkinter.simpledialog',
17
+ 'tkColorChooser': 'tkinter.colorchooser',
18
+ 'tkCommonDialog': 'tkinter.commondialog',
19
+ 'Dialog': 'tkinter.dialog',
20
+ 'Tkdnd': 'tkinter.dnd',
21
+ 'tkFont': 'tkinter.font',
22
+ 'tkMessageBox': 'tkinter.messagebox',
23
+ 'ScrolledText': 'tkinter.scrolledtext',
24
+ 'Tkconstants': 'tkinter.constants',
25
+ 'Tix': 'tkinter.tix',
26
+ 'ttk': 'tkinter.ttk',
27
+ 'Tkinter': 'tkinter',
28
+ 'markupbase': '_markupbase',
29
+ '_winreg': 'winreg',
30
+ 'thread': '_thread',
31
+ 'dummy_thread': '_dummy_thread',
32
+ 'dbhash': 'dbm.bsd',
33
+ 'dumbdbm': 'dbm.dumb',
34
+ 'dbm': 'dbm.ndbm',
35
+ 'gdbm': 'dbm.gnu',
36
+ 'xmlrpclib': 'xmlrpc.client',
37
+ 'SimpleXMLRPCServer': 'xmlrpc.server',
38
+ 'httplib': 'http.client',
39
+ 'htmlentitydefs' : 'html.entities',
40
+ 'HTMLParser' : 'html.parser',
41
+ 'Cookie': 'http.cookies',
42
+ 'cookielib': 'http.cookiejar',
43
+ 'BaseHTTPServer': 'http.server',
44
+ 'test.test_support': 'test.support',
45
+ 'commands': 'subprocess',
46
+ 'urlparse' : 'urllib.parse',
47
+ 'robotparser' : 'urllib.robotparser',
48
+ 'urllib2': 'urllib.request',
49
+ 'anydbm': 'dbm',
50
+ '_abcoll' : 'collections.abc',
51
+ }
52
+
53
+
54
+ # This contains rename rules that are easy to handle. We ignore the more
55
+ # complex stuff (e.g. mapping the names in the urllib and types modules).
56
+ # These rules should be run before import names are fixed.
57
+ NAME_MAPPING = {
58
+ ('__builtin__', 'xrange'): ('builtins', 'range'),
59
+ ('__builtin__', 'reduce'): ('functools', 'reduce'),
60
+ ('__builtin__', 'intern'): ('sys', 'intern'),
61
+ ('__builtin__', 'unichr'): ('builtins', 'chr'),
62
+ ('__builtin__', 'unicode'): ('builtins', 'str'),
63
+ ('__builtin__', 'long'): ('builtins', 'int'),
64
+ ('itertools', 'izip'): ('builtins', 'zip'),
65
+ ('itertools', 'imap'): ('builtins', 'map'),
66
+ ('itertools', 'ifilter'): ('builtins', 'filter'),
67
+ ('itertools', 'ifilterfalse'): ('itertools', 'filterfalse'),
68
+ ('itertools', 'izip_longest'): ('itertools', 'zip_longest'),
69
+ ('UserDict', 'IterableUserDict'): ('collections', 'UserDict'),
70
+ ('UserList', 'UserList'): ('collections', 'UserList'),
71
+ ('UserString', 'UserString'): ('collections', 'UserString'),
72
+ ('whichdb', 'whichdb'): ('dbm', 'whichdb'),
73
+ ('_socket', 'fromfd'): ('socket', 'fromfd'),
74
+ ('_multiprocessing', 'Connection'): ('multiprocessing.connection', 'Connection'),
75
+ ('multiprocessing.process', 'Process'): ('multiprocessing.context', 'Process'),
76
+ ('multiprocessing.forking', 'Popen'): ('multiprocessing.popen_fork', 'Popen'),
77
+ ('urllib', 'ContentTooShortError'): ('urllib.error', 'ContentTooShortError'),
78
+ ('urllib', 'getproxies'): ('urllib.request', 'getproxies'),
79
+ ('urllib', 'pathname2url'): ('urllib.request', 'pathname2url'),
80
+ ('urllib', 'quote_plus'): ('urllib.parse', 'quote_plus'),
81
+ ('urllib', 'quote'): ('urllib.parse', 'quote'),
82
+ ('urllib', 'unquote_plus'): ('urllib.parse', 'unquote_plus'),
83
+ ('urllib', 'unquote'): ('urllib.parse', 'unquote'),
84
+ ('urllib', 'url2pathname'): ('urllib.request', 'url2pathname'),
85
+ ('urllib', 'urlcleanup'): ('urllib.request', 'urlcleanup'),
86
+ ('urllib', 'urlencode'): ('urllib.parse', 'urlencode'),
87
+ ('urllib', 'urlopen'): ('urllib.request', 'urlopen'),
88
+ ('urllib', 'urlretrieve'): ('urllib.request', 'urlretrieve'),
89
+ ('urllib2', 'HTTPError'): ('urllib.error', 'HTTPError'),
90
+ ('urllib2', 'URLError'): ('urllib.error', 'URLError'),
91
+ }
92
+
93
+ PYTHON2_EXCEPTIONS = (
94
+ "ArithmeticError",
95
+ "AssertionError",
96
+ "AttributeError",
97
+ "BaseException",
98
+ "BufferError",
99
+ "BytesWarning",
100
+ "DeprecationWarning",
101
+ "EOFError",
102
+ "EnvironmentError",
103
+ "Exception",
104
+ "FloatingPointError",
105
+ "FutureWarning",
106
+ "GeneratorExit",
107
+ "IOError",
108
+ "ImportError",
109
+ "ImportWarning",
110
+ "IndentationError",
111
+ "IndexError",
112
+ "KeyError",
113
+ "KeyboardInterrupt",
114
+ "LookupError",
115
+ "MemoryError",
116
+ "NameError",
117
+ "NotImplementedError",
118
+ "OSError",
119
+ "OverflowError",
120
+ "PendingDeprecationWarning",
121
+ "ReferenceError",
122
+ "RuntimeError",
123
+ "RuntimeWarning",
124
+ # StandardError is gone in Python 3, so we map it to Exception
125
+ "StopIteration",
126
+ "SyntaxError",
127
+ "SyntaxWarning",
128
+ "SystemError",
129
+ "SystemExit",
130
+ "TabError",
131
+ "TypeError",
132
+ "UnboundLocalError",
133
+ "UnicodeDecodeError",
134
+ "UnicodeEncodeError",
135
+ "UnicodeError",
136
+ "UnicodeTranslateError",
137
+ "UnicodeWarning",
138
+ "UserWarning",
139
+ "ValueError",
140
+ "Warning",
141
+ "ZeroDivisionError",
142
+ )
143
+
144
+ try:
145
+ WindowsError
146
+ except NameError:
147
+ pass
148
+ else:
149
+ PYTHON2_EXCEPTIONS += ("WindowsError",)
150
+
151
+ for excname in PYTHON2_EXCEPTIONS:
152
+ NAME_MAPPING[("exceptions", excname)] = ("builtins", excname)
153
+
154
+ MULTIPROCESSING_EXCEPTIONS = (
155
+ 'AuthenticationError',
156
+ 'BufferTooShort',
157
+ 'ProcessError',
158
+ 'TimeoutError',
159
+ )
160
+
161
+ for excname in MULTIPROCESSING_EXCEPTIONS:
162
+ NAME_MAPPING[("multiprocessing", excname)] = ("multiprocessing.context", excname)
163
+
164
+ # Same, but for 3.x to 2.x
165
+ REVERSE_IMPORT_MAPPING = dict((v, k) for (k, v) in IMPORT_MAPPING.items())
166
+ assert len(REVERSE_IMPORT_MAPPING) == len(IMPORT_MAPPING)
167
+ REVERSE_NAME_MAPPING = dict((v, k) for (k, v) in NAME_MAPPING.items())
168
+ assert len(REVERSE_NAME_MAPPING) == len(NAME_MAPPING)
169
+
170
+ # Non-mutual mappings.
171
+
172
+ IMPORT_MAPPING.update({
173
+ 'cPickle': 'pickle',
174
+ '_elementtree': 'xml.etree.ElementTree',
175
+ 'FileDialog': 'tkinter.filedialog',
176
+ 'SimpleDialog': 'tkinter.simpledialog',
177
+ 'DocXMLRPCServer': 'xmlrpc.server',
178
+ 'SimpleHTTPServer': 'http.server',
179
+ 'CGIHTTPServer': 'http.server',
180
+ # For compatibility with broken pickles saved in old Python 3 versions
181
+ 'UserDict': 'collections',
182
+ 'UserList': 'collections',
183
+ 'UserString': 'collections',
184
+ 'whichdb': 'dbm',
185
+ 'StringIO': 'io',
186
+ 'cStringIO': 'io',
187
+ })
188
+
189
+ REVERSE_IMPORT_MAPPING.update({
190
+ '_bz2': 'bz2',
191
+ '_dbm': 'dbm',
192
+ '_functools': 'functools',
193
+ '_gdbm': 'gdbm',
194
+ '_pickle': 'pickle',
195
+ })
196
+
197
+ NAME_MAPPING.update({
198
+ ('__builtin__', 'basestring'): ('builtins', 'str'),
199
+ ('exceptions', 'StandardError'): ('builtins', 'Exception'),
200
+ ('UserDict', 'UserDict'): ('collections', 'UserDict'),
201
+ ('socket', '_socketobject'): ('socket', 'SocketType'),
202
+ })
203
+
204
+ REVERSE_NAME_MAPPING.update({
205
+ ('_functools', 'reduce'): ('__builtin__', 'reduce'),
206
+ ('tkinter.filedialog', 'FileDialog'): ('FileDialog', 'FileDialog'),
207
+ ('tkinter.filedialog', 'LoadFileDialog'): ('FileDialog', 'LoadFileDialog'),
208
+ ('tkinter.filedialog', 'SaveFileDialog'): ('FileDialog', 'SaveFileDialog'),
209
+ ('tkinter.simpledialog', 'SimpleDialog'): ('SimpleDialog', 'SimpleDialog'),
210
+ ('xmlrpc.server', 'ServerHTMLDoc'): ('DocXMLRPCServer', 'ServerHTMLDoc'),
211
+ ('xmlrpc.server', 'XMLRPCDocGenerator'):
212
+ ('DocXMLRPCServer', 'XMLRPCDocGenerator'),
213
+ ('xmlrpc.server', 'DocXMLRPCRequestHandler'):
214
+ ('DocXMLRPCServer', 'DocXMLRPCRequestHandler'),
215
+ ('xmlrpc.server', 'DocXMLRPCServer'):
216
+ ('DocXMLRPCServer', 'DocXMLRPCServer'),
217
+ ('xmlrpc.server', 'DocCGIXMLRPCRequestHandler'):
218
+ ('DocXMLRPCServer', 'DocCGIXMLRPCRequestHandler'),
219
+ ('http.server', 'SimpleHTTPRequestHandler'):
220
+ ('SimpleHTTPServer', 'SimpleHTTPRequestHandler'),
221
+ ('http.server', 'CGIHTTPRequestHandler'):
222
+ ('CGIHTTPServer', 'CGIHTTPRequestHandler'),
223
+ ('_socket', 'socket'): ('socket', '_socketobject'),
224
+ })
225
+
226
+ PYTHON3_OSERROR_EXCEPTIONS = (
227
+ 'BrokenPipeError',
228
+ 'ChildProcessError',
229
+ 'ConnectionAbortedError',
230
+ 'ConnectionError',
231
+ 'ConnectionRefusedError',
232
+ 'ConnectionResetError',
233
+ 'FileExistsError',
234
+ 'FileNotFoundError',
235
+ 'InterruptedError',
236
+ 'IsADirectoryError',
237
+ 'NotADirectoryError',
238
+ 'PermissionError',
239
+ 'ProcessLookupError',
240
+ 'TimeoutError',
241
+ )
242
+
243
+ for excname in PYTHON3_OSERROR_EXCEPTIONS:
244
+ REVERSE_NAME_MAPPING[('builtins', excname)] = ('exceptions', 'OSError')
245
+
246
+ PYTHON3_IMPORTERROR_EXCEPTIONS = (
247
+ 'ModuleNotFoundError',
248
+ )
249
+
250
+ for excname in PYTHON3_IMPORTERROR_EXCEPTIONS:
251
+ REVERSE_NAME_MAPPING[('builtins', excname)] = ('exceptions', 'ImportError')
252
+ del excname
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_compression.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Internal classes used by the gzip, lzma and bz2 modules"""
2
+
3
+ import io
4
+ import sys
5
+
6
+ BUFFER_SIZE = io.DEFAULT_BUFFER_SIZE # Compressed data read chunk size
7
+
8
+
9
+ class BaseStream(io.BufferedIOBase):
10
+ """Mode-checking helper functions."""
11
+
12
+ def _check_not_closed(self):
13
+ if self.closed:
14
+ raise ValueError("I/O operation on closed file")
15
+
16
+ def _check_can_read(self):
17
+ if not self.readable():
18
+ raise io.UnsupportedOperation("File not open for reading")
19
+
20
+ def _check_can_write(self):
21
+ if not self.writable():
22
+ raise io.UnsupportedOperation("File not open for writing")
23
+
24
+ def _check_can_seek(self):
25
+ if not self.readable():
26
+ raise io.UnsupportedOperation("Seeking is only supported "
27
+ "on files open for reading")
28
+ if not self.seekable():
29
+ raise io.UnsupportedOperation("The underlying file object "
30
+ "does not support seeking")
31
+
32
+
33
+ class DecompressReader(io.RawIOBase):
34
+ """Adapts the decompressor API to a RawIOBase reader API"""
35
+
36
+ def readable(self):
37
+ return True
38
+
39
+ def __init__(self, fp, decomp_factory, trailing_error=(), **decomp_args):
40
+ self._fp = fp
41
+ self._eof = False
42
+ self._pos = 0 # Current offset in decompressed stream
43
+
44
+ # Set to size of decompressed stream once it is known, for SEEK_END
45
+ self._size = -1
46
+
47
+ # Save the decompressor factory and arguments.
48
+ # If the file contains multiple compressed streams, each
49
+ # stream will need a separate decompressor object. A new decompressor
50
+ # object is also needed when implementing a backwards seek().
51
+ self._decomp_factory = decomp_factory
52
+ self._decomp_args = decomp_args
53
+ self._decompressor = self._decomp_factory(**self._decomp_args)
54
+
55
+ # Exception class to catch from decompressor signifying invalid
56
+ # trailing data to ignore
57
+ self._trailing_error = trailing_error
58
+
59
+ def close(self):
60
+ self._decompressor = None
61
+ return super().close()
62
+
63
+ def seekable(self):
64
+ return self._fp.seekable()
65
+
66
+ def readinto(self, b):
67
+ with memoryview(b) as view, view.cast("B") as byte_view:
68
+ data = self.read(len(byte_view))
69
+ byte_view[:len(data)] = data
70
+ return len(data)
71
+
72
+ def read(self, size=-1):
73
+ if size < 0:
74
+ return self.readall()
75
+
76
+ if not size or self._eof:
77
+ return b""
78
+ data = None # Default if EOF is encountered
79
+ # Depending on the input data, our call to the decompressor may not
80
+ # return any data. In this case, try again after reading another block.
81
+ while True:
82
+ if self._decompressor.eof:
83
+ rawblock = (self._decompressor.unused_data or
84
+ self._fp.read(BUFFER_SIZE))
85
+ if not rawblock:
86
+ break
87
+ # Continue to next stream.
88
+ self._decompressor = self._decomp_factory(
89
+ **self._decomp_args)
90
+ try:
91
+ data = self._decompressor.decompress(rawblock, size)
92
+ except self._trailing_error:
93
+ # Trailing data isn't a valid compressed stream; ignore it.
94
+ break
95
+ else:
96
+ if self._decompressor.needs_input:
97
+ rawblock = self._fp.read(BUFFER_SIZE)
98
+ if not rawblock:
99
+ raise EOFError("Compressed file ended before the "
100
+ "end-of-stream marker was reached")
101
+ else:
102
+ rawblock = b""
103
+ data = self._decompressor.decompress(rawblock, size)
104
+ if data:
105
+ break
106
+ if not data:
107
+ self._eof = True
108
+ self._size = self._pos
109
+ return b""
110
+ self._pos += len(data)
111
+ return data
112
+
113
+ def readall(self):
114
+ chunks = []
115
+ # sys.maxsize means the max length of output buffer is unlimited,
116
+ # so that the whole input buffer can be decompressed within one
117
+ # .decompress() call.
118
+ while data := self.read(sys.maxsize):
119
+ chunks.append(data)
120
+
121
+ return b"".join(chunks)
122
+
123
+ # Rewind the file to the beginning of the data stream.
124
+ def _rewind(self):
125
+ self._fp.seek(0)
126
+ self._eof = False
127
+ self._pos = 0
128
+ self._decompressor = self._decomp_factory(**self._decomp_args)
129
+
130
+ def seek(self, offset, whence=io.SEEK_SET):
131
+ # Recalculate offset as an absolute file position.
132
+ if whence == io.SEEK_SET:
133
+ pass
134
+ elif whence == io.SEEK_CUR:
135
+ offset = self._pos + offset
136
+ elif whence == io.SEEK_END:
137
+ # Seeking relative to EOF - we need to know the file's size.
138
+ if self._size < 0:
139
+ while self.read(io.DEFAULT_BUFFER_SIZE):
140
+ pass
141
+ offset = self._size + offset
142
+ else:
143
+ raise ValueError("Invalid value for whence: {}".format(whence))
144
+
145
+ # Make it so that offset is the number of bytes to skip forward.
146
+ if offset < self._pos:
147
+ self._rewind()
148
+ else:
149
+ offset -= self._pos
150
+
151
+ # Read and discard data until we reach the desired position.
152
+ while offset > 0:
153
+ data = self.read(min(io.DEFAULT_BUFFER_SIZE, offset))
154
+ if not data:
155
+ break
156
+ offset -= len(data)
157
+
158
+ return self._pos
159
+
160
+ def tell(self):
161
+ """Return the current file position."""
162
+ return self._pos
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_markupbase.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared support for scanning document type declarations in HTML and XHTML.
2
+
3
+ This module is used as a foundation for the html.parser module. It has no
4
+ documented public API and should not be used directly.
5
+
6
+ """
7
+
8
+ import re
9
+
10
+ _declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9]*\s*').match
11
+ _declstringlit_match = re.compile(r'(\'[^\']*\'|"[^"]*")\s*').match
12
+ _commentclose = re.compile(r'--\s*>')
13
+ _markedsectionclose = re.compile(r']\s*]\s*>')
14
+
15
+ # An analysis of the MS-Word extensions is available at
16
+ # http://www.planetpublish.com/xmlarena/xap/Thursday/WordtoXML.pdf
17
+
18
+ _msmarkedsectionclose = re.compile(r']\s*>')
19
+
20
+ del re
21
+
22
+
23
+ class ParserBase:
24
+ """Parser base class which provides some common support methods used
25
+ by the SGML/HTML and XHTML parsers."""
26
+
27
+ def __init__(self):
28
+ if self.__class__ is ParserBase:
29
+ raise RuntimeError(
30
+ "_markupbase.ParserBase must be subclassed")
31
+
32
+ def reset(self):
33
+ self.lineno = 1
34
+ self.offset = 0
35
+
36
+ def getpos(self):
37
+ """Return current line number and offset."""
38
+ return self.lineno, self.offset
39
+
40
+ # Internal -- update line number and offset. This should be
41
+ # called for each piece of data exactly once, in order -- in other
42
+ # words the concatenation of all the input strings to this
43
+ # function should be exactly the entire input.
44
+ def updatepos(self, i, j):
45
+ if i >= j:
46
+ return j
47
+ rawdata = self.rawdata
48
+ nlines = rawdata.count("\n", i, j)
49
+ if nlines:
50
+ self.lineno = self.lineno + nlines
51
+ pos = rawdata.rindex("\n", i, j) # Should not fail
52
+ self.offset = j-(pos+1)
53
+ else:
54
+ self.offset = self.offset + j-i
55
+ return j
56
+
57
+ _decl_otherchars = ''
58
+
59
+ # Internal -- parse declaration (for use by subclasses).
60
+ def parse_declaration(self, i):
61
+ # This is some sort of declaration; in "HTML as
62
+ # deployed," this should only be the document type
63
+ # declaration ("<!DOCTYPE html...>").
64
+ # ISO 8879:1986, however, has more complex
65
+ # declaration syntax for elements in <!...>, including:
66
+ # --comment--
67
+ # [marked section]
68
+ # name in the following list: ENTITY, DOCTYPE, ELEMENT,
69
+ # ATTLIST, NOTATION, SHORTREF, USEMAP,
70
+ # LINKTYPE, LINK, IDLINK, USELINK, SYSTEM
71
+ rawdata = self.rawdata
72
+ j = i + 2
73
+ assert rawdata[i:j] == "<!", "unexpected call to parse_declaration"
74
+ if rawdata[j:j+1] == ">":
75
+ # the empty comment <!>
76
+ return j + 1
77
+ if rawdata[j:j+1] in ("-", ""):
78
+ # Start of comment followed by buffer boundary,
79
+ # or just a buffer boundary.
80
+ return -1
81
+ # A simple, practical version could look like: ((name|stringlit) S*) + '>'
82
+ n = len(rawdata)
83
+ if rawdata[j:j+2] == '--': #comment
84
+ # Locate --.*-- as the body of the comment
85
+ return self.parse_comment(i)
86
+ elif rawdata[j] == '[': #marked section
87
+ # Locate [statusWord [...arbitrary SGML...]] as the body of the marked section
88
+ # Where statusWord is one of TEMP, CDATA, IGNORE, INCLUDE, RCDATA
89
+ # Note that this is extended by Microsoft Office "Save as Web" function
90
+ # to include [if...] and [endif].
91
+ return self.parse_marked_section(i)
92
+ else: #all other declaration elements
93
+ decltype, j = self._scan_name(j, i)
94
+ if j < 0:
95
+ return j
96
+ if decltype == "doctype":
97
+ self._decl_otherchars = ''
98
+ while j < n:
99
+ c = rawdata[j]
100
+ if c == ">":
101
+ # end of declaration syntax
102
+ data = rawdata[i+2:j]
103
+ if decltype == "doctype":
104
+ self.handle_decl(data)
105
+ else:
106
+ # According to the HTML5 specs sections "8.2.4.44 Bogus
107
+ # comment state" and "8.2.4.45 Markup declaration open
108
+ # state", a comment token should be emitted.
109
+ # Calling unknown_decl provides more flexibility though.
110
+ self.unknown_decl(data)
111
+ return j + 1
112
+ if c in "\"'":
113
+ m = _declstringlit_match(rawdata, j)
114
+ if not m:
115
+ return -1 # incomplete
116
+ j = m.end()
117
+ elif c in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ":
118
+ name, j = self._scan_name(j, i)
119
+ elif c in self._decl_otherchars:
120
+ j = j + 1
121
+ elif c == "[":
122
+ # this could be handled in a separate doctype parser
123
+ if decltype == "doctype":
124
+ j = self._parse_doctype_subset(j + 1, i)
125
+ elif decltype in {"attlist", "linktype", "link", "element"}:
126
+ # must tolerate []'d groups in a content model in an element declaration
127
+ # also in data attribute specifications of attlist declaration
128
+ # also link type declaration subsets in linktype declarations
129
+ # also link attribute specification lists in link declarations
130
+ raise AssertionError("unsupported '[' char in %s declaration" % decltype)
131
+ else:
132
+ raise AssertionError("unexpected '[' char in declaration")
133
+ else:
134
+ raise AssertionError("unexpected %r char in declaration" % rawdata[j])
135
+ if j < 0:
136
+ return j
137
+ return -1 # incomplete
138
+
139
+ # Internal -- parse a marked section
140
+ # Override this to handle MS-word extension syntax <![if word]>content<![endif]>
141
+ def parse_marked_section(self, i, report=1):
142
+ rawdata= self.rawdata
143
+ assert rawdata[i:i+3] == '<![', "unexpected call to parse_marked_section()"
144
+ sectName, j = self._scan_name( i+3, i )
145
+ if j < 0:
146
+ return j
147
+ if sectName in {"temp", "cdata", "ignore", "include", "rcdata"}:
148
+ # look for standard ]]> ending
149
+ match= _markedsectionclose.search(rawdata, i+3)
150
+ elif sectName in {"if", "else", "endif"}:
151
+ # look for MS Office ]> ending
152
+ match= _msmarkedsectionclose.search(rawdata, i+3)
153
+ else:
154
+ raise AssertionError(
155
+ 'unknown status keyword %r in marked section' % rawdata[i+3:j]
156
+ )
157
+ if not match:
158
+ return -1
159
+ if report:
160
+ j = match.start(0)
161
+ self.unknown_decl(rawdata[i+3: j])
162
+ return match.end(0)
163
+
164
+ # Internal -- parse comment, return length or -1 if not terminated
165
+ def parse_comment(self, i, report=1):
166
+ rawdata = self.rawdata
167
+ if rawdata[i:i+4] != '<!--':
168
+ raise AssertionError('unexpected call to parse_comment()')
169
+ match = _commentclose.search(rawdata, i+4)
170
+ if not match:
171
+ return -1
172
+ if report:
173
+ j = match.start(0)
174
+ self.handle_comment(rawdata[i+4: j])
175
+ return match.end(0)
176
+
177
+ # Internal -- scan past the internal subset in a <!DOCTYPE declaration,
178
+ # returning the index just past any whitespace following the trailing ']'.
179
+ def _parse_doctype_subset(self, i, declstartpos):
180
+ rawdata = self.rawdata
181
+ n = len(rawdata)
182
+ j = i
183
+ while j < n:
184
+ c = rawdata[j]
185
+ if c == "<":
186
+ s = rawdata[j:j+2]
187
+ if s == "<":
188
+ # end of buffer; incomplete
189
+ return -1
190
+ if s != "<!":
191
+ self.updatepos(declstartpos, j + 1)
192
+ raise AssertionError(
193
+ "unexpected char in internal subset (in %r)" % s
194
+ )
195
+ if (j + 2) == n:
196
+ # end of buffer; incomplete
197
+ return -1
198
+ if (j + 4) > n:
199
+ # end of buffer; incomplete
200
+ return -1
201
+ if rawdata[j:j+4] == "<!--":
202
+ j = self.parse_comment(j, report=0)
203
+ if j < 0:
204
+ return j
205
+ continue
206
+ name, j = self._scan_name(j + 2, declstartpos)
207
+ if j == -1:
208
+ return -1
209
+ if name not in {"attlist", "element", "entity", "notation"}:
210
+ self.updatepos(declstartpos, j + 2)
211
+ raise AssertionError(
212
+ "unknown declaration %r in internal subset" % name
213
+ )
214
+ # handle the individual names
215
+ meth = getattr(self, "_parse_doctype_" + name)
216
+ j = meth(j, declstartpos)
217
+ if j < 0:
218
+ return j
219
+ elif c == "%":
220
+ # parameter entity reference
221
+ if (j + 1) == n:
222
+ # end of buffer; incomplete
223
+ return -1
224
+ s, j = self._scan_name(j + 1, declstartpos)
225
+ if j < 0:
226
+ return j
227
+ if rawdata[j] == ";":
228
+ j = j + 1
229
+ elif c == "]":
230
+ j = j + 1
231
+ while j < n and rawdata[j].isspace():
232
+ j = j + 1
233
+ if j < n:
234
+ if rawdata[j] == ">":
235
+ return j
236
+ self.updatepos(declstartpos, j)
237
+ raise AssertionError("unexpected char after internal subset")
238
+ else:
239
+ return -1
240
+ elif c.isspace():
241
+ j = j + 1
242
+ else:
243
+ self.updatepos(declstartpos, j)
244
+ raise AssertionError("unexpected char %r in internal subset" % c)
245
+ # end of buffer reached
246
+ return -1
247
+
248
+ # Internal -- scan past <!ELEMENT declarations
249
+ def _parse_doctype_element(self, i, declstartpos):
250
+ name, j = self._scan_name(i, declstartpos)
251
+ if j == -1:
252
+ return -1
253
+ # style content model; just skip until '>'
254
+ rawdata = self.rawdata
255
+ if '>' in rawdata[j:]:
256
+ return rawdata.find(">", j) + 1
257
+ return -1
258
+
259
+ # Internal -- scan past <!ATTLIST declarations
260
+ def _parse_doctype_attlist(self, i, declstartpos):
261
+ rawdata = self.rawdata
262
+ name, j = self._scan_name(i, declstartpos)
263
+ c = rawdata[j:j+1]
264
+ if c == "":
265
+ return -1
266
+ if c == ">":
267
+ return j + 1
268
+ while 1:
269
+ # scan a series of attribute descriptions; simplified:
270
+ # name type [value] [#constraint]
271
+ name, j = self._scan_name(j, declstartpos)
272
+ if j < 0:
273
+ return j
274
+ c = rawdata[j:j+1]
275
+ if c == "":
276
+ return -1
277
+ if c == "(":
278
+ # an enumerated type; look for ')'
279
+ if ")" in rawdata[j:]:
280
+ j = rawdata.find(")", j) + 1
281
+ else:
282
+ return -1
283
+ while rawdata[j:j+1].isspace():
284
+ j = j + 1
285
+ if not rawdata[j:]:
286
+ # end of buffer, incomplete
287
+ return -1
288
+ else:
289
+ name, j = self._scan_name(j, declstartpos)
290
+ c = rawdata[j:j+1]
291
+ if not c:
292
+ return -1
293
+ if c in "'\"":
294
+ m = _declstringlit_match(rawdata, j)
295
+ if m:
296
+ j = m.end()
297
+ else:
298
+ return -1
299
+ c = rawdata[j:j+1]
300
+ if not c:
301
+ return -1
302
+ if c == "#":
303
+ if rawdata[j:] == "#":
304
+ # end of buffer
305
+ return -1
306
+ name, j = self._scan_name(j + 1, declstartpos)
307
+ if j < 0:
308
+ return j
309
+ c = rawdata[j:j+1]
310
+ if not c:
311
+ return -1
312
+ if c == '>':
313
+ # all done
314
+ return j + 1
315
+
316
+ # Internal -- scan past <!NOTATION declarations
317
+ def _parse_doctype_notation(self, i, declstartpos):
318
+ name, j = self._scan_name(i, declstartpos)
319
+ if j < 0:
320
+ return j
321
+ rawdata = self.rawdata
322
+ while 1:
323
+ c = rawdata[j:j+1]
324
+ if not c:
325
+ # end of buffer; incomplete
326
+ return -1
327
+ if c == '>':
328
+ return j + 1
329
+ if c in "'\"":
330
+ m = _declstringlit_match(rawdata, j)
331
+ if not m:
332
+ return -1
333
+ j = m.end()
334
+ else:
335
+ name, j = self._scan_name(j, declstartpos)
336
+ if j < 0:
337
+ return j
338
+
339
+ # Internal -- scan past <!ENTITY declarations
340
+ def _parse_doctype_entity(self, i, declstartpos):
341
+ rawdata = self.rawdata
342
+ if rawdata[i:i+1] == "%":
343
+ j = i + 1
344
+ while 1:
345
+ c = rawdata[j:j+1]
346
+ if not c:
347
+ return -1
348
+ if c.isspace():
349
+ j = j + 1
350
+ else:
351
+ break
352
+ else:
353
+ j = i
354
+ name, j = self._scan_name(j, declstartpos)
355
+ if j < 0:
356
+ return j
357
+ while 1:
358
+ c = self.rawdata[j:j+1]
359
+ if not c:
360
+ return -1
361
+ if c in "'\"":
362
+ m = _declstringlit_match(rawdata, j)
363
+ if m:
364
+ j = m.end()
365
+ else:
366
+ return -1 # incomplete
367
+ elif c == ">":
368
+ return j + 1
369
+ else:
370
+ name, j = self._scan_name(j, declstartpos)
371
+ if j < 0:
372
+ return j
373
+
374
+ # Internal -- scan a name token and the new position and the token, or
375
+ # return -1 if we've reached the end of the buffer.
376
+ def _scan_name(self, i, declstartpos):
377
+ rawdata = self.rawdata
378
+ n = len(rawdata)
379
+ if i == n:
380
+ return None, -1
381
+ m = _declname_match(rawdata, i)
382
+ if m:
383
+ s = m.group()
384
+ name = s.strip()
385
+ if (i + len(s)) == n:
386
+ return None, -1 # end of buffer
387
+ return name.lower(), m.end()
388
+ else:
389
+ self.updatepos(declstartpos, i)
390
+ raise AssertionError(
391
+ "expected name token at %r" % rawdata[declstartpos:declstartpos+20]
392
+ )
393
+
394
+ # To be overridden -- handlers for unknown objects
395
+ def unknown_decl(self, data):
396
+ pass
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_osx_support.py ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared OS X support functions."""
2
+
3
+ import os
4
+ import re
5
+ import sys
6
+
7
+ __all__ = [
8
+ 'compiler_fixup',
9
+ 'customize_config_vars',
10
+ 'customize_compiler',
11
+ 'get_platform_osx',
12
+ ]
13
+
14
+ # configuration variables that may contain universal build flags,
15
+ # like "-arch" or "-isdkroot", that may need customization for
16
+ # the user environment
17
+ _UNIVERSAL_CONFIG_VARS = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS', 'BASECFLAGS',
18
+ 'BLDSHARED', 'LDSHARED', 'CC', 'CXX',
19
+ 'PY_CFLAGS', 'PY_LDFLAGS', 'PY_CPPFLAGS',
20
+ 'PY_CORE_CFLAGS', 'PY_CORE_LDFLAGS')
21
+
22
+ # configuration variables that may contain compiler calls
23
+ _COMPILER_CONFIG_VARS = ('BLDSHARED', 'LDSHARED', 'CC', 'CXX')
24
+
25
+ # prefix added to original configuration variable names
26
+ _INITPRE = '_OSX_SUPPORT_INITIAL_'
27
+
28
+
29
+ def _find_executable(executable, path=None):
30
+ """Tries to find 'executable' in the directories listed in 'path'.
31
+
32
+ A string listing directories separated by 'os.pathsep'; defaults to
33
+ os.environ['PATH']. Returns the complete filename or None if not found.
34
+ """
35
+ if path is None:
36
+ path = os.environ['PATH']
37
+
38
+ paths = path.split(os.pathsep)
39
+ base, ext = os.path.splitext(executable)
40
+
41
+ if (sys.platform == 'win32') and (ext != '.exe'):
42
+ executable = executable + '.exe'
43
+
44
+ if not os.path.isfile(executable):
45
+ for p in paths:
46
+ f = os.path.join(p, executable)
47
+ if os.path.isfile(f):
48
+ # the file exists, we have a shot at spawn working
49
+ return f
50
+ return None
51
+ else:
52
+ return executable
53
+
54
+
55
+ def _read_output(commandstring, capture_stderr=False):
56
+ """Output from successful command execution or None"""
57
+ # Similar to os.popen(commandstring, "r").read(),
58
+ # but without actually using os.popen because that
59
+ # function is not usable during python bootstrap.
60
+ # tempfile is also not available then.
61
+ import contextlib
62
+ try:
63
+ import tempfile
64
+ fp = tempfile.NamedTemporaryFile()
65
+ except ImportError:
66
+ fp = open("/tmp/_osx_support.%s"%(
67
+ os.getpid(),), "w+b")
68
+
69
+ with contextlib.closing(fp) as fp:
70
+ if capture_stderr:
71
+ cmd = "%s >'%s' 2>&1" % (commandstring, fp.name)
72
+ else:
73
+ cmd = "%s 2>/dev/null >'%s'" % (commandstring, fp.name)
74
+ return fp.read().decode('utf-8').strip() if not os.system(cmd) else None
75
+
76
+
77
+ def _find_build_tool(toolname):
78
+ """Find a build tool on current path or using xcrun"""
79
+ return (_find_executable(toolname)
80
+ or _read_output("/usr/bin/xcrun -find %s" % (toolname,))
81
+ or ''
82
+ )
83
+
84
+ _SYSTEM_VERSION = None
85
+
86
+ def _get_system_version():
87
+ """Return the OS X system version as a string"""
88
+ # Reading this plist is a documented way to get the system
89
+ # version (see the documentation for the Gestalt Manager)
90
+ # We avoid using platform.mac_ver to avoid possible bootstrap issues during
91
+ # the build of Python itself (distutils is used to build standard library
92
+ # extensions).
93
+
94
+ global _SYSTEM_VERSION
95
+
96
+ if _SYSTEM_VERSION is None:
97
+ _SYSTEM_VERSION = ''
98
+ try:
99
+ f = open('/System/Library/CoreServices/SystemVersion.plist', encoding="utf-8")
100
+ except OSError:
101
+ # We're on a plain darwin box, fall back to the default
102
+ # behaviour.
103
+ pass
104
+ else:
105
+ try:
106
+ m = re.search(r'<key>ProductUserVisibleVersion</key>\s*'
107
+ r'<string>(.*?)</string>', f.read())
108
+ finally:
109
+ f.close()
110
+ if m is not None:
111
+ _SYSTEM_VERSION = '.'.join(m.group(1).split('.')[:2])
112
+ # else: fall back to the default behaviour
113
+
114
+ return _SYSTEM_VERSION
115
+
116
+ _SYSTEM_VERSION_TUPLE = None
117
+ def _get_system_version_tuple():
118
+ """
119
+ Return the macOS system version as a tuple
120
+
121
+ The return value is safe to use to compare
122
+ two version numbers.
123
+ """
124
+ global _SYSTEM_VERSION_TUPLE
125
+ if _SYSTEM_VERSION_TUPLE is None:
126
+ osx_version = _get_system_version()
127
+ if osx_version:
128
+ try:
129
+ _SYSTEM_VERSION_TUPLE = tuple(int(i) for i in osx_version.split('.'))
130
+ except ValueError:
131
+ _SYSTEM_VERSION_TUPLE = ()
132
+
133
+ return _SYSTEM_VERSION_TUPLE
134
+
135
+
136
+ def _remove_original_values(_config_vars):
137
+ """Remove original unmodified values for testing"""
138
+ # This is needed for higher-level cross-platform tests of get_platform.
139
+ for k in list(_config_vars):
140
+ if k.startswith(_INITPRE):
141
+ del _config_vars[k]
142
+
143
+ def _save_modified_value(_config_vars, cv, newvalue):
144
+ """Save modified and original unmodified value of configuration var"""
145
+
146
+ oldvalue = _config_vars.get(cv, '')
147
+ if (oldvalue != newvalue) and (_INITPRE + cv not in _config_vars):
148
+ _config_vars[_INITPRE + cv] = oldvalue
149
+ _config_vars[cv] = newvalue
150
+
151
+
152
+ _cache_default_sysroot = None
153
+ def _default_sysroot(cc):
154
+ """ Returns the root of the default SDK for this system, or '/' """
155
+ global _cache_default_sysroot
156
+
157
+ if _cache_default_sysroot is not None:
158
+ return _cache_default_sysroot
159
+
160
+ contents = _read_output('%s -c -E -v - </dev/null' % (cc,), True)
161
+ in_incdirs = False
162
+ for line in contents.splitlines():
163
+ if line.startswith("#include <...>"):
164
+ in_incdirs = True
165
+ elif line.startswith("End of search list"):
166
+ in_incdirs = False
167
+ elif in_incdirs:
168
+ line = line.strip()
169
+ if line == '/usr/include':
170
+ _cache_default_sysroot = '/'
171
+ elif line.endswith(".sdk/usr/include"):
172
+ _cache_default_sysroot = line[:-12]
173
+ if _cache_default_sysroot is None:
174
+ _cache_default_sysroot = '/'
175
+
176
+ return _cache_default_sysroot
177
+
178
+ def _supports_universal_builds():
179
+ """Returns True if universal builds are supported on this system"""
180
+ # As an approximation, we assume that if we are running on 10.4 or above,
181
+ # then we are running with an Xcode environment that supports universal
182
+ # builds, in particular -isysroot and -arch arguments to the compiler. This
183
+ # is in support of allowing 10.4 universal builds to run on 10.3.x systems.
184
+
185
+ osx_version = _get_system_version_tuple()
186
+ return bool(osx_version >= (10, 4)) if osx_version else False
187
+
188
+ def _supports_arm64_builds():
189
+ """Returns True if arm64 builds are supported on this system"""
190
+ # There are two sets of systems supporting macOS/arm64 builds:
191
+ # 1. macOS 11 and later, unconditionally
192
+ # 2. macOS 10.15 with Xcode 12.2 or later
193
+ # For now the second category is ignored.
194
+ osx_version = _get_system_version_tuple()
195
+ return osx_version >= (11, 0) if osx_version else False
196
+
197
+
198
+ def _find_appropriate_compiler(_config_vars):
199
+ """Find appropriate C compiler for extension module builds"""
200
+
201
+ # Issue #13590:
202
+ # The OSX location for the compiler varies between OSX
203
+ # (or rather Xcode) releases. With older releases (up-to 10.5)
204
+ # the compiler is in /usr/bin, with newer releases the compiler
205
+ # can only be found inside Xcode.app if the "Command Line Tools"
206
+ # are not installed.
207
+ #
208
+ # Furthermore, the compiler that can be used varies between
209
+ # Xcode releases. Up to Xcode 4 it was possible to use 'gcc-4.2'
210
+ # as the compiler, after that 'clang' should be used because
211
+ # gcc-4.2 is either not present, or a copy of 'llvm-gcc' that
212
+ # miscompiles Python.
213
+
214
+ # skip checks if the compiler was overridden with a CC env variable
215
+ if 'CC' in os.environ:
216
+ return _config_vars
217
+
218
+ # The CC config var might contain additional arguments.
219
+ # Ignore them while searching.
220
+ cc = oldcc = _config_vars['CC'].split()[0]
221
+ if not _find_executable(cc):
222
+ # Compiler is not found on the shell search PATH.
223
+ # Now search for clang, first on PATH (if the Command LIne
224
+ # Tools have been installed in / or if the user has provided
225
+ # another location via CC). If not found, try using xcrun
226
+ # to find an uninstalled clang (within a selected Xcode).
227
+
228
+ # NOTE: Cannot use subprocess here because of bootstrap
229
+ # issues when building Python itself (and os.popen is
230
+ # implemented on top of subprocess and is therefore not
231
+ # usable as well)
232
+
233
+ cc = _find_build_tool('clang')
234
+
235
+ elif os.path.basename(cc).startswith('gcc'):
236
+ # Compiler is GCC, check if it is LLVM-GCC
237
+ data = _read_output("'%s' --version"
238
+ % (cc.replace("'", "'\"'\"'"),))
239
+ if data and 'llvm-gcc' in data:
240
+ # Found LLVM-GCC, fall back to clang
241
+ cc = _find_build_tool('clang')
242
+
243
+ if not cc:
244
+ raise SystemError(
245
+ "Cannot locate working compiler")
246
+
247
+ if cc != oldcc:
248
+ # Found a replacement compiler.
249
+ # Modify config vars using new compiler, if not already explicitly
250
+ # overridden by an env variable, preserving additional arguments.
251
+ for cv in _COMPILER_CONFIG_VARS:
252
+ if cv in _config_vars and cv not in os.environ:
253
+ cv_split = _config_vars[cv].split()
254
+ cv_split[0] = cc if cv != 'CXX' else cc + '++'
255
+ _save_modified_value(_config_vars, cv, ' '.join(cv_split))
256
+
257
+ return _config_vars
258
+
259
+
260
+ def _remove_universal_flags(_config_vars):
261
+ """Remove all universal build arguments from config vars"""
262
+
263
+ for cv in _UNIVERSAL_CONFIG_VARS:
264
+ # Do not alter a config var explicitly overridden by env var
265
+ if cv in _config_vars and cv not in os.environ:
266
+ flags = _config_vars[cv]
267
+ flags = re.sub(r'-arch\s+\w+\s', ' ', flags, flags=re.ASCII)
268
+ flags = re.sub(r'-isysroot\s*\S+', ' ', flags)
269
+ _save_modified_value(_config_vars, cv, flags)
270
+
271
+ return _config_vars
272
+
273
+
274
+ def _remove_unsupported_archs(_config_vars):
275
+ """Remove any unsupported archs from config vars"""
276
+ # Different Xcode releases support different sets for '-arch'
277
+ # flags. In particular, Xcode 4.x no longer supports the
278
+ # PPC architectures.
279
+ #
280
+ # This code automatically removes '-arch ppc' and '-arch ppc64'
281
+ # when these are not supported. That makes it possible to
282
+ # build extensions on OSX 10.7 and later with the prebuilt
283
+ # 32-bit installer on the python.org website.
284
+
285
+ # skip checks if the compiler was overridden with a CC env variable
286
+ if 'CC' in os.environ:
287
+ return _config_vars
288
+
289
+ if re.search(r'-arch\s+ppc', _config_vars['CFLAGS']) is not None:
290
+ # NOTE: Cannot use subprocess here because of bootstrap
291
+ # issues when building Python itself
292
+ status = os.system(
293
+ """echo 'int main{};' | """
294
+ """'%s' -c -arch ppc -x c -o /dev/null /dev/null 2>/dev/null"""
295
+ %(_config_vars['CC'].replace("'", "'\"'\"'"),))
296
+ if status:
297
+ # The compile failed for some reason. Because of differences
298
+ # across Xcode and compiler versions, there is no reliable way
299
+ # to be sure why it failed. Assume here it was due to lack of
300
+ # PPC support and remove the related '-arch' flags from each
301
+ # config variables not explicitly overridden by an environment
302
+ # variable. If the error was for some other reason, we hope the
303
+ # failure will show up again when trying to compile an extension
304
+ # module.
305
+ for cv in _UNIVERSAL_CONFIG_VARS:
306
+ if cv in _config_vars and cv not in os.environ:
307
+ flags = _config_vars[cv]
308
+ flags = re.sub(r'-arch\s+ppc\w*\s', ' ', flags)
309
+ _save_modified_value(_config_vars, cv, flags)
310
+
311
+ return _config_vars
312
+
313
+
314
+ def _override_all_archs(_config_vars):
315
+ """Allow override of all archs with ARCHFLAGS env var"""
316
+ # NOTE: This name was introduced by Apple in OSX 10.5 and
317
+ # is used by several scripting languages distributed with
318
+ # that OS release.
319
+ if 'ARCHFLAGS' in os.environ:
320
+ arch = os.environ['ARCHFLAGS']
321
+ for cv in _UNIVERSAL_CONFIG_VARS:
322
+ if cv in _config_vars and '-arch' in _config_vars[cv]:
323
+ flags = _config_vars[cv]
324
+ flags = re.sub(r'-arch\s+\w+\s', ' ', flags)
325
+ flags = flags + ' ' + arch
326
+ _save_modified_value(_config_vars, cv, flags)
327
+
328
+ return _config_vars
329
+
330
+
331
+ def _check_for_unavailable_sdk(_config_vars):
332
+ """Remove references to any SDKs not available"""
333
+ # If we're on OSX 10.5 or later and the user tries to
334
+ # compile an extension using an SDK that is not present
335
+ # on the current machine it is better to not use an SDK
336
+ # than to fail. This is particularly important with
337
+ # the standalone Command Line Tools alternative to a
338
+ # full-blown Xcode install since the CLT packages do not
339
+ # provide SDKs. If the SDK is not present, it is assumed
340
+ # that the header files and dev libs have been installed
341
+ # to /usr and /System/Library by either a standalone CLT
342
+ # package or the CLT component within Xcode.
343
+ cflags = _config_vars.get('CFLAGS', '')
344
+ m = re.search(r'-isysroot\s*(\S+)', cflags)
345
+ if m is not None:
346
+ sdk = m.group(1)
347
+ if not os.path.exists(sdk):
348
+ for cv in _UNIVERSAL_CONFIG_VARS:
349
+ # Do not alter a config var explicitly overridden by env var
350
+ if cv in _config_vars and cv not in os.environ:
351
+ flags = _config_vars[cv]
352
+ flags = re.sub(r'-isysroot\s*\S+(?:\s|$)', ' ', flags)
353
+ _save_modified_value(_config_vars, cv, flags)
354
+
355
+ return _config_vars
356
+
357
+
358
+ def compiler_fixup(compiler_so, cc_args):
359
+ """
360
+ This function will strip '-isysroot PATH' and '-arch ARCH' from the
361
+ compile flags if the user has specified one them in extra_compile_flags.
362
+
363
+ This is needed because '-arch ARCH' adds another architecture to the
364
+ build, without a way to remove an architecture. Furthermore GCC will
365
+ barf if multiple '-isysroot' arguments are present.
366
+ """
367
+ stripArch = stripSysroot = False
368
+
369
+ compiler_so = list(compiler_so)
370
+
371
+ if not _supports_universal_builds():
372
+ # OSX before 10.4.0, these don't support -arch and -isysroot at
373
+ # all.
374
+ stripArch = stripSysroot = True
375
+ else:
376
+ stripArch = '-arch' in cc_args
377
+ stripSysroot = any(arg for arg in cc_args if arg.startswith('-isysroot'))
378
+
379
+ if stripArch or 'ARCHFLAGS' in os.environ:
380
+ while True:
381
+ try:
382
+ index = compiler_so.index('-arch')
383
+ # Strip this argument and the next one:
384
+ del compiler_so[index:index+2]
385
+ except ValueError:
386
+ break
387
+
388
+ elif not _supports_arm64_builds():
389
+ # Look for "-arch arm64" and drop that
390
+ for idx in reversed(range(len(compiler_so))):
391
+ if compiler_so[idx] == '-arch' and compiler_so[idx+1] == "arm64":
392
+ del compiler_so[idx:idx+2]
393
+
394
+ if 'ARCHFLAGS' in os.environ and not stripArch:
395
+ # User specified different -arch flags in the environ,
396
+ # see also distutils.sysconfig
397
+ compiler_so = compiler_so + os.environ['ARCHFLAGS'].split()
398
+
399
+ if stripSysroot:
400
+ while True:
401
+ indices = [i for i,x in enumerate(compiler_so) if x.startswith('-isysroot')]
402
+ if not indices:
403
+ break
404
+ index = indices[0]
405
+ if compiler_so[index] == '-isysroot':
406
+ # Strip this argument and the next one:
407
+ del compiler_so[index:index+2]
408
+ else:
409
+ # It's '-isysroot/some/path' in one arg
410
+ del compiler_so[index:index+1]
411
+
412
+ # Check if the SDK that is used during compilation actually exists,
413
+ # the universal build requires the usage of a universal SDK and not all
414
+ # users have that installed by default.
415
+ sysroot = None
416
+ argvar = cc_args
417
+ indices = [i for i,x in enumerate(cc_args) if x.startswith('-isysroot')]
418
+ if not indices:
419
+ argvar = compiler_so
420
+ indices = [i for i,x in enumerate(compiler_so) if x.startswith('-isysroot')]
421
+
422
+ for idx in indices:
423
+ if argvar[idx] == '-isysroot':
424
+ sysroot = argvar[idx+1]
425
+ break
426
+ else:
427
+ sysroot = argvar[idx][len('-isysroot'):]
428
+ break
429
+
430
+ if sysroot and not os.path.isdir(sysroot):
431
+ sys.stderr.write(f"Compiling with an SDK that doesn't seem to exist: {sysroot}\n")
432
+ sys.stderr.write("Please check your Xcode installation\n")
433
+ sys.stderr.flush()
434
+
435
+ return compiler_so
436
+
437
+
438
+ def customize_config_vars(_config_vars):
439
+ """Customize Python build configuration variables.
440
+
441
+ Called internally from sysconfig with a mutable mapping
442
+ containing name/value pairs parsed from the configured
443
+ makefile used to build this interpreter. Returns
444
+ the mapping updated as needed to reflect the environment
445
+ in which the interpreter is running; in the case of
446
+ a Python from a binary installer, the installed
447
+ environment may be very different from the build
448
+ environment, i.e. different OS levels, different
449
+ built tools, different available CPU architectures.
450
+
451
+ This customization is performed whenever
452
+ distutils.sysconfig.get_config_vars() is first
453
+ called. It may be used in environments where no
454
+ compilers are present, i.e. when installing pure
455
+ Python dists. Customization of compiler paths
456
+ and detection of unavailable archs is deferred
457
+ until the first extension module build is
458
+ requested (in distutils.sysconfig.customize_compiler).
459
+
460
+ Currently called from distutils.sysconfig
461
+ """
462
+
463
+ if not _supports_universal_builds():
464
+ # On Mac OS X before 10.4, check if -arch and -isysroot
465
+ # are in CFLAGS or LDFLAGS and remove them if they are.
466
+ # This is needed when building extensions on a 10.3 system
467
+ # using a universal build of python.
468
+ _remove_universal_flags(_config_vars)
469
+
470
+ # Allow user to override all archs with ARCHFLAGS env var
471
+ _override_all_archs(_config_vars)
472
+
473
+ # Remove references to sdks that are not found
474
+ _check_for_unavailable_sdk(_config_vars)
475
+
476
+ return _config_vars
477
+
478
+
479
+ def customize_compiler(_config_vars):
480
+ """Customize compiler path and configuration variables.
481
+
482
+ This customization is performed when the first
483
+ extension module build is requested
484
+ in distutils.sysconfig.customize_compiler.
485
+ """
486
+
487
+ # Find a compiler to use for extension module builds
488
+ _find_appropriate_compiler(_config_vars)
489
+
490
+ # Remove ppc arch flags if not supported here
491
+ _remove_unsupported_archs(_config_vars)
492
+
493
+ # Allow user to override all archs with ARCHFLAGS env var
494
+ _override_all_archs(_config_vars)
495
+
496
+ return _config_vars
497
+
498
+
499
+ def get_platform_osx(_config_vars, osname, release, machine):
500
+ """Filter values for get_platform()"""
501
+ # called from get_platform() in sysconfig and distutils.util
502
+ #
503
+ # For our purposes, we'll assume that the system version from
504
+ # distutils' perspective is what MACOSX_DEPLOYMENT_TARGET is set
505
+ # to. This makes the compatibility story a bit more sane because the
506
+ # machine is going to compile and link as if it were
507
+ # MACOSX_DEPLOYMENT_TARGET.
508
+
509
+ macver = _config_vars.get('MACOSX_DEPLOYMENT_TARGET', '')
510
+ if macver and '.' not in macver:
511
+ # Ensure that the version includes at least a major
512
+ # and minor version, even if MACOSX_DEPLOYMENT_TARGET
513
+ # is set to a single-label version like "14".
514
+ macver += '.0'
515
+ macrelease = _get_system_version() or macver
516
+ macver = macver or macrelease
517
+
518
+ if macver:
519
+ release = macver
520
+ osname = "macosx"
521
+
522
+ # Use the original CFLAGS value, if available, so that we
523
+ # return the same machine type for the platform string.
524
+ # Otherwise, distutils may consider this a cross-compiling
525
+ # case and disallow installs.
526
+ cflags = _config_vars.get(_INITPRE+'CFLAGS',
527
+ _config_vars.get('CFLAGS', ''))
528
+ if macrelease:
529
+ try:
530
+ macrelease = tuple(int(i) for i in macrelease.split('.')[0:2])
531
+ except ValueError:
532
+ macrelease = (10, 3)
533
+ else:
534
+ # assume no universal support
535
+ macrelease = (10, 3)
536
+
537
+ if (macrelease >= (10, 4)) and '-arch' in cflags.strip():
538
+ # The universal build will build fat binaries, but not on
539
+ # systems before 10.4
540
+
541
+ machine = 'fat'
542
+
543
+ archs = re.findall(r'-arch\s+(\S+)', cflags)
544
+ archs = tuple(sorted(set(archs)))
545
+
546
+ if len(archs) == 1:
547
+ machine = archs[0]
548
+ elif archs == ('arm64', 'x86_64'):
549
+ machine = 'universal2'
550
+ elif archs == ('i386', 'ppc'):
551
+ machine = 'fat'
552
+ elif archs == ('i386', 'x86_64'):
553
+ machine = 'intel'
554
+ elif archs == ('i386', 'ppc', 'x86_64'):
555
+ machine = 'fat3'
556
+ elif archs == ('ppc64', 'x86_64'):
557
+ machine = 'fat64'
558
+ elif archs == ('i386', 'ppc', 'ppc64', 'x86_64'):
559
+ machine = 'universal'
560
+ else:
561
+ raise ValueError(
562
+ "Don't know machine value for archs=%r" % (archs,))
563
+
564
+ elif machine == 'i386':
565
+ # On OSX the machine type returned by uname is always the
566
+ # 32-bit variant, even if the executable architecture is
567
+ # the 64-bit variant
568
+ if sys.maxsize >= 2**32:
569
+ machine = 'x86_64'
570
+
571
+ elif machine in ('PowerPC', 'Power_Macintosh'):
572
+ # Pick a sane name for the PPC architecture.
573
+ # See 'i386' case
574
+ if sys.maxsize >= 2**32:
575
+ machine = 'ppc64'
576
+ else:
577
+ machine = 'ppc'
578
+
579
+ return (osname, release, machine)
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_py_abc.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from _weakrefset import WeakSet
2
+
3
+
4
+ def get_cache_token():
5
+ """Returns the current ABC cache token.
6
+
7
+ The token is an opaque object (supporting equality testing) identifying the
8
+ current version of the ABC cache for virtual subclasses. The token changes
9
+ with every call to ``register()`` on any ABC.
10
+ """
11
+ return ABCMeta._abc_invalidation_counter
12
+
13
+
14
+ class ABCMeta(type):
15
+ """Metaclass for defining Abstract Base Classes (ABCs).
16
+
17
+ Use this metaclass to create an ABC. An ABC can be subclassed
18
+ directly, and then acts as a mix-in class. You can also register
19
+ unrelated concrete classes (even built-in classes) and unrelated
20
+ ABCs as 'virtual subclasses' -- these and their descendants will
21
+ be considered subclasses of the registering ABC by the built-in
22
+ issubclass() function, but the registering ABC won't show up in
23
+ their MRO (Method Resolution Order) nor will method
24
+ implementations defined by the registering ABC be callable (not
25
+ even via super()).
26
+ """
27
+
28
+ # A global counter that is incremented each time a class is
29
+ # registered as a virtual subclass of anything. It forces the
30
+ # negative cache to be cleared before its next use.
31
+ # Note: this counter is private. Use `abc.get_cache_token()` for
32
+ # external code.
33
+ _abc_invalidation_counter = 0
34
+
35
+ def __new__(mcls, name, bases, namespace, /, **kwargs):
36
+ cls = super().__new__(mcls, name, bases, namespace, **kwargs)
37
+ # Compute set of abstract method names
38
+ abstracts = {name
39
+ for name, value in namespace.items()
40
+ if getattr(value, "__isabstractmethod__", False)}
41
+ for base in bases:
42
+ for name in getattr(base, "__abstractmethods__", set()):
43
+ value = getattr(cls, name, None)
44
+ if getattr(value, "__isabstractmethod__", False):
45
+ abstracts.add(name)
46
+ cls.__abstractmethods__ = frozenset(abstracts)
47
+ # Set up inheritance registry
48
+ cls._abc_registry = WeakSet()
49
+ cls._abc_cache = WeakSet()
50
+ cls._abc_negative_cache = WeakSet()
51
+ cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
52
+ return cls
53
+
54
+ def register(cls, subclass):
55
+ """Register a virtual subclass of an ABC.
56
+
57
+ Returns the subclass, to allow usage as a class decorator.
58
+ """
59
+ if not isinstance(subclass, type):
60
+ raise TypeError("Can only register classes")
61
+ if issubclass(subclass, cls):
62
+ return subclass # Already a subclass
63
+ # Subtle: test for cycles *after* testing for "already a subclass";
64
+ # this means we allow X.register(X) and interpret it as a no-op.
65
+ if issubclass(cls, subclass):
66
+ # This would create a cycle, which is bad for the algorithm below
67
+ raise RuntimeError("Refusing to create an inheritance cycle")
68
+ cls._abc_registry.add(subclass)
69
+ ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache
70
+ return subclass
71
+
72
+ def _dump_registry(cls, file=None):
73
+ """Debug helper to print the ABC registry."""
74
+ print(f"Class: {cls.__module__}.{cls.__qualname__}", file=file)
75
+ print(f"Inv. counter: {get_cache_token()}", file=file)
76
+ for name in cls.__dict__:
77
+ if name.startswith("_abc_"):
78
+ value = getattr(cls, name)
79
+ if isinstance(value, WeakSet):
80
+ value = set(value)
81
+ print(f"{name}: {value!r}", file=file)
82
+
83
+ def _abc_registry_clear(cls):
84
+ """Clear the registry (for debugging or testing)."""
85
+ cls._abc_registry.clear()
86
+
87
+ def _abc_caches_clear(cls):
88
+ """Clear the caches (for debugging or testing)."""
89
+ cls._abc_cache.clear()
90
+ cls._abc_negative_cache.clear()
91
+
92
+ def __instancecheck__(cls, instance):
93
+ """Override for isinstance(instance, cls)."""
94
+ # Inline the cache checking
95
+ subclass = instance.__class__
96
+ if subclass in cls._abc_cache:
97
+ return True
98
+ subtype = type(instance)
99
+ if subtype is subclass:
100
+ if (cls._abc_negative_cache_version ==
101
+ ABCMeta._abc_invalidation_counter and
102
+ subclass in cls._abc_negative_cache):
103
+ return False
104
+ # Fall back to the subclass check.
105
+ return cls.__subclasscheck__(subclass)
106
+ return any(cls.__subclasscheck__(c) for c in (subclass, subtype))
107
+
108
+ def __subclasscheck__(cls, subclass):
109
+ """Override for issubclass(subclass, cls)."""
110
+ if not isinstance(subclass, type):
111
+ raise TypeError('issubclass() arg 1 must be a class')
112
+ # Check cache
113
+ if subclass in cls._abc_cache:
114
+ return True
115
+ # Check negative cache; may have to invalidate
116
+ if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter:
117
+ # Invalidate the negative cache
118
+ cls._abc_negative_cache = WeakSet()
119
+ cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
120
+ elif subclass in cls._abc_negative_cache:
121
+ return False
122
+ # Check the subclass hook
123
+ ok = cls.__subclasshook__(subclass)
124
+ if ok is not NotImplemented:
125
+ assert isinstance(ok, bool)
126
+ if ok:
127
+ cls._abc_cache.add(subclass)
128
+ else:
129
+ cls._abc_negative_cache.add(subclass)
130
+ return ok
131
+ # Check if it's a direct subclass
132
+ if cls in getattr(subclass, '__mro__', ()):
133
+ cls._abc_cache.add(subclass)
134
+ return True
135
+ # Check if it's a subclass of a registered class (recursive)
136
+ for rcls in cls._abc_registry:
137
+ if issubclass(subclass, rcls):
138
+ cls._abc_cache.add(subclass)
139
+ return True
140
+ # Check if it's a subclass of a subclass (recursive)
141
+ for scls in cls.__subclasses__():
142
+ if issubclass(subclass, scls):
143
+ cls._abc_cache.add(subclass)
144
+ return True
145
+ # No dice; update negative cache
146
+ cls._abc_negative_cache.add(subclass)
147
+ return False
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_pydecimal.py ADDED
The diff for this file is too large to render. See raw diff
 
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_pyio.py ADDED
@@ -0,0 +1,2712 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Python implementation of the io module.
3
+ """
4
+
5
+ import os
6
+ import abc
7
+ import codecs
8
+ import errno
9
+ import stat
10
+ import sys
11
+ # Import _thread instead of threading to reduce startup cost
12
+ from _thread import allocate_lock as Lock
13
+ if sys.platform in {'win32', 'cygwin'}:
14
+ from msvcrt import setmode as _setmode
15
+ else:
16
+ _setmode = None
17
+
18
+ import io
19
+ from io import (__all__, SEEK_SET, SEEK_CUR, SEEK_END)
20
+
21
+ valid_seek_flags = {0, 1, 2} # Hardwired values
22
+ if hasattr(os, 'SEEK_HOLE') :
23
+ valid_seek_flags.add(os.SEEK_HOLE)
24
+ valid_seek_flags.add(os.SEEK_DATA)
25
+
26
+ # open() uses st_blksize whenever we can
27
+ DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
28
+
29
+ # NOTE: Base classes defined here are registered with the "official" ABCs
30
+ # defined in io.py. We don't use real inheritance though, because we don't want
31
+ # to inherit the C implementations.
32
+
33
+ # Rebind for compatibility
34
+ BlockingIOError = BlockingIOError
35
+
36
+ # Does io.IOBase finalizer log the exception if the close() method fails?
37
+ # The exception is ignored silently by default in release build.
38
+ _IOBASE_EMITS_UNRAISABLE = (hasattr(sys, "gettotalrefcount") or sys.flags.dev_mode)
39
+ # Does open() check its 'errors' argument?
40
+ _CHECK_ERRORS = _IOBASE_EMITS_UNRAISABLE
41
+
42
+
43
+ def text_encoding(encoding, stacklevel=2):
44
+ """
45
+ A helper function to choose the text encoding.
46
+
47
+ When encoding is not None, this function returns it.
48
+ Otherwise, this function returns the default text encoding
49
+ (i.e. "locale" or "utf-8" depends on UTF-8 mode).
50
+
51
+ This function emits an EncodingWarning if *encoding* is None and
52
+ sys.flags.warn_default_encoding is true.
53
+
54
+ This can be used in APIs with an encoding=None parameter
55
+ that pass it to TextIOWrapper or open.
56
+ However, please consider using encoding="utf-8" for new APIs.
57
+ """
58
+ if encoding is None:
59
+ if sys.flags.utf8_mode:
60
+ encoding = "utf-8"
61
+ else:
62
+ encoding = "locale"
63
+ if sys.flags.warn_default_encoding:
64
+ import warnings
65
+ warnings.warn("'encoding' argument not specified.",
66
+ EncodingWarning, stacklevel + 1)
67
+ return encoding
68
+
69
+
70
+ # Wrapper for builtins.open
71
+ #
72
+ # Trick so that open() won't become a bound method when stored
73
+ # as a class variable (as dbm.dumb does).
74
+ #
75
+ # See init_set_builtins_open() in Python/pylifecycle.c.
76
+ @staticmethod
77
+ def open(file, mode="r", buffering=-1, encoding=None, errors=None,
78
+ newline=None, closefd=True, opener=None):
79
+
80
+ r"""Open file and return a stream. Raise OSError upon failure.
81
+
82
+ file is either a text or byte string giving the name (and the path
83
+ if the file isn't in the current working directory) of the file to
84
+ be opened or an integer file descriptor of the file to be
85
+ wrapped. (If a file descriptor is given, it is closed when the
86
+ returned I/O object is closed, unless closefd is set to False.)
87
+
88
+ mode is an optional string that specifies the mode in which the file is
89
+ opened. It defaults to 'r' which means open for reading in text mode. Other
90
+ common values are 'w' for writing (truncating the file if it already
91
+ exists), 'x' for exclusive creation of a new file, and 'a' for appending
92
+ (which on some Unix systems, means that all writes append to the end of the
93
+ file regardless of the current seek position). In text mode, if encoding is
94
+ not specified the encoding used is platform dependent. (For reading and
95
+ writing raw bytes use binary mode and leave encoding unspecified.) The
96
+ available modes are:
97
+
98
+ ========= ===============================================================
99
+ Character Meaning
100
+ --------- ---------------------------------------------------------------
101
+ 'r' open for reading (default)
102
+ 'w' open for writing, truncating the file first
103
+ 'x' create a new file and open it for writing
104
+ 'a' open for writing, appending to the end of the file if it exists
105
+ 'b' binary mode
106
+ 't' text mode (default)
107
+ '+' open a disk file for updating (reading and writing)
108
+ ========= ===============================================================
109
+
110
+ The default mode is 'rt' (open for reading text). For binary random
111
+ access, the mode 'w+b' opens and truncates the file to 0 bytes, while
112
+ 'r+b' opens the file without truncation. The 'x' mode implies 'w' and
113
+ raises an `FileExistsError` if the file already exists.
114
+
115
+ Python distinguishes between files opened in binary and text modes,
116
+ even when the underlying operating system doesn't. Files opened in
117
+ binary mode (appending 'b' to the mode argument) return contents as
118
+ bytes objects without any decoding. In text mode (the default, or when
119
+ 't' is appended to the mode argument), the contents of the file are
120
+ returned as strings, the bytes having been first decoded using a
121
+ platform-dependent encoding or using the specified encoding if given.
122
+
123
+ buffering is an optional integer used to set the buffering policy.
124
+ Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
125
+ line buffering (only usable in text mode), and an integer > 1 to indicate
126
+ the size of a fixed-size chunk buffer. When no buffering argument is
127
+ given, the default buffering policy works as follows:
128
+
129
+ * Binary files are buffered in fixed-size chunks; the size of the buffer
130
+ is chosen using a heuristic trying to determine the underlying device's
131
+ "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
132
+ On many systems, the buffer will typically be 4096 or 8192 bytes long.
133
+
134
+ * "Interactive" text files (files for which isatty() returns True)
135
+ use line buffering. Other text files use the policy described above
136
+ for binary files.
137
+
138
+ encoding is the str name of the encoding used to decode or encode the
139
+ file. This should only be used in text mode. The default encoding is
140
+ platform dependent, but any encoding supported by Python can be
141
+ passed. See the codecs module for the list of supported encodings.
142
+
143
+ errors is an optional string that specifies how encoding errors are to
144
+ be handled---this argument should not be used in binary mode. Pass
145
+ 'strict' to raise a ValueError exception if there is an encoding error
146
+ (the default of None has the same effect), or pass 'ignore' to ignore
147
+ errors. (Note that ignoring encoding errors can lead to data loss.)
148
+ See the documentation for codecs.register for a list of the permitted
149
+ encoding error strings.
150
+
151
+ newline is a string controlling how universal newlines works (it only
152
+ applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works
153
+ as follows:
154
+
155
+ * On input, if newline is None, universal newlines mode is
156
+ enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
157
+ these are translated into '\n' before being returned to the
158
+ caller. If it is '', universal newline mode is enabled, but line
159
+ endings are returned to the caller untranslated. If it has any of
160
+ the other legal values, input lines are only terminated by the given
161
+ string, and the line ending is returned to the caller untranslated.
162
+
163
+ * On output, if newline is None, any '\n' characters written are
164
+ translated to the system default line separator, os.linesep. If
165
+ newline is '', no translation takes place. If newline is any of the
166
+ other legal values, any '\n' characters written are translated to
167
+ the given string.
168
+
169
+ closedfd is a bool. If closefd is False, the underlying file descriptor will
170
+ be kept open when the file is closed. This does not work when a file name is
171
+ given and must be True in that case.
172
+
173
+ The newly created file is non-inheritable.
174
+
175
+ A custom opener can be used by passing a callable as *opener*. The
176
+ underlying file descriptor for the file object is then obtained by calling
177
+ *opener* with (*file*, *flags*). *opener* must return an open file
178
+ descriptor (passing os.open as *opener* results in functionality similar to
179
+ passing None).
180
+
181
+ open() returns a file object whose type depends on the mode, and
182
+ through which the standard file operations such as reading and writing
183
+ are performed. When open() is used to open a file in a text mode ('w',
184
+ 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
185
+ a file in a binary mode, the returned class varies: in read binary
186
+ mode, it returns a BufferedReader; in write binary and append binary
187
+ modes, it returns a BufferedWriter, and in read/write mode, it returns
188
+ a BufferedRandom.
189
+
190
+ It is also possible to use a string or bytearray as a file for both
191
+ reading and writing. For strings StringIO can be used like a file
192
+ opened in a text mode, and for bytes a BytesIO can be used like a file
193
+ opened in a binary mode.
194
+ """
195
+ if not isinstance(file, int):
196
+ file = os.fspath(file)
197
+ if not isinstance(file, (str, bytes, int)):
198
+ raise TypeError("invalid file: %r" % file)
199
+ if not isinstance(mode, str):
200
+ raise TypeError("invalid mode: %r" % mode)
201
+ if not isinstance(buffering, int):
202
+ raise TypeError("invalid buffering: %r" % buffering)
203
+ if encoding is not None and not isinstance(encoding, str):
204
+ raise TypeError("invalid encoding: %r" % encoding)
205
+ if errors is not None and not isinstance(errors, str):
206
+ raise TypeError("invalid errors: %r" % errors)
207
+ modes = set(mode)
208
+ if modes - set("axrwb+t") or len(mode) > len(modes):
209
+ raise ValueError("invalid mode: %r" % mode)
210
+ creating = "x" in modes
211
+ reading = "r" in modes
212
+ writing = "w" in modes
213
+ appending = "a" in modes
214
+ updating = "+" in modes
215
+ text = "t" in modes
216
+ binary = "b" in modes
217
+ if text and binary:
218
+ raise ValueError("can't have text and binary mode at once")
219
+ if creating + reading + writing + appending > 1:
220
+ raise ValueError("can't have read/write/append mode at once")
221
+ if not (creating or reading or writing or appending):
222
+ raise ValueError("must have exactly one of read/write/append mode")
223
+ if binary and encoding is not None:
224
+ raise ValueError("binary mode doesn't take an encoding argument")
225
+ if binary and errors is not None:
226
+ raise ValueError("binary mode doesn't take an errors argument")
227
+ if binary and newline is not None:
228
+ raise ValueError("binary mode doesn't take a newline argument")
229
+ if binary and buffering == 1:
230
+ import warnings
231
+ warnings.warn("line buffering (buffering=1) isn't supported in binary "
232
+ "mode, the default buffer size will be used",
233
+ RuntimeWarning, 2)
234
+ raw = FileIO(file,
235
+ (creating and "x" or "") +
236
+ (reading and "r" or "") +
237
+ (writing and "w" or "") +
238
+ (appending and "a" or "") +
239
+ (updating and "+" or ""),
240
+ closefd, opener=opener)
241
+ result = raw
242
+ try:
243
+ line_buffering = False
244
+ if buffering == 1 or buffering < 0 and raw.isatty():
245
+ buffering = -1
246
+ line_buffering = True
247
+ if buffering < 0:
248
+ buffering = DEFAULT_BUFFER_SIZE
249
+ try:
250
+ bs = os.fstat(raw.fileno()).st_blksize
251
+ except (OSError, AttributeError):
252
+ pass
253
+ else:
254
+ if bs > 1:
255
+ buffering = bs
256
+ if buffering < 0:
257
+ raise ValueError("invalid buffering size")
258
+ if buffering == 0:
259
+ if binary:
260
+ return result
261
+ raise ValueError("can't have unbuffered text I/O")
262
+ if updating:
263
+ buffer = BufferedRandom(raw, buffering)
264
+ elif creating or writing or appending:
265
+ buffer = BufferedWriter(raw, buffering)
266
+ elif reading:
267
+ buffer = BufferedReader(raw, buffering)
268
+ else:
269
+ raise ValueError("unknown mode: %r" % mode)
270
+ result = buffer
271
+ if binary:
272
+ return result
273
+ encoding = text_encoding(encoding)
274
+ text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
275
+ result = text
276
+ text.mode = mode
277
+ return result
278
+ except:
279
+ result.close()
280
+ raise
281
+
282
+ # Define a default pure-Python implementation for open_code()
283
+ # that does not allow hooks. Warn on first use. Defined for tests.
284
+ def _open_code_with_warning(path):
285
+ """Opens the provided file with mode ``'rb'``. This function
286
+ should be used when the intent is to treat the contents as
287
+ executable code.
288
+
289
+ ``path`` should be an absolute path.
290
+
291
+ When supported by the runtime, this function can be hooked
292
+ in order to allow embedders more control over code files.
293
+ This functionality is not supported on the current runtime.
294
+ """
295
+ import warnings
296
+ warnings.warn("_pyio.open_code() may not be using hooks",
297
+ RuntimeWarning, 2)
298
+ return open(path, "rb")
299
+
300
+ try:
301
+ open_code = io.open_code
302
+ except AttributeError:
303
+ open_code = _open_code_with_warning
304
+
305
+
306
+ def __getattr__(name):
307
+ if name == "OpenWrapper":
308
+ # bpo-43680: Until Python 3.9, _pyio.open was not a static method and
309
+ # builtins.open was set to OpenWrapper to not become a bound method
310
+ # when set to a class variable. _io.open is a built-in function whereas
311
+ # _pyio.open is a Python function. In Python 3.10, _pyio.open() is now
312
+ # a static method, and builtins.open() is now io.open().
313
+ import warnings
314
+ warnings.warn('OpenWrapper is deprecated, use open instead',
315
+ DeprecationWarning, stacklevel=2)
316
+ global OpenWrapper
317
+ OpenWrapper = open
318
+ return OpenWrapper
319
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
320
+
321
+
322
+ # In normal operation, both `UnsupportedOperation`s should be bound to the
323
+ # same object.
324
+ try:
325
+ UnsupportedOperation = io.UnsupportedOperation
326
+ except AttributeError:
327
+ class UnsupportedOperation(OSError, ValueError):
328
+ pass
329
+
330
+
331
+ class IOBase(metaclass=abc.ABCMeta):
332
+
333
+ """The abstract base class for all I/O classes.
334
+
335
+ This class provides dummy implementations for many methods that
336
+ derived classes can override selectively; the default implementations
337
+ represent a file that cannot be read, written or seeked.
338
+
339
+ Even though IOBase does not declare read or write because
340
+ their signatures will vary, implementations and clients should
341
+ consider those methods part of the interface. Also, implementations
342
+ may raise UnsupportedOperation when operations they do not support are
343
+ called.
344
+
345
+ The basic type used for binary data read from or written to a file is
346
+ bytes. Other bytes-like objects are accepted as method arguments too.
347
+ Text I/O classes work with str data.
348
+
349
+ Note that calling any method (even inquiries) on a closed stream is
350
+ undefined. Implementations may raise OSError in this case.
351
+
352
+ IOBase (and its subclasses) support the iterator protocol, meaning
353
+ that an IOBase object can be iterated over yielding the lines in a
354
+ stream.
355
+
356
+ IOBase also supports the :keyword:`with` statement. In this example,
357
+ fp is closed after the suite of the with statement is complete:
358
+
359
+ with open('spam.txt', 'r') as fp:
360
+ fp.write('Spam and eggs!')
361
+ """
362
+
363
+ ### Internal ###
364
+
365
+ def _unsupported(self, name):
366
+ """Internal: raise an OSError exception for unsupported operations."""
367
+ raise UnsupportedOperation("%s.%s() not supported" %
368
+ (self.__class__.__name__, name))
369
+
370
+ ### Positioning ###
371
+
372
+ def seek(self, pos, whence=0):
373
+ """Change stream position.
374
+
375
+ Change the stream position to byte offset pos. Argument pos is
376
+ interpreted relative to the position indicated by whence. Values
377
+ for whence are ints:
378
+
379
+ * 0 -- start of stream (the default); offset should be zero or positive
380
+ * 1 -- current stream position; offset may be negative
381
+ * 2 -- end of stream; offset is usually negative
382
+ Some operating systems / file systems could provide additional values.
383
+
384
+ Return an int indicating the new absolute position.
385
+ """
386
+ self._unsupported("seek")
387
+
388
+ def tell(self):
389
+ """Return an int indicating the current stream position."""
390
+ return self.seek(0, 1)
391
+
392
+ def truncate(self, pos=None):
393
+ """Truncate file to size bytes.
394
+
395
+ Size defaults to the current IO position as reported by tell(). Return
396
+ the new size.
397
+ """
398
+ self._unsupported("truncate")
399
+
400
+ ### Flush and close ###
401
+
402
+ def flush(self):
403
+ """Flush write buffers, if applicable.
404
+
405
+ This is not implemented for read-only and non-blocking streams.
406
+ """
407
+ self._checkClosed()
408
+ # XXX Should this return the number of bytes written???
409
+
410
+ __closed = False
411
+
412
+ def close(self):
413
+ """Flush and close the IO object.
414
+
415
+ This method has no effect if the file is already closed.
416
+ """
417
+ if not self.__closed:
418
+ try:
419
+ self.flush()
420
+ finally:
421
+ self.__closed = True
422
+
423
+ def __del__(self):
424
+ """Destructor. Calls close()."""
425
+ try:
426
+ closed = self.closed
427
+ except AttributeError:
428
+ # If getting closed fails, then the object is probably
429
+ # in an unusable state, so ignore.
430
+ return
431
+
432
+ if closed:
433
+ return
434
+
435
+ if _IOBASE_EMITS_UNRAISABLE:
436
+ self.close()
437
+ else:
438
+ # The try/except block is in case this is called at program
439
+ # exit time, when it's possible that globals have already been
440
+ # deleted, and then the close() call might fail. Since
441
+ # there's nothing we can do about such failures and they annoy
442
+ # the end users, we suppress the traceback.
443
+ try:
444
+ self.close()
445
+ except:
446
+ pass
447
+
448
+ ### Inquiries ###
449
+
450
+ def seekable(self):
451
+ """Return a bool indicating whether object supports random access.
452
+
453
+ If False, seek(), tell() and truncate() will raise OSError.
454
+ This method may need to do a test seek().
455
+ """
456
+ return False
457
+
458
+ def _checkSeekable(self, msg=None):
459
+ """Internal: raise UnsupportedOperation if file is not seekable
460
+ """
461
+ if not self.seekable():
462
+ raise UnsupportedOperation("File or stream is not seekable."
463
+ if msg is None else msg)
464
+
465
+ def readable(self):
466
+ """Return a bool indicating whether object was opened for reading.
467
+
468
+ If False, read() will raise OSError.
469
+ """
470
+ return False
471
+
472
+ def _checkReadable(self, msg=None):
473
+ """Internal: raise UnsupportedOperation if file is not readable
474
+ """
475
+ if not self.readable():
476
+ raise UnsupportedOperation("File or stream is not readable."
477
+ if msg is None else msg)
478
+
479
+ def writable(self):
480
+ """Return a bool indicating whether object was opened for writing.
481
+
482
+ If False, write() and truncate() will raise OSError.
483
+ """
484
+ return False
485
+
486
+ def _checkWritable(self, msg=None):
487
+ """Internal: raise UnsupportedOperation if file is not writable
488
+ """
489
+ if not self.writable():
490
+ raise UnsupportedOperation("File or stream is not writable."
491
+ if msg is None else msg)
492
+
493
+ @property
494
+ def closed(self):
495
+ """closed: bool. True iff the file has been closed.
496
+
497
+ For backwards compatibility, this is a property, not a predicate.
498
+ """
499
+ return self.__closed
500
+
501
+ def _checkClosed(self, msg=None):
502
+ """Internal: raise a ValueError if file is closed
503
+ """
504
+ if self.closed:
505
+ raise ValueError("I/O operation on closed file."
506
+ if msg is None else msg)
507
+
508
+ ### Context manager ###
509
+
510
+ def __enter__(self): # That's a forward reference
511
+ """Context management protocol. Returns self (an instance of IOBase)."""
512
+ self._checkClosed()
513
+ return self
514
+
515
+ def __exit__(self, *args):
516
+ """Context management protocol. Calls close()"""
517
+ self.close()
518
+
519
+ ### Lower-level APIs ###
520
+
521
+ # XXX Should these be present even if unimplemented?
522
+
523
+ def fileno(self):
524
+ """Returns underlying file descriptor (an int) if one exists.
525
+
526
+ An OSError is raised if the IO object does not use a file descriptor.
527
+ """
528
+ self._unsupported("fileno")
529
+
530
+ def isatty(self):
531
+ """Return a bool indicating whether this is an 'interactive' stream.
532
+
533
+ Return False if it can't be determined.
534
+ """
535
+ self._checkClosed()
536
+ return False
537
+
538
+ ### Readline[s] and writelines ###
539
+
540
+ def readline(self, size=-1):
541
+ r"""Read and return a line of bytes from the stream.
542
+
543
+ If size is specified, at most size bytes will be read.
544
+ Size should be an int.
545
+
546
+ The line terminator is always b'\n' for binary files; for text
547
+ files, the newlines argument to open can be used to select the line
548
+ terminator(s) recognized.
549
+ """
550
+ # For backwards compatibility, a (slowish) readline().
551
+ if hasattr(self, "peek"):
552
+ def nreadahead():
553
+ readahead = self.peek(1)
554
+ if not readahead:
555
+ return 1
556
+ n = (readahead.find(b"\n") + 1) or len(readahead)
557
+ if size >= 0:
558
+ n = min(n, size)
559
+ return n
560
+ else:
561
+ def nreadahead():
562
+ return 1
563
+ if size is None:
564
+ size = -1
565
+ else:
566
+ try:
567
+ size_index = size.__index__
568
+ except AttributeError:
569
+ raise TypeError(f"{size!r} is not an integer")
570
+ else:
571
+ size = size_index()
572
+ res = bytearray()
573
+ while size < 0 or len(res) < size:
574
+ b = self.read(nreadahead())
575
+ if not b:
576
+ break
577
+ res += b
578
+ if res.endswith(b"\n"):
579
+ break
580
+ return bytes(res)
581
+
582
+ def __iter__(self):
583
+ self._checkClosed()
584
+ return self
585
+
586
+ def __next__(self):
587
+ line = self.readline()
588
+ if not line:
589
+ raise StopIteration
590
+ return line
591
+
592
+ def readlines(self, hint=None):
593
+ """Return a list of lines from the stream.
594
+
595
+ hint can be specified to control the number of lines read: no more
596
+ lines will be read if the total size (in bytes/characters) of all
597
+ lines so far exceeds hint.
598
+ """
599
+ if hint is None or hint <= 0:
600
+ return list(self)
601
+ n = 0
602
+ lines = []
603
+ for line in self:
604
+ lines.append(line)
605
+ n += len(line)
606
+ if n >= hint:
607
+ break
608
+ return lines
609
+
610
+ def writelines(self, lines):
611
+ """Write a list of lines to the stream.
612
+
613
+ Line separators are not added, so it is usual for each of the lines
614
+ provided to have a line separator at the end.
615
+ """
616
+ self._checkClosed()
617
+ for line in lines:
618
+ self.write(line)
619
+
620
+ io.IOBase.register(IOBase)
621
+
622
+
623
+ class RawIOBase(IOBase):
624
+
625
+ """Base class for raw binary I/O."""
626
+
627
+ # The read() method is implemented by calling readinto(); derived
628
+ # classes that want to support read() only need to implement
629
+ # readinto() as a primitive operation. In general, readinto() can be
630
+ # more efficient than read().
631
+
632
+ # (It would be tempting to also provide an implementation of
633
+ # readinto() in terms of read(), in case the latter is a more suitable
634
+ # primitive operation, but that would lead to nasty recursion in case
635
+ # a subclass doesn't implement either.)
636
+
637
+ def read(self, size=-1):
638
+ """Read and return up to size bytes, where size is an int.
639
+
640
+ Returns an empty bytes object on EOF, or None if the object is
641
+ set not to block and has no data to read.
642
+ """
643
+ if size is None:
644
+ size = -1
645
+ if size < 0:
646
+ return self.readall()
647
+ b = bytearray(size.__index__())
648
+ n = self.readinto(b)
649
+ if n is None:
650
+ return None
651
+ del b[n:]
652
+ return bytes(b)
653
+
654
+ def readall(self):
655
+ """Read until EOF, using multiple read() call."""
656
+ res = bytearray()
657
+ while True:
658
+ data = self.read(DEFAULT_BUFFER_SIZE)
659
+ if not data:
660
+ break
661
+ res += data
662
+ if res:
663
+ return bytes(res)
664
+ else:
665
+ # b'' or None
666
+ return data
667
+
668
+ def readinto(self, b):
669
+ """Read bytes into a pre-allocated bytes-like object b.
670
+
671
+ Returns an int representing the number of bytes read (0 for EOF), or
672
+ None if the object is set not to block and has no data to read.
673
+ """
674
+ self._unsupported("readinto")
675
+
676
+ def write(self, b):
677
+ """Write the given buffer to the IO stream.
678
+
679
+ Returns the number of bytes written, which may be less than the
680
+ length of b in bytes.
681
+ """
682
+ self._unsupported("write")
683
+
684
+ io.RawIOBase.register(RawIOBase)
685
+ from _io import FileIO
686
+ RawIOBase.register(FileIO)
687
+
688
+
689
+ class BufferedIOBase(IOBase):
690
+
691
+ """Base class for buffered IO objects.
692
+
693
+ The main difference with RawIOBase is that the read() method
694
+ supports omitting the size argument, and does not have a default
695
+ implementation that defers to readinto().
696
+
697
+ In addition, read(), readinto() and write() may raise
698
+ BlockingIOError if the underlying raw stream is in non-blocking
699
+ mode and not ready; unlike their raw counterparts, they will never
700
+ return None.
701
+
702
+ A typical implementation should not inherit from a RawIOBase
703
+ implementation, but wrap one.
704
+ """
705
+
706
+ def read(self, size=-1):
707
+ """Read and return up to size bytes, where size is an int.
708
+
709
+ If the argument is omitted, None, or negative, reads and
710
+ returns all data until EOF.
711
+
712
+ If the argument is positive, and the underlying raw stream is
713
+ not 'interactive', multiple raw reads may be issued to satisfy
714
+ the byte count (unless EOF is reached first). But for
715
+ interactive raw streams (XXX and for pipes?), at most one raw
716
+ read will be issued, and a short result does not imply that
717
+ EOF is imminent.
718
+
719
+ Returns an empty bytes array on EOF.
720
+
721
+ Raises BlockingIOError if the underlying raw stream has no
722
+ data at the moment.
723
+ """
724
+ self._unsupported("read")
725
+
726
+ def read1(self, size=-1):
727
+ """Read up to size bytes with at most one read() system call,
728
+ where size is an int.
729
+ """
730
+ self._unsupported("read1")
731
+
732
+ def readinto(self, b):
733
+ """Read bytes into a pre-allocated bytes-like object b.
734
+
735
+ Like read(), this may issue multiple reads to the underlying raw
736
+ stream, unless the latter is 'interactive'.
737
+
738
+ Returns an int representing the number of bytes read (0 for EOF).
739
+
740
+ Raises BlockingIOError if the underlying raw stream has no
741
+ data at the moment.
742
+ """
743
+
744
+ return self._readinto(b, read1=False)
745
+
746
+ def readinto1(self, b):
747
+ """Read bytes into buffer *b*, using at most one system call
748
+
749
+ Returns an int representing the number of bytes read (0 for EOF).
750
+
751
+ Raises BlockingIOError if the underlying raw stream has no
752
+ data at the moment.
753
+ """
754
+
755
+ return self._readinto(b, read1=True)
756
+
757
+ def _readinto(self, b, read1):
758
+ if not isinstance(b, memoryview):
759
+ b = memoryview(b)
760
+ b = b.cast('B')
761
+
762
+ if read1:
763
+ data = self.read1(len(b))
764
+ else:
765
+ data = self.read(len(b))
766
+ n = len(data)
767
+
768
+ b[:n] = data
769
+
770
+ return n
771
+
772
+ def write(self, b):
773
+ """Write the given bytes buffer to the IO stream.
774
+
775
+ Return the number of bytes written, which is always the length of b
776
+ in bytes.
777
+
778
+ Raises BlockingIOError if the buffer is full and the
779
+ underlying raw stream cannot accept more data at the moment.
780
+ """
781
+ self._unsupported("write")
782
+
783
+ def detach(self):
784
+ """
785
+ Separate the underlying raw stream from the buffer and return it.
786
+
787
+ After the raw stream has been detached, the buffer is in an unusable
788
+ state.
789
+ """
790
+ self._unsupported("detach")
791
+
792
+ io.BufferedIOBase.register(BufferedIOBase)
793
+
794
+
795
+ class _BufferedIOMixin(BufferedIOBase):
796
+
797
+ """A mixin implementation of BufferedIOBase with an underlying raw stream.
798
+
799
+ This passes most requests on to the underlying raw stream. It
800
+ does *not* provide implementations of read(), readinto() or
801
+ write().
802
+ """
803
+
804
+ def __init__(self, raw):
805
+ self._raw = raw
806
+
807
+ ### Positioning ###
808
+
809
+ def seek(self, pos, whence=0):
810
+ new_position = self.raw.seek(pos, whence)
811
+ if new_position < 0:
812
+ raise OSError("seek() returned an invalid position")
813
+ return new_position
814
+
815
+ def tell(self):
816
+ pos = self.raw.tell()
817
+ if pos < 0:
818
+ raise OSError("tell() returned an invalid position")
819
+ return pos
820
+
821
+ def truncate(self, pos=None):
822
+ self._checkClosed()
823
+ self._checkWritable()
824
+
825
+ # Flush the stream. We're mixing buffered I/O with lower-level I/O,
826
+ # and a flush may be necessary to synch both views of the current
827
+ # file state.
828
+ self.flush()
829
+
830
+ if pos is None:
831
+ pos = self.tell()
832
+ # XXX: Should seek() be used, instead of passing the position
833
+ # XXX directly to truncate?
834
+ return self.raw.truncate(pos)
835
+
836
+ ### Flush and close ###
837
+
838
+ def flush(self):
839
+ if self.closed:
840
+ raise ValueError("flush on closed file")
841
+ self.raw.flush()
842
+
843
+ def close(self):
844
+ if self.raw is not None and not self.closed:
845
+ try:
846
+ # may raise BlockingIOError or BrokenPipeError etc
847
+ self.flush()
848
+ finally:
849
+ self.raw.close()
850
+
851
+ def detach(self):
852
+ if self.raw is None:
853
+ raise ValueError("raw stream already detached")
854
+ self.flush()
855
+ raw = self._raw
856
+ self._raw = None
857
+ return raw
858
+
859
+ ### Inquiries ###
860
+
861
+ def seekable(self):
862
+ return self.raw.seekable()
863
+
864
+ @property
865
+ def raw(self):
866
+ return self._raw
867
+
868
+ @property
869
+ def closed(self):
870
+ return self.raw.closed
871
+
872
+ @property
873
+ def name(self):
874
+ return self.raw.name
875
+
876
+ @property
877
+ def mode(self):
878
+ return self.raw.mode
879
+
880
+ def __getstate__(self):
881
+ raise TypeError(f"cannot pickle {self.__class__.__name__!r} object")
882
+
883
+ def __repr__(self):
884
+ modname = self.__class__.__module__
885
+ clsname = self.__class__.__qualname__
886
+ try:
887
+ name = self.name
888
+ except AttributeError:
889
+ return "<{}.{}>".format(modname, clsname)
890
+ else:
891
+ return "<{}.{} name={!r}>".format(modname, clsname, name)
892
+
893
+ ### Lower-level APIs ###
894
+
895
+ def fileno(self):
896
+ return self.raw.fileno()
897
+
898
+ def isatty(self):
899
+ return self.raw.isatty()
900
+
901
+
902
+ class BytesIO(BufferedIOBase):
903
+
904
+ """Buffered I/O implementation using an in-memory bytes buffer."""
905
+
906
+ # Initialize _buffer as soon as possible since it's used by __del__()
907
+ # which calls close()
908
+ _buffer = None
909
+
910
+ def __init__(self, initial_bytes=None):
911
+ buf = bytearray()
912
+ if initial_bytes is not None:
913
+ buf += initial_bytes
914
+ self._buffer = buf
915
+ self._pos = 0
916
+
917
+ def __getstate__(self):
918
+ if self.closed:
919
+ raise ValueError("__getstate__ on closed file")
920
+ return self.__dict__.copy()
921
+
922
+ def getvalue(self):
923
+ """Return the bytes value (contents) of the buffer
924
+ """
925
+ if self.closed:
926
+ raise ValueError("getvalue on closed file")
927
+ return bytes(self._buffer)
928
+
929
+ def getbuffer(self):
930
+ """Return a readable and writable view of the buffer.
931
+ """
932
+ if self.closed:
933
+ raise ValueError("getbuffer on closed file")
934
+ return memoryview(self._buffer)
935
+
936
+ def close(self):
937
+ if self._buffer is not None:
938
+ self._buffer.clear()
939
+ super().close()
940
+
941
+ def read(self, size=-1):
942
+ if self.closed:
943
+ raise ValueError("read from closed file")
944
+ if size is None:
945
+ size = -1
946
+ else:
947
+ try:
948
+ size_index = size.__index__
949
+ except AttributeError:
950
+ raise TypeError(f"{size!r} is not an integer")
951
+ else:
952
+ size = size_index()
953
+ if size < 0:
954
+ size = len(self._buffer)
955
+ if len(self._buffer) <= self._pos:
956
+ return b""
957
+ newpos = min(len(self._buffer), self._pos + size)
958
+ b = self._buffer[self._pos : newpos]
959
+ self._pos = newpos
960
+ return bytes(b)
961
+
962
+ def read1(self, size=-1):
963
+ """This is the same as read.
964
+ """
965
+ return self.read(size)
966
+
967
+ def write(self, b):
968
+ if self.closed:
969
+ raise ValueError("write to closed file")
970
+ if isinstance(b, str):
971
+ raise TypeError("can't write str to binary stream")
972
+ with memoryview(b) as view:
973
+ n = view.nbytes # Size of any bytes-like object
974
+ if n == 0:
975
+ return 0
976
+ pos = self._pos
977
+ if pos > len(self._buffer):
978
+ # Inserts null bytes between the current end of the file
979
+ # and the new write position.
980
+ padding = b'\x00' * (pos - len(self._buffer))
981
+ self._buffer += padding
982
+ self._buffer[pos:pos + n] = b
983
+ self._pos += n
984
+ return n
985
+
986
+ def seek(self, pos, whence=0):
987
+ if self.closed:
988
+ raise ValueError("seek on closed file")
989
+ try:
990
+ pos_index = pos.__index__
991
+ except AttributeError:
992
+ raise TypeError(f"{pos!r} is not an integer")
993
+ else:
994
+ pos = pos_index()
995
+ if whence == 0:
996
+ if pos < 0:
997
+ raise ValueError("negative seek position %r" % (pos,))
998
+ self._pos = pos
999
+ elif whence == 1:
1000
+ self._pos = max(0, self._pos + pos)
1001
+ elif whence == 2:
1002
+ self._pos = max(0, len(self._buffer) + pos)
1003
+ else:
1004
+ raise ValueError("unsupported whence value")
1005
+ return self._pos
1006
+
1007
+ def tell(self):
1008
+ if self.closed:
1009
+ raise ValueError("tell on closed file")
1010
+ return self._pos
1011
+
1012
+ def truncate(self, pos=None):
1013
+ if self.closed:
1014
+ raise ValueError("truncate on closed file")
1015
+ if pos is None:
1016
+ pos = self._pos
1017
+ else:
1018
+ try:
1019
+ pos_index = pos.__index__
1020
+ except AttributeError:
1021
+ raise TypeError(f"{pos!r} is not an integer")
1022
+ else:
1023
+ pos = pos_index()
1024
+ if pos < 0:
1025
+ raise ValueError("negative truncate position %r" % (pos,))
1026
+ del self._buffer[pos:]
1027
+ return pos
1028
+
1029
+ def readable(self):
1030
+ if self.closed:
1031
+ raise ValueError("I/O operation on closed file.")
1032
+ return True
1033
+
1034
+ def writable(self):
1035
+ if self.closed:
1036
+ raise ValueError("I/O operation on closed file.")
1037
+ return True
1038
+
1039
+ def seekable(self):
1040
+ if self.closed:
1041
+ raise ValueError("I/O operation on closed file.")
1042
+ return True
1043
+
1044
+
1045
+ class BufferedReader(_BufferedIOMixin):
1046
+
1047
+ """BufferedReader(raw[, buffer_size])
1048
+
1049
+ A buffer for a readable, sequential BaseRawIO object.
1050
+
1051
+ The constructor creates a BufferedReader for the given readable raw
1052
+ stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
1053
+ is used.
1054
+ """
1055
+
1056
+ def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
1057
+ """Create a new buffered reader using the given readable raw IO object.
1058
+ """
1059
+ if not raw.readable():
1060
+ raise OSError('"raw" argument must be readable.')
1061
+
1062
+ _BufferedIOMixin.__init__(self, raw)
1063
+ if buffer_size <= 0:
1064
+ raise ValueError("invalid buffer size")
1065
+ self.buffer_size = buffer_size
1066
+ self._reset_read_buf()
1067
+ self._read_lock = Lock()
1068
+
1069
+ def readable(self):
1070
+ return self.raw.readable()
1071
+
1072
+ def _reset_read_buf(self):
1073
+ self._read_buf = b""
1074
+ self._read_pos = 0
1075
+
1076
+ def read(self, size=None):
1077
+ """Read size bytes.
1078
+
1079
+ Returns exactly size bytes of data unless the underlying raw IO
1080
+ stream reaches EOF or if the call would block in non-blocking
1081
+ mode. If size is negative, read until EOF or until read() would
1082
+ block.
1083
+ """
1084
+ if size is not None and size < -1:
1085
+ raise ValueError("invalid number of bytes to read")
1086
+ with self._read_lock:
1087
+ return self._read_unlocked(size)
1088
+
1089
+ def _read_unlocked(self, n=None):
1090
+ nodata_val = b""
1091
+ empty_values = (b"", None)
1092
+ buf = self._read_buf
1093
+ pos = self._read_pos
1094
+
1095
+ # Special case for when the number of bytes to read is unspecified.
1096
+ if n is None or n == -1:
1097
+ self._reset_read_buf()
1098
+ if hasattr(self.raw, 'readall'):
1099
+ chunk = self.raw.readall()
1100
+ if chunk is None:
1101
+ return buf[pos:] or None
1102
+ else:
1103
+ return buf[pos:] + chunk
1104
+ chunks = [buf[pos:]] # Strip the consumed bytes.
1105
+ current_size = 0
1106
+ while True:
1107
+ # Read until EOF or until read() would block.
1108
+ chunk = self.raw.read()
1109
+ if chunk in empty_values:
1110
+ nodata_val = chunk
1111
+ break
1112
+ current_size += len(chunk)
1113
+ chunks.append(chunk)
1114
+ return b"".join(chunks) or nodata_val
1115
+
1116
+ # The number of bytes to read is specified, return at most n bytes.
1117
+ avail = len(buf) - pos # Length of the available buffered data.
1118
+ if n <= avail:
1119
+ # Fast path: the data to read is fully buffered.
1120
+ self._read_pos += n
1121
+ return buf[pos:pos+n]
1122
+ # Slow path: read from the stream until enough bytes are read,
1123
+ # or until an EOF occurs or until read() would block.
1124
+ chunks = [buf[pos:]]
1125
+ wanted = max(self.buffer_size, n)
1126
+ while avail < n:
1127
+ chunk = self.raw.read(wanted)
1128
+ if chunk in empty_values:
1129
+ nodata_val = chunk
1130
+ break
1131
+ avail += len(chunk)
1132
+ chunks.append(chunk)
1133
+ # n is more than avail only when an EOF occurred or when
1134
+ # read() would have blocked.
1135
+ n = min(n, avail)
1136
+ out = b"".join(chunks)
1137
+ self._read_buf = out[n:] # Save the extra data in the buffer.
1138
+ self._read_pos = 0
1139
+ return out[:n] if out else nodata_val
1140
+
1141
+ def peek(self, size=0):
1142
+ """Returns buffered bytes without advancing the position.
1143
+
1144
+ The argument indicates a desired minimal number of bytes; we
1145
+ do at most one raw read to satisfy it. We never return more
1146
+ than self.buffer_size.
1147
+ """
1148
+ with self._read_lock:
1149
+ return self._peek_unlocked(size)
1150
+
1151
+ def _peek_unlocked(self, n=0):
1152
+ want = min(n, self.buffer_size)
1153
+ have = len(self._read_buf) - self._read_pos
1154
+ if have < want or have <= 0:
1155
+ to_read = self.buffer_size - have
1156
+ current = self.raw.read(to_read)
1157
+ if current:
1158
+ self._read_buf = self._read_buf[self._read_pos:] + current
1159
+ self._read_pos = 0
1160
+ return self._read_buf[self._read_pos:]
1161
+
1162
+ def read1(self, size=-1):
1163
+ """Reads up to size bytes, with at most one read() system call."""
1164
+ # Returns up to size bytes. If at least one byte is buffered, we
1165
+ # only return buffered bytes. Otherwise, we do one raw read.
1166
+ if size < 0:
1167
+ size = self.buffer_size
1168
+ if size == 0:
1169
+ return b""
1170
+ with self._read_lock:
1171
+ self._peek_unlocked(1)
1172
+ return self._read_unlocked(
1173
+ min(size, len(self._read_buf) - self._read_pos))
1174
+
1175
+ # Implementing readinto() and readinto1() is not strictly necessary (we
1176
+ # could rely on the base class that provides an implementation in terms of
1177
+ # read() and read1()). We do it anyway to keep the _pyio implementation
1178
+ # similar to the io implementation (which implements the methods for
1179
+ # performance reasons).
1180
+ def _readinto(self, buf, read1):
1181
+ """Read data into *buf* with at most one system call."""
1182
+
1183
+ # Need to create a memoryview object of type 'b', otherwise
1184
+ # we may not be able to assign bytes to it, and slicing it
1185
+ # would create a new object.
1186
+ if not isinstance(buf, memoryview):
1187
+ buf = memoryview(buf)
1188
+ if buf.nbytes == 0:
1189
+ return 0
1190
+ buf = buf.cast('B')
1191
+
1192
+ written = 0
1193
+ with self._read_lock:
1194
+ while written < len(buf):
1195
+
1196
+ # First try to read from internal buffer
1197
+ avail = min(len(self._read_buf) - self._read_pos, len(buf))
1198
+ if avail:
1199
+ buf[written:written+avail] = \
1200
+ self._read_buf[self._read_pos:self._read_pos+avail]
1201
+ self._read_pos += avail
1202
+ written += avail
1203
+ if written == len(buf):
1204
+ break
1205
+
1206
+ # If remaining space in callers buffer is larger than
1207
+ # internal buffer, read directly into callers buffer
1208
+ if len(buf) - written > self.buffer_size:
1209
+ n = self.raw.readinto(buf[written:])
1210
+ if not n:
1211
+ break # eof
1212
+ written += n
1213
+
1214
+ # Otherwise refill internal buffer - unless we're
1215
+ # in read1 mode and already got some data
1216
+ elif not (read1 and written):
1217
+ if not self._peek_unlocked(1):
1218
+ break # eof
1219
+
1220
+ # In readinto1 mode, return as soon as we have some data
1221
+ if read1 and written:
1222
+ break
1223
+
1224
+ return written
1225
+
1226
+ def tell(self):
1227
+ # GH-95782: Keep return value non-negative
1228
+ return max(_BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos, 0)
1229
+
1230
+ def seek(self, pos, whence=0):
1231
+ if whence not in valid_seek_flags:
1232
+ raise ValueError("invalid whence value")
1233
+ with self._read_lock:
1234
+ if whence == 1:
1235
+ pos -= len(self._read_buf) - self._read_pos
1236
+ pos = _BufferedIOMixin.seek(self, pos, whence)
1237
+ self._reset_read_buf()
1238
+ return pos
1239
+
1240
+ class BufferedWriter(_BufferedIOMixin):
1241
+
1242
+ """A buffer for a writeable sequential RawIO object.
1243
+
1244
+ The constructor creates a BufferedWriter for the given writeable raw
1245
+ stream. If the buffer_size is not given, it defaults to
1246
+ DEFAULT_BUFFER_SIZE.
1247
+ """
1248
+
1249
+ def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
1250
+ if not raw.writable():
1251
+ raise OSError('"raw" argument must be writable.')
1252
+
1253
+ _BufferedIOMixin.__init__(self, raw)
1254
+ if buffer_size <= 0:
1255
+ raise ValueError("invalid buffer size")
1256
+ self.buffer_size = buffer_size
1257
+ self._write_buf = bytearray()
1258
+ self._write_lock = Lock()
1259
+
1260
+ def writable(self):
1261
+ return self.raw.writable()
1262
+
1263
+ def write(self, b):
1264
+ if isinstance(b, str):
1265
+ raise TypeError("can't write str to binary stream")
1266
+ with self._write_lock:
1267
+ if self.closed:
1268
+ raise ValueError("write to closed file")
1269
+ # XXX we can implement some more tricks to try and avoid
1270
+ # partial writes
1271
+ if len(self._write_buf) > self.buffer_size:
1272
+ # We're full, so let's pre-flush the buffer. (This may
1273
+ # raise BlockingIOError with characters_written == 0.)
1274
+ self._flush_unlocked()
1275
+ before = len(self._write_buf)
1276
+ self._write_buf.extend(b)
1277
+ written = len(self._write_buf) - before
1278
+ if len(self._write_buf) > self.buffer_size:
1279
+ try:
1280
+ self._flush_unlocked()
1281
+ except BlockingIOError as e:
1282
+ if len(self._write_buf) > self.buffer_size:
1283
+ # We've hit the buffer_size. We have to accept a partial
1284
+ # write and cut back our buffer.
1285
+ overage = len(self._write_buf) - self.buffer_size
1286
+ written -= overage
1287
+ self._write_buf = self._write_buf[:self.buffer_size]
1288
+ raise BlockingIOError(e.errno, e.strerror, written)
1289
+ return written
1290
+
1291
+ def truncate(self, pos=None):
1292
+ with self._write_lock:
1293
+ self._flush_unlocked()
1294
+ if pos is None:
1295
+ pos = self.raw.tell()
1296
+ return self.raw.truncate(pos)
1297
+
1298
+ def flush(self):
1299
+ with self._write_lock:
1300
+ self._flush_unlocked()
1301
+
1302
+ def _flush_unlocked(self):
1303
+ if self.closed:
1304
+ raise ValueError("flush on closed file")
1305
+ while self._write_buf:
1306
+ try:
1307
+ n = self.raw.write(self._write_buf)
1308
+ except BlockingIOError:
1309
+ raise RuntimeError("self.raw should implement RawIOBase: it "
1310
+ "should not raise BlockingIOError")
1311
+ if n is None:
1312
+ raise BlockingIOError(
1313
+ errno.EAGAIN,
1314
+ "write could not complete without blocking", 0)
1315
+ if n > len(self._write_buf) or n < 0:
1316
+ raise OSError("write() returned incorrect number of bytes")
1317
+ del self._write_buf[:n]
1318
+
1319
+ def tell(self):
1320
+ return _BufferedIOMixin.tell(self) + len(self._write_buf)
1321
+
1322
+ def seek(self, pos, whence=0):
1323
+ if whence not in valid_seek_flags:
1324
+ raise ValueError("invalid whence value")
1325
+ with self._write_lock:
1326
+ self._flush_unlocked()
1327
+ return _BufferedIOMixin.seek(self, pos, whence)
1328
+
1329
+ def close(self):
1330
+ with self._write_lock:
1331
+ if self.raw is None or self.closed:
1332
+ return
1333
+ # We have to release the lock and call self.flush() (which will
1334
+ # probably just re-take the lock) in case flush has been overridden in
1335
+ # a subclass or the user set self.flush to something. This is the same
1336
+ # behavior as the C implementation.
1337
+ try:
1338
+ # may raise BlockingIOError or BrokenPipeError etc
1339
+ self.flush()
1340
+ finally:
1341
+ with self._write_lock:
1342
+ self.raw.close()
1343
+
1344
+
1345
+ class BufferedRWPair(BufferedIOBase):
1346
+
1347
+ """A buffered reader and writer object together.
1348
+
1349
+ A buffered reader object and buffered writer object put together to
1350
+ form a sequential IO object that can read and write. This is typically
1351
+ used with a socket or two-way pipe.
1352
+
1353
+ reader and writer are RawIOBase objects that are readable and
1354
+ writeable respectively. If the buffer_size is omitted it defaults to
1355
+ DEFAULT_BUFFER_SIZE.
1356
+ """
1357
+
1358
+ # XXX The usefulness of this (compared to having two separate IO
1359
+ # objects) is questionable.
1360
+
1361
+ def __init__(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE):
1362
+ """Constructor.
1363
+
1364
+ The arguments are two RawIO instances.
1365
+ """
1366
+ if not reader.readable():
1367
+ raise OSError('"reader" argument must be readable.')
1368
+
1369
+ if not writer.writable():
1370
+ raise OSError('"writer" argument must be writable.')
1371
+
1372
+ self.reader = BufferedReader(reader, buffer_size)
1373
+ self.writer = BufferedWriter(writer, buffer_size)
1374
+
1375
+ def read(self, size=-1):
1376
+ if size is None:
1377
+ size = -1
1378
+ return self.reader.read(size)
1379
+
1380
+ def readinto(self, b):
1381
+ return self.reader.readinto(b)
1382
+
1383
+ def write(self, b):
1384
+ return self.writer.write(b)
1385
+
1386
+ def peek(self, size=0):
1387
+ return self.reader.peek(size)
1388
+
1389
+ def read1(self, size=-1):
1390
+ return self.reader.read1(size)
1391
+
1392
+ def readinto1(self, b):
1393
+ return self.reader.readinto1(b)
1394
+
1395
+ def readable(self):
1396
+ return self.reader.readable()
1397
+
1398
+ def writable(self):
1399
+ return self.writer.writable()
1400
+
1401
+ def flush(self):
1402
+ return self.writer.flush()
1403
+
1404
+ def close(self):
1405
+ try:
1406
+ self.writer.close()
1407
+ finally:
1408
+ self.reader.close()
1409
+
1410
+ def isatty(self):
1411
+ return self.reader.isatty() or self.writer.isatty()
1412
+
1413
+ @property
1414
+ def closed(self):
1415
+ return self.writer.closed
1416
+
1417
+
1418
+ class BufferedRandom(BufferedWriter, BufferedReader):
1419
+
1420
+ """A buffered interface to random access streams.
1421
+
1422
+ The constructor creates a reader and writer for a seekable stream,
1423
+ raw, given in the first argument. If the buffer_size is omitted it
1424
+ defaults to DEFAULT_BUFFER_SIZE.
1425
+ """
1426
+
1427
+ def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
1428
+ raw._checkSeekable()
1429
+ BufferedReader.__init__(self, raw, buffer_size)
1430
+ BufferedWriter.__init__(self, raw, buffer_size)
1431
+
1432
+ def seek(self, pos, whence=0):
1433
+ if whence not in valid_seek_flags:
1434
+ raise ValueError("invalid whence value")
1435
+ self.flush()
1436
+ if self._read_buf:
1437
+ # Undo read ahead.
1438
+ with self._read_lock:
1439
+ self.raw.seek(self._read_pos - len(self._read_buf), 1)
1440
+ # First do the raw seek, then empty the read buffer, so that
1441
+ # if the raw seek fails, we don't lose buffered data forever.
1442
+ pos = self.raw.seek(pos, whence)
1443
+ with self._read_lock:
1444
+ self._reset_read_buf()
1445
+ if pos < 0:
1446
+ raise OSError("seek() returned invalid position")
1447
+ return pos
1448
+
1449
+ def tell(self):
1450
+ if self._write_buf:
1451
+ return BufferedWriter.tell(self)
1452
+ else:
1453
+ return BufferedReader.tell(self)
1454
+
1455
+ def truncate(self, pos=None):
1456
+ if pos is None:
1457
+ pos = self.tell()
1458
+ # Use seek to flush the read buffer.
1459
+ return BufferedWriter.truncate(self, pos)
1460
+
1461
+ def read(self, size=None):
1462
+ if size is None:
1463
+ size = -1
1464
+ self.flush()
1465
+ return BufferedReader.read(self, size)
1466
+
1467
+ def readinto(self, b):
1468
+ self.flush()
1469
+ return BufferedReader.readinto(self, b)
1470
+
1471
+ def peek(self, size=0):
1472
+ self.flush()
1473
+ return BufferedReader.peek(self, size)
1474
+
1475
+ def read1(self, size=-1):
1476
+ self.flush()
1477
+ return BufferedReader.read1(self, size)
1478
+
1479
+ def readinto1(self, b):
1480
+ self.flush()
1481
+ return BufferedReader.readinto1(self, b)
1482
+
1483
+ def write(self, b):
1484
+ if self._read_buf:
1485
+ # Undo readahead
1486
+ with self._read_lock:
1487
+ self.raw.seek(self._read_pos - len(self._read_buf), 1)
1488
+ self._reset_read_buf()
1489
+ return BufferedWriter.write(self, b)
1490
+
1491
+
1492
+ class FileIO(RawIOBase):
1493
+ _fd = -1
1494
+ _created = False
1495
+ _readable = False
1496
+ _writable = False
1497
+ _appending = False
1498
+ _seekable = None
1499
+ _closefd = True
1500
+
1501
+ def __init__(self, file, mode='r', closefd=True, opener=None):
1502
+ """Open a file. The mode can be 'r' (default), 'w', 'x' or 'a' for reading,
1503
+ writing, exclusive creation or appending. The file will be created if it
1504
+ doesn't exist when opened for writing or appending; it will be truncated
1505
+ when opened for writing. A FileExistsError will be raised if it already
1506
+ exists when opened for creating. Opening a file for creating implies
1507
+ writing so this mode behaves in a similar way to 'w'. Add a '+' to the mode
1508
+ to allow simultaneous reading and writing. A custom opener can be used by
1509
+ passing a callable as *opener*. The underlying file descriptor for the file
1510
+ object is then obtained by calling opener with (*name*, *flags*).
1511
+ *opener* must return an open file descriptor (passing os.open as *opener*
1512
+ results in functionality similar to passing None).
1513
+ """
1514
+ if self._fd >= 0:
1515
+ # Have to close the existing file first.
1516
+ try:
1517
+ if self._closefd:
1518
+ os.close(self._fd)
1519
+ finally:
1520
+ self._fd = -1
1521
+
1522
+ if isinstance(file, float):
1523
+ raise TypeError('integer argument expected, got float')
1524
+ if isinstance(file, int):
1525
+ fd = file
1526
+ if fd < 0:
1527
+ raise ValueError('negative file descriptor')
1528
+ else:
1529
+ fd = -1
1530
+
1531
+ if not isinstance(mode, str):
1532
+ raise TypeError('invalid mode: %s' % (mode,))
1533
+ if not set(mode) <= set('xrwab+'):
1534
+ raise ValueError('invalid mode: %s' % (mode,))
1535
+ if sum(c in 'rwax' for c in mode) != 1 or mode.count('+') > 1:
1536
+ raise ValueError('Must have exactly one of create/read/write/append '
1537
+ 'mode and at most one plus')
1538
+
1539
+ if 'x' in mode:
1540
+ self._created = True
1541
+ self._writable = True
1542
+ flags = os.O_EXCL | os.O_CREAT
1543
+ elif 'r' in mode:
1544
+ self._readable = True
1545
+ flags = 0
1546
+ elif 'w' in mode:
1547
+ self._writable = True
1548
+ flags = os.O_CREAT | os.O_TRUNC
1549
+ elif 'a' in mode:
1550
+ self._writable = True
1551
+ self._appending = True
1552
+ flags = os.O_APPEND | os.O_CREAT
1553
+
1554
+ if '+' in mode:
1555
+ self._readable = True
1556
+ self._writable = True
1557
+
1558
+ if self._readable and self._writable:
1559
+ flags |= os.O_RDWR
1560
+ elif self._readable:
1561
+ flags |= os.O_RDONLY
1562
+ else:
1563
+ flags |= os.O_WRONLY
1564
+
1565
+ flags |= getattr(os, 'O_BINARY', 0)
1566
+
1567
+ noinherit_flag = (getattr(os, 'O_NOINHERIT', 0) or
1568
+ getattr(os, 'O_CLOEXEC', 0))
1569
+ flags |= noinherit_flag
1570
+
1571
+ owned_fd = None
1572
+ try:
1573
+ if fd < 0:
1574
+ if not closefd:
1575
+ raise ValueError('Cannot use closefd=False with file name')
1576
+ if opener is None:
1577
+ fd = os.open(file, flags, 0o666)
1578
+ else:
1579
+ fd = opener(file, flags)
1580
+ if not isinstance(fd, int):
1581
+ raise TypeError('expected integer from opener')
1582
+ if fd < 0:
1583
+ raise OSError('Negative file descriptor')
1584
+ owned_fd = fd
1585
+ if not noinherit_flag:
1586
+ os.set_inheritable(fd, False)
1587
+
1588
+ self._closefd = closefd
1589
+ fdfstat = os.fstat(fd)
1590
+ try:
1591
+ if stat.S_ISDIR(fdfstat.st_mode):
1592
+ raise IsADirectoryError(errno.EISDIR,
1593
+ os.strerror(errno.EISDIR), file)
1594
+ except AttributeError:
1595
+ # Ignore the AttributeError if stat.S_ISDIR or errno.EISDIR
1596
+ # don't exist.
1597
+ pass
1598
+ self._blksize = getattr(fdfstat, 'st_blksize', 0)
1599
+ if self._blksize <= 1:
1600
+ self._blksize = DEFAULT_BUFFER_SIZE
1601
+
1602
+ if _setmode:
1603
+ # don't translate newlines (\r\n <=> \n)
1604
+ _setmode(fd, os.O_BINARY)
1605
+
1606
+ self.name = file
1607
+ if self._appending:
1608
+ # For consistent behaviour, we explicitly seek to the
1609
+ # end of file (otherwise, it might be done only on the
1610
+ # first write()).
1611
+ try:
1612
+ os.lseek(fd, 0, SEEK_END)
1613
+ except OSError as e:
1614
+ if e.errno != errno.ESPIPE:
1615
+ raise
1616
+ except:
1617
+ if owned_fd is not None:
1618
+ os.close(owned_fd)
1619
+ raise
1620
+ self._fd = fd
1621
+
1622
+ def __del__(self):
1623
+ if self._fd >= 0 and self._closefd and not self.closed:
1624
+ import warnings
1625
+ warnings.warn('unclosed file %r' % (self,), ResourceWarning,
1626
+ stacklevel=2, source=self)
1627
+ self.close()
1628
+
1629
+ def __getstate__(self):
1630
+ raise TypeError(f"cannot pickle {self.__class__.__name__!r} object")
1631
+
1632
+ def __repr__(self):
1633
+ class_name = '%s.%s' % (self.__class__.__module__,
1634
+ self.__class__.__qualname__)
1635
+ if self.closed:
1636
+ return '<%s [closed]>' % class_name
1637
+ try:
1638
+ name = self.name
1639
+ except AttributeError:
1640
+ return ('<%s fd=%d mode=%r closefd=%r>' %
1641
+ (class_name, self._fd, self.mode, self._closefd))
1642
+ else:
1643
+ return ('<%s name=%r mode=%r closefd=%r>' %
1644
+ (class_name, name, self.mode, self._closefd))
1645
+
1646
+ def _checkReadable(self):
1647
+ if not self._readable:
1648
+ raise UnsupportedOperation('File not open for reading')
1649
+
1650
+ def _checkWritable(self, msg=None):
1651
+ if not self._writable:
1652
+ raise UnsupportedOperation('File not open for writing')
1653
+
1654
+ def read(self, size=None):
1655
+ """Read at most size bytes, returned as bytes.
1656
+
1657
+ Only makes one system call, so less data may be returned than requested
1658
+ In non-blocking mode, returns None if no data is available.
1659
+ Return an empty bytes object at EOF.
1660
+ """
1661
+ self._checkClosed()
1662
+ self._checkReadable()
1663
+ if size is None or size < 0:
1664
+ return self.readall()
1665
+ try:
1666
+ return os.read(self._fd, size)
1667
+ except BlockingIOError:
1668
+ return None
1669
+
1670
+ def readall(self):
1671
+ """Read all data from the file, returned as bytes.
1672
+
1673
+ In non-blocking mode, returns as much as is immediately available,
1674
+ or None if no data is available. Return an empty bytes object at EOF.
1675
+ """
1676
+ self._checkClosed()
1677
+ self._checkReadable()
1678
+ bufsize = DEFAULT_BUFFER_SIZE
1679
+ try:
1680
+ pos = os.lseek(self._fd, 0, SEEK_CUR)
1681
+ end = os.fstat(self._fd).st_size
1682
+ if end >= pos:
1683
+ bufsize = end - pos + 1
1684
+ except OSError:
1685
+ pass
1686
+
1687
+ result = bytearray()
1688
+ while True:
1689
+ if len(result) >= bufsize:
1690
+ bufsize = len(result)
1691
+ bufsize += max(bufsize, DEFAULT_BUFFER_SIZE)
1692
+ n = bufsize - len(result)
1693
+ try:
1694
+ chunk = os.read(self._fd, n)
1695
+ except BlockingIOError:
1696
+ if result:
1697
+ break
1698
+ return None
1699
+ if not chunk: # reached the end of the file
1700
+ break
1701
+ result += chunk
1702
+
1703
+ return bytes(result)
1704
+
1705
+ def readinto(self, b):
1706
+ """Same as RawIOBase.readinto()."""
1707
+ m = memoryview(b).cast('B')
1708
+ data = self.read(len(m))
1709
+ n = len(data)
1710
+ m[:n] = data
1711
+ return n
1712
+
1713
+ def write(self, b):
1714
+ """Write bytes b to file, return number written.
1715
+
1716
+ Only makes one system call, so not all of the data may be written.
1717
+ The number of bytes actually written is returned. In non-blocking mode,
1718
+ returns None if the write would block.
1719
+ """
1720
+ self._checkClosed()
1721
+ self._checkWritable()
1722
+ try:
1723
+ return os.write(self._fd, b)
1724
+ except BlockingIOError:
1725
+ return None
1726
+
1727
+ def seek(self, pos, whence=SEEK_SET):
1728
+ """Move to new file position.
1729
+
1730
+ Argument offset is a byte count. Optional argument whence defaults to
1731
+ SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
1732
+ are SEEK_CUR or 1 (move relative to current position, positive or negative),
1733
+ and SEEK_END or 2 (move relative to end of file, usually negative, although
1734
+ many platforms allow seeking beyond the end of a file).
1735
+
1736
+ Note that not all file objects are seekable.
1737
+ """
1738
+ if isinstance(pos, float):
1739
+ raise TypeError('an integer is required')
1740
+ self._checkClosed()
1741
+ return os.lseek(self._fd, pos, whence)
1742
+
1743
+ def tell(self):
1744
+ """tell() -> int. Current file position.
1745
+
1746
+ Can raise OSError for non seekable files."""
1747
+ self._checkClosed()
1748
+ return os.lseek(self._fd, 0, SEEK_CUR)
1749
+
1750
+ def truncate(self, size=None):
1751
+ """Truncate the file to at most size bytes.
1752
+
1753
+ Size defaults to the current file position, as returned by tell().
1754
+ The current file position is changed to the value of size.
1755
+ """
1756
+ self._checkClosed()
1757
+ self._checkWritable()
1758
+ if size is None:
1759
+ size = self.tell()
1760
+ os.ftruncate(self._fd, size)
1761
+ return size
1762
+
1763
+ def close(self):
1764
+ """Close the file.
1765
+
1766
+ A closed file cannot be used for further I/O operations. close() may be
1767
+ called more than once without error.
1768
+ """
1769
+ if not self.closed:
1770
+ try:
1771
+ if self._closefd:
1772
+ os.close(self._fd)
1773
+ finally:
1774
+ super().close()
1775
+
1776
+ def seekable(self):
1777
+ """True if file supports random-access."""
1778
+ self._checkClosed()
1779
+ if self._seekable is None:
1780
+ try:
1781
+ self.tell()
1782
+ except OSError:
1783
+ self._seekable = False
1784
+ else:
1785
+ self._seekable = True
1786
+ return self._seekable
1787
+
1788
+ def readable(self):
1789
+ """True if file was opened in a read mode."""
1790
+ self._checkClosed()
1791
+ return self._readable
1792
+
1793
+ def writable(self):
1794
+ """True if file was opened in a write mode."""
1795
+ self._checkClosed()
1796
+ return self._writable
1797
+
1798
+ def fileno(self):
1799
+ """Return the underlying file descriptor (an integer)."""
1800
+ self._checkClosed()
1801
+ return self._fd
1802
+
1803
+ def isatty(self):
1804
+ """True if the file is connected to a TTY device."""
1805
+ self._checkClosed()
1806
+ return os.isatty(self._fd)
1807
+
1808
+ @property
1809
+ def closefd(self):
1810
+ """True if the file descriptor will be closed by close()."""
1811
+ return self._closefd
1812
+
1813
+ @property
1814
+ def mode(self):
1815
+ """String giving the file mode"""
1816
+ if self._created:
1817
+ if self._readable:
1818
+ return 'xb+'
1819
+ else:
1820
+ return 'xb'
1821
+ elif self._appending:
1822
+ if self._readable:
1823
+ return 'ab+'
1824
+ else:
1825
+ return 'ab'
1826
+ elif self._readable:
1827
+ if self._writable:
1828
+ return 'rb+'
1829
+ else:
1830
+ return 'rb'
1831
+ else:
1832
+ return 'wb'
1833
+
1834
+
1835
+ class TextIOBase(IOBase):
1836
+
1837
+ """Base class for text I/O.
1838
+
1839
+ This class provides a character and line based interface to stream
1840
+ I/O.
1841
+ """
1842
+
1843
+ def read(self, size=-1):
1844
+ """Read at most size characters from stream, where size is an int.
1845
+
1846
+ Read from underlying buffer until we have size characters or we hit EOF.
1847
+ If size is negative or omitted, read until EOF.
1848
+
1849
+ Returns a string.
1850
+ """
1851
+ self._unsupported("read")
1852
+
1853
+ def write(self, s):
1854
+ """Write string s to stream and returning an int."""
1855
+ self._unsupported("write")
1856
+
1857
+ def truncate(self, pos=None):
1858
+ """Truncate size to pos, where pos is an int."""
1859
+ self._unsupported("truncate")
1860
+
1861
+ def readline(self):
1862
+ """Read until newline or EOF.
1863
+
1864
+ Returns an empty string if EOF is hit immediately.
1865
+ """
1866
+ self._unsupported("readline")
1867
+
1868
+ def detach(self):
1869
+ """
1870
+ Separate the underlying buffer from the TextIOBase and return it.
1871
+
1872
+ After the underlying buffer has been detached, the TextIO is in an
1873
+ unusable state.
1874
+ """
1875
+ self._unsupported("detach")
1876
+
1877
+ @property
1878
+ def encoding(self):
1879
+ """Subclasses should override."""
1880
+ return None
1881
+
1882
+ @property
1883
+ def newlines(self):
1884
+ """Line endings translated so far.
1885
+
1886
+ Only line endings translated during reading are considered.
1887
+
1888
+ Subclasses should override.
1889
+ """
1890
+ return None
1891
+
1892
+ @property
1893
+ def errors(self):
1894
+ """Error setting of the decoder or encoder.
1895
+
1896
+ Subclasses should override."""
1897
+ return None
1898
+
1899
+ io.TextIOBase.register(TextIOBase)
1900
+
1901
+
1902
+ class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1903
+ r"""Codec used when reading a file in universal newlines mode. It wraps
1904
+ another incremental decoder, translating \r\n and \r into \n. It also
1905
+ records the types of newlines encountered. When used with
1906
+ translate=False, it ensures that the newline sequence is returned in
1907
+ one piece.
1908
+ """
1909
+ def __init__(self, decoder, translate, errors='strict'):
1910
+ codecs.IncrementalDecoder.__init__(self, errors=errors)
1911
+ self.translate = translate
1912
+ self.decoder = decoder
1913
+ self.seennl = 0
1914
+ self.pendingcr = False
1915
+
1916
+ def decode(self, input, final=False):
1917
+ # decode input (with the eventual \r from a previous pass)
1918
+ if self.decoder is None:
1919
+ output = input
1920
+ else:
1921
+ output = self.decoder.decode(input, final=final)
1922
+ if self.pendingcr and (output or final):
1923
+ output = "\r" + output
1924
+ self.pendingcr = False
1925
+
1926
+ # retain last \r even when not translating data:
1927
+ # then readline() is sure to get \r\n in one pass
1928
+ if output.endswith("\r") and not final:
1929
+ output = output[:-1]
1930
+ self.pendingcr = True
1931
+
1932
+ # Record which newlines are read
1933
+ crlf = output.count('\r\n')
1934
+ cr = output.count('\r') - crlf
1935
+ lf = output.count('\n') - crlf
1936
+ self.seennl |= (lf and self._LF) | (cr and self._CR) \
1937
+ | (crlf and self._CRLF)
1938
+
1939
+ if self.translate:
1940
+ if crlf:
1941
+ output = output.replace("\r\n", "\n")
1942
+ if cr:
1943
+ output = output.replace("\r", "\n")
1944
+
1945
+ return output
1946
+
1947
+ def getstate(self):
1948
+ if self.decoder is None:
1949
+ buf = b""
1950
+ flag = 0
1951
+ else:
1952
+ buf, flag = self.decoder.getstate()
1953
+ flag <<= 1
1954
+ if self.pendingcr:
1955
+ flag |= 1
1956
+ return buf, flag
1957
+
1958
+ def setstate(self, state):
1959
+ buf, flag = state
1960
+ self.pendingcr = bool(flag & 1)
1961
+ if self.decoder is not None:
1962
+ self.decoder.setstate((buf, flag >> 1))
1963
+
1964
+ def reset(self):
1965
+ self.seennl = 0
1966
+ self.pendingcr = False
1967
+ if self.decoder is not None:
1968
+ self.decoder.reset()
1969
+
1970
+ _LF = 1
1971
+ _CR = 2
1972
+ _CRLF = 4
1973
+
1974
+ @property
1975
+ def newlines(self):
1976
+ return (None,
1977
+ "\n",
1978
+ "\r",
1979
+ ("\r", "\n"),
1980
+ "\r\n",
1981
+ ("\n", "\r\n"),
1982
+ ("\r", "\r\n"),
1983
+ ("\r", "\n", "\r\n")
1984
+ )[self.seennl]
1985
+
1986
+
1987
+ class TextIOWrapper(TextIOBase):
1988
+
1989
+ r"""Character and line based layer over a BufferedIOBase object, buffer.
1990
+
1991
+ encoding gives the name of the encoding that the stream will be
1992
+ decoded or encoded with. It defaults to locale.getencoding().
1993
+
1994
+ errors determines the strictness of encoding and decoding (see the
1995
+ codecs.register) and defaults to "strict".
1996
+
1997
+ newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1998
+ handling of line endings. If it is None, universal newlines is
1999
+ enabled. With this enabled, on input, the lines endings '\n', '\r',
2000
+ or '\r\n' are translated to '\n' before being returned to the
2001
+ caller. Conversely, on output, '\n' is translated to the system
2002
+ default line separator, os.linesep. If newline is any other of its
2003
+ legal values, that newline becomes the newline when the file is read
2004
+ and it is returned untranslated. On output, '\n' is converted to the
2005
+ newline.
2006
+
2007
+ If line_buffering is True, a call to flush is implied when a call to
2008
+ write contains a newline character.
2009
+ """
2010
+
2011
+ _CHUNK_SIZE = 2048
2012
+
2013
+ # Initialize _buffer as soon as possible since it's used by __del__()
2014
+ # which calls close()
2015
+ _buffer = None
2016
+
2017
+ # The write_through argument has no effect here since this
2018
+ # implementation always writes through. The argument is present only
2019
+ # so that the signature can match the signature of the C version.
2020
+ def __init__(self, buffer, encoding=None, errors=None, newline=None,
2021
+ line_buffering=False, write_through=False):
2022
+ self._check_newline(newline)
2023
+ encoding = text_encoding(encoding)
2024
+
2025
+ if encoding == "locale":
2026
+ encoding = self._get_locale_encoding()
2027
+
2028
+ if not isinstance(encoding, str):
2029
+ raise ValueError("invalid encoding: %r" % encoding)
2030
+
2031
+ if not codecs.lookup(encoding)._is_text_encoding:
2032
+ msg = ("%r is not a text encoding; "
2033
+ "use codecs.open() to handle arbitrary codecs")
2034
+ raise LookupError(msg % encoding)
2035
+
2036
+ if errors is None:
2037
+ errors = "strict"
2038
+ else:
2039
+ if not isinstance(errors, str):
2040
+ raise ValueError("invalid errors: %r" % errors)
2041
+ if _CHECK_ERRORS:
2042
+ codecs.lookup_error(errors)
2043
+
2044
+ self._buffer = buffer
2045
+ self._decoded_chars = '' # buffer for text returned from decoder
2046
+ self._decoded_chars_used = 0 # offset into _decoded_chars for read()
2047
+ self._snapshot = None # info for reconstructing decoder state
2048
+ self._seekable = self._telling = self.buffer.seekable()
2049
+ self._has_read1 = hasattr(self.buffer, 'read1')
2050
+ self._configure(encoding, errors, newline,
2051
+ line_buffering, write_through)
2052
+
2053
+ def _check_newline(self, newline):
2054
+ if newline is not None and not isinstance(newline, str):
2055
+ raise TypeError("illegal newline type: %r" % (type(newline),))
2056
+ if newline not in (None, "", "\n", "\r", "\r\n"):
2057
+ raise ValueError("illegal newline value: %r" % (newline,))
2058
+
2059
+ def _configure(self, encoding=None, errors=None, newline=None,
2060
+ line_buffering=False, write_through=False):
2061
+ self._encoding = encoding
2062
+ self._errors = errors
2063
+ self._encoder = None
2064
+ self._decoder = None
2065
+ self._b2cratio = 0.0
2066
+
2067
+ self._readuniversal = not newline
2068
+ self._readtranslate = newline is None
2069
+ self._readnl = newline
2070
+ self._writetranslate = newline != ''
2071
+ self._writenl = newline or os.linesep
2072
+
2073
+ self._line_buffering = line_buffering
2074
+ self._write_through = write_through
2075
+
2076
+ # don't write a BOM in the middle of a file
2077
+ if self._seekable and self.writable():
2078
+ position = self.buffer.tell()
2079
+ if position != 0:
2080
+ try:
2081
+ self._get_encoder().setstate(0)
2082
+ except LookupError:
2083
+ # Sometimes the encoder doesn't exist
2084
+ pass
2085
+
2086
+ # self._snapshot is either None, or a tuple (dec_flags, next_input)
2087
+ # where dec_flags is the second (integer) item of the decoder state
2088
+ # and next_input is the chunk of input bytes that comes next after the
2089
+ # snapshot point. We use this to reconstruct decoder states in tell().
2090
+
2091
+ # Naming convention:
2092
+ # - "bytes_..." for integer variables that count input bytes
2093
+ # - "chars_..." for integer variables that count decoded characters
2094
+
2095
+ def __repr__(self):
2096
+ result = "<{}.{}".format(self.__class__.__module__,
2097
+ self.__class__.__qualname__)
2098
+ try:
2099
+ name = self.name
2100
+ except AttributeError:
2101
+ pass
2102
+ else:
2103
+ result += " name={0!r}".format(name)
2104
+ try:
2105
+ mode = self.mode
2106
+ except AttributeError:
2107
+ pass
2108
+ else:
2109
+ result += " mode={0!r}".format(mode)
2110
+ return result + " encoding={0!r}>".format(self.encoding)
2111
+
2112
+ @property
2113
+ def encoding(self):
2114
+ return self._encoding
2115
+
2116
+ @property
2117
+ def errors(self):
2118
+ return self._errors
2119
+
2120
+ @property
2121
+ def line_buffering(self):
2122
+ return self._line_buffering
2123
+
2124
+ @property
2125
+ def write_through(self):
2126
+ return self._write_through
2127
+
2128
+ @property
2129
+ def buffer(self):
2130
+ return self._buffer
2131
+
2132
+ def reconfigure(self, *,
2133
+ encoding=None, errors=None, newline=Ellipsis,
2134
+ line_buffering=None, write_through=None):
2135
+ """Reconfigure the text stream with new parameters.
2136
+
2137
+ This also flushes the stream.
2138
+ """
2139
+ if (self._decoder is not None
2140
+ and (encoding is not None or errors is not None
2141
+ or newline is not Ellipsis)):
2142
+ raise UnsupportedOperation(
2143
+ "It is not possible to set the encoding or newline of stream "
2144
+ "after the first read")
2145
+
2146
+ if errors is None:
2147
+ if encoding is None:
2148
+ errors = self._errors
2149
+ else:
2150
+ errors = 'strict'
2151
+ elif not isinstance(errors, str):
2152
+ raise TypeError("invalid errors: %r" % errors)
2153
+
2154
+ if encoding is None:
2155
+ encoding = self._encoding
2156
+ else:
2157
+ if not isinstance(encoding, str):
2158
+ raise TypeError("invalid encoding: %r" % encoding)
2159
+ if encoding == "locale":
2160
+ encoding = self._get_locale_encoding()
2161
+
2162
+ if newline is Ellipsis:
2163
+ newline = self._readnl
2164
+ self._check_newline(newline)
2165
+
2166
+ if line_buffering is None:
2167
+ line_buffering = self.line_buffering
2168
+ if write_through is None:
2169
+ write_through = self.write_through
2170
+
2171
+ self.flush()
2172
+ self._configure(encoding, errors, newline,
2173
+ line_buffering, write_through)
2174
+
2175
+ def seekable(self):
2176
+ if self.closed:
2177
+ raise ValueError("I/O operation on closed file.")
2178
+ return self._seekable
2179
+
2180
+ def readable(self):
2181
+ return self.buffer.readable()
2182
+
2183
+ def writable(self):
2184
+ return self.buffer.writable()
2185
+
2186
+ def flush(self):
2187
+ self.buffer.flush()
2188
+ self._telling = self._seekable
2189
+
2190
+ def close(self):
2191
+ if self.buffer is not None and not self.closed:
2192
+ try:
2193
+ self.flush()
2194
+ finally:
2195
+ self.buffer.close()
2196
+
2197
+ @property
2198
+ def closed(self):
2199
+ return self.buffer.closed
2200
+
2201
+ @property
2202
+ def name(self):
2203
+ return self.buffer.name
2204
+
2205
+ def fileno(self):
2206
+ return self.buffer.fileno()
2207
+
2208
+ def isatty(self):
2209
+ return self.buffer.isatty()
2210
+
2211
+ def write(self, s):
2212
+ 'Write data, where s is a str'
2213
+ if self.closed:
2214
+ raise ValueError("write to closed file")
2215
+ if not isinstance(s, str):
2216
+ raise TypeError("can't write %s to text stream" %
2217
+ s.__class__.__name__)
2218
+ length = len(s)
2219
+ haslf = (self._writetranslate or self._line_buffering) and "\n" in s
2220
+ if haslf and self._writetranslate and self._writenl != "\n":
2221
+ s = s.replace("\n", self._writenl)
2222
+ encoder = self._encoder or self._get_encoder()
2223
+ # XXX What if we were just reading?
2224
+ b = encoder.encode(s)
2225
+ self.buffer.write(b)
2226
+ if self._line_buffering and (haslf or "\r" in s):
2227
+ self.flush()
2228
+ if self._snapshot is not None:
2229
+ self._set_decoded_chars('')
2230
+ self._snapshot = None
2231
+ if self._decoder:
2232
+ self._decoder.reset()
2233
+ return length
2234
+
2235
+ def _get_encoder(self):
2236
+ make_encoder = codecs.getincrementalencoder(self._encoding)
2237
+ self._encoder = make_encoder(self._errors)
2238
+ return self._encoder
2239
+
2240
+ def _get_decoder(self):
2241
+ make_decoder = codecs.getincrementaldecoder(self._encoding)
2242
+ decoder = make_decoder(self._errors)
2243
+ if self._readuniversal:
2244
+ decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
2245
+ self._decoder = decoder
2246
+ return decoder
2247
+
2248
+ # The following three methods implement an ADT for _decoded_chars.
2249
+ # Text returned from the decoder is buffered here until the client
2250
+ # requests it by calling our read() or readline() method.
2251
+ def _set_decoded_chars(self, chars):
2252
+ """Set the _decoded_chars buffer."""
2253
+ self._decoded_chars = chars
2254
+ self._decoded_chars_used = 0
2255
+
2256
+ def _get_decoded_chars(self, n=None):
2257
+ """Advance into the _decoded_chars buffer."""
2258
+ offset = self._decoded_chars_used
2259
+ if n is None:
2260
+ chars = self._decoded_chars[offset:]
2261
+ else:
2262
+ chars = self._decoded_chars[offset:offset + n]
2263
+ self._decoded_chars_used += len(chars)
2264
+ return chars
2265
+
2266
+ def _get_locale_encoding(self):
2267
+ try:
2268
+ import locale
2269
+ except ImportError:
2270
+ # Importing locale may fail if Python is being built
2271
+ return "utf-8"
2272
+ else:
2273
+ return locale.getencoding()
2274
+
2275
+ def _rewind_decoded_chars(self, n):
2276
+ """Rewind the _decoded_chars buffer."""
2277
+ if self._decoded_chars_used < n:
2278
+ raise AssertionError("rewind decoded_chars out of bounds")
2279
+ self._decoded_chars_used -= n
2280
+
2281
+ def _read_chunk(self):
2282
+ """
2283
+ Read and decode the next chunk of data from the BufferedReader.
2284
+ """
2285
+
2286
+ # The return value is True unless EOF was reached. The decoded
2287
+ # string is placed in self._decoded_chars (replacing its previous
2288
+ # value). The entire input chunk is sent to the decoder, though
2289
+ # some of it may remain buffered in the decoder, yet to be
2290
+ # converted.
2291
+
2292
+ if self._decoder is None:
2293
+ raise ValueError("no decoder")
2294
+
2295
+ if self._telling:
2296
+ # To prepare for tell(), we need to snapshot a point in the
2297
+ # file where the decoder's input buffer is empty.
2298
+
2299
+ dec_buffer, dec_flags = self._decoder.getstate()
2300
+ # Given this, we know there was a valid snapshot point
2301
+ # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
2302
+
2303
+ # Read a chunk, decode it, and put the result in self._decoded_chars.
2304
+ if self._has_read1:
2305
+ input_chunk = self.buffer.read1(self._CHUNK_SIZE)
2306
+ else:
2307
+ input_chunk = self.buffer.read(self._CHUNK_SIZE)
2308
+ eof = not input_chunk
2309
+ decoded_chars = self._decoder.decode(input_chunk, eof)
2310
+ self._set_decoded_chars(decoded_chars)
2311
+ if decoded_chars:
2312
+ self._b2cratio = len(input_chunk) / len(self._decoded_chars)
2313
+ else:
2314
+ self._b2cratio = 0.0
2315
+
2316
+ if self._telling:
2317
+ # At the snapshot point, len(dec_buffer) bytes before the read,
2318
+ # the next input to be decoded is dec_buffer + input_chunk.
2319
+ self._snapshot = (dec_flags, dec_buffer + input_chunk)
2320
+
2321
+ return not eof
2322
+
2323
+ def _pack_cookie(self, position, dec_flags=0,
2324
+ bytes_to_feed=0, need_eof=False, chars_to_skip=0):
2325
+ # The meaning of a tell() cookie is: seek to position, set the
2326
+ # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
2327
+ # into the decoder with need_eof as the EOF flag, then skip
2328
+ # chars_to_skip characters of the decoded result. For most simple
2329
+ # decoders, tell() will often just give a byte offset in the file.
2330
+ return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
2331
+ (chars_to_skip<<192) | bool(need_eof)<<256)
2332
+
2333
+ def _unpack_cookie(self, bigint):
2334
+ rest, position = divmod(bigint, 1<<64)
2335
+ rest, dec_flags = divmod(rest, 1<<64)
2336
+ rest, bytes_to_feed = divmod(rest, 1<<64)
2337
+ need_eof, chars_to_skip = divmod(rest, 1<<64)
2338
+ return position, dec_flags, bytes_to_feed, bool(need_eof), chars_to_skip
2339
+
2340
+ def tell(self):
2341
+ if not self._seekable:
2342
+ raise UnsupportedOperation("underlying stream is not seekable")
2343
+ if not self._telling:
2344
+ raise OSError("telling position disabled by next() call")
2345
+ self.flush()
2346
+ position = self.buffer.tell()
2347
+ decoder = self._decoder
2348
+ if decoder is None or self._snapshot is None:
2349
+ if self._decoded_chars:
2350
+ # This should never happen.
2351
+ raise AssertionError("pending decoded text")
2352
+ return position
2353
+
2354
+ # Skip backward to the snapshot point (see _read_chunk).
2355
+ dec_flags, next_input = self._snapshot
2356
+ position -= len(next_input)
2357
+
2358
+ # How many decoded characters have been used up since the snapshot?
2359
+ chars_to_skip = self._decoded_chars_used
2360
+ if chars_to_skip == 0:
2361
+ # We haven't moved from the snapshot point.
2362
+ return self._pack_cookie(position, dec_flags)
2363
+
2364
+ # Starting from the snapshot position, we will walk the decoder
2365
+ # forward until it gives us enough decoded characters.
2366
+ saved_state = decoder.getstate()
2367
+ try:
2368
+ # Fast search for an acceptable start point, close to our
2369
+ # current pos.
2370
+ # Rationale: calling decoder.decode() has a large overhead
2371
+ # regardless of chunk size; we want the number of such calls to
2372
+ # be O(1) in most situations (common decoders, sensible input).
2373
+ # Actually, it will be exactly 1 for fixed-size codecs (all
2374
+ # 8-bit codecs, also UTF-16 and UTF-32).
2375
+ skip_bytes = int(self._b2cratio * chars_to_skip)
2376
+ skip_back = 1
2377
+ assert skip_bytes <= len(next_input)
2378
+ while skip_bytes > 0:
2379
+ decoder.setstate((b'', dec_flags))
2380
+ # Decode up to temptative start point
2381
+ n = len(decoder.decode(next_input[:skip_bytes]))
2382
+ if n <= chars_to_skip:
2383
+ b, d = decoder.getstate()
2384
+ if not b:
2385
+ # Before pos and no bytes buffered in decoder => OK
2386
+ dec_flags = d
2387
+ chars_to_skip -= n
2388
+ break
2389
+ # Skip back by buffered amount and reset heuristic
2390
+ skip_bytes -= len(b)
2391
+ skip_back = 1
2392
+ else:
2393
+ # We're too far ahead, skip back a bit
2394
+ skip_bytes -= skip_back
2395
+ skip_back = skip_back * 2
2396
+ else:
2397
+ skip_bytes = 0
2398
+ decoder.setstate((b'', dec_flags))
2399
+
2400
+ # Note our initial start point.
2401
+ start_pos = position + skip_bytes
2402
+ start_flags = dec_flags
2403
+ if chars_to_skip == 0:
2404
+ # We haven't moved from the start point.
2405
+ return self._pack_cookie(start_pos, start_flags)
2406
+
2407
+ # Feed the decoder one byte at a time. As we go, note the
2408
+ # nearest "safe start point" before the current location
2409
+ # (a point where the decoder has nothing buffered, so seek()
2410
+ # can safely start from there and advance to this location).
2411
+ bytes_fed = 0
2412
+ need_eof = False
2413
+ # Chars decoded since `start_pos`
2414
+ chars_decoded = 0
2415
+ for i in range(skip_bytes, len(next_input)):
2416
+ bytes_fed += 1
2417
+ chars_decoded += len(decoder.decode(next_input[i:i+1]))
2418
+ dec_buffer, dec_flags = decoder.getstate()
2419
+ if not dec_buffer and chars_decoded <= chars_to_skip:
2420
+ # Decoder buffer is empty, so this is a safe start point.
2421
+ start_pos += bytes_fed
2422
+ chars_to_skip -= chars_decoded
2423
+ start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
2424
+ if chars_decoded >= chars_to_skip:
2425
+ break
2426
+ else:
2427
+ # We didn't get enough decoded data; signal EOF to get more.
2428
+ chars_decoded += len(decoder.decode(b'', final=True))
2429
+ need_eof = True
2430
+ if chars_decoded < chars_to_skip:
2431
+ raise OSError("can't reconstruct logical file position")
2432
+
2433
+ # The returned cookie corresponds to the last safe start point.
2434
+ return self._pack_cookie(
2435
+ start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
2436
+ finally:
2437
+ decoder.setstate(saved_state)
2438
+
2439
+ def truncate(self, pos=None):
2440
+ self.flush()
2441
+ if pos is None:
2442
+ pos = self.tell()
2443
+ return self.buffer.truncate(pos)
2444
+
2445
+ def detach(self):
2446
+ if self.buffer is None:
2447
+ raise ValueError("buffer is already detached")
2448
+ self.flush()
2449
+ buffer = self._buffer
2450
+ self._buffer = None
2451
+ return buffer
2452
+
2453
+ def seek(self, cookie, whence=0):
2454
+ def _reset_encoder(position):
2455
+ """Reset the encoder (merely useful for proper BOM handling)"""
2456
+ try:
2457
+ encoder = self._encoder or self._get_encoder()
2458
+ except LookupError:
2459
+ # Sometimes the encoder doesn't exist
2460
+ pass
2461
+ else:
2462
+ if position != 0:
2463
+ encoder.setstate(0)
2464
+ else:
2465
+ encoder.reset()
2466
+
2467
+ if self.closed:
2468
+ raise ValueError("tell on closed file")
2469
+ if not self._seekable:
2470
+ raise UnsupportedOperation("underlying stream is not seekable")
2471
+ if whence == SEEK_CUR:
2472
+ if cookie != 0:
2473
+ raise UnsupportedOperation("can't do nonzero cur-relative seeks")
2474
+ # Seeking to the current position should attempt to
2475
+ # sync the underlying buffer with the current position.
2476
+ whence = 0
2477
+ cookie = self.tell()
2478
+ elif whence == SEEK_END:
2479
+ if cookie != 0:
2480
+ raise UnsupportedOperation("can't do nonzero end-relative seeks")
2481
+ self.flush()
2482
+ position = self.buffer.seek(0, whence)
2483
+ self._set_decoded_chars('')
2484
+ self._snapshot = None
2485
+ if self._decoder:
2486
+ self._decoder.reset()
2487
+ _reset_encoder(position)
2488
+ return position
2489
+ if whence != 0:
2490
+ raise ValueError("unsupported whence (%r)" % (whence,))
2491
+ if cookie < 0:
2492
+ raise ValueError("negative seek position %r" % (cookie,))
2493
+ self.flush()
2494
+
2495
+ # The strategy of seek() is to go back to the safe start point
2496
+ # and replay the effect of read(chars_to_skip) from there.
2497
+ start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
2498
+ self._unpack_cookie(cookie)
2499
+
2500
+ # Seek back to the safe start point.
2501
+ self.buffer.seek(start_pos)
2502
+ self._set_decoded_chars('')
2503
+ self._snapshot = None
2504
+
2505
+ # Restore the decoder to its state from the safe start point.
2506
+ if cookie == 0 and self._decoder:
2507
+ self._decoder.reset()
2508
+ elif self._decoder or dec_flags or chars_to_skip:
2509
+ self._decoder = self._decoder or self._get_decoder()
2510
+ self._decoder.setstate((b'', dec_flags))
2511
+ self._snapshot = (dec_flags, b'')
2512
+
2513
+ if chars_to_skip:
2514
+ # Just like _read_chunk, feed the decoder and save a snapshot.
2515
+ input_chunk = self.buffer.read(bytes_to_feed)
2516
+ self._set_decoded_chars(
2517
+ self._decoder.decode(input_chunk, need_eof))
2518
+ self._snapshot = (dec_flags, input_chunk)
2519
+
2520
+ # Skip chars_to_skip of the decoded characters.
2521
+ if len(self._decoded_chars) < chars_to_skip:
2522
+ raise OSError("can't restore logical file position")
2523
+ self._decoded_chars_used = chars_to_skip
2524
+
2525
+ _reset_encoder(cookie)
2526
+ return cookie
2527
+
2528
+ def read(self, size=None):
2529
+ self._checkReadable()
2530
+ if size is None:
2531
+ size = -1
2532
+ else:
2533
+ try:
2534
+ size_index = size.__index__
2535
+ except AttributeError:
2536
+ raise TypeError(f"{size!r} is not an integer")
2537
+ else:
2538
+ size = size_index()
2539
+ decoder = self._decoder or self._get_decoder()
2540
+ if size < 0:
2541
+ # Read everything.
2542
+ result = (self._get_decoded_chars() +
2543
+ decoder.decode(self.buffer.read(), final=True))
2544
+ if self._snapshot is not None:
2545
+ self._set_decoded_chars('')
2546
+ self._snapshot = None
2547
+ return result
2548
+ else:
2549
+ # Keep reading chunks until we have size characters to return.
2550
+ eof = False
2551
+ result = self._get_decoded_chars(size)
2552
+ while len(result) < size and not eof:
2553
+ eof = not self._read_chunk()
2554
+ result += self._get_decoded_chars(size - len(result))
2555
+ return result
2556
+
2557
+ def __next__(self):
2558
+ self._telling = False
2559
+ line = self.readline()
2560
+ if not line:
2561
+ self._snapshot = None
2562
+ self._telling = self._seekable
2563
+ raise StopIteration
2564
+ return line
2565
+
2566
+ def readline(self, size=None):
2567
+ if self.closed:
2568
+ raise ValueError("read from closed file")
2569
+ if size is None:
2570
+ size = -1
2571
+ else:
2572
+ try:
2573
+ size_index = size.__index__
2574
+ except AttributeError:
2575
+ raise TypeError(f"{size!r} is not an integer")
2576
+ else:
2577
+ size = size_index()
2578
+
2579
+ # Grab all the decoded text (we will rewind any extra bits later).
2580
+ line = self._get_decoded_chars()
2581
+
2582
+ start = 0
2583
+ # Make the decoder if it doesn't already exist.
2584
+ if not self._decoder:
2585
+ self._get_decoder()
2586
+
2587
+ pos = endpos = None
2588
+ while True:
2589
+ if self._readtranslate:
2590
+ # Newlines are already translated, only search for \n
2591
+ pos = line.find('\n', start)
2592
+ if pos >= 0:
2593
+ endpos = pos + 1
2594
+ break
2595
+ else:
2596
+ start = len(line)
2597
+
2598
+ elif self._readuniversal:
2599
+ # Universal newline search. Find any of \r, \r\n, \n
2600
+ # The decoder ensures that \r\n are not split in two pieces
2601
+
2602
+ # In C we'd look for these in parallel of course.
2603
+ nlpos = line.find("\n", start)
2604
+ crpos = line.find("\r", start)
2605
+ if crpos == -1:
2606
+ if nlpos == -1:
2607
+ # Nothing found
2608
+ start = len(line)
2609
+ else:
2610
+ # Found \n
2611
+ endpos = nlpos + 1
2612
+ break
2613
+ elif nlpos == -1:
2614
+ # Found lone \r
2615
+ endpos = crpos + 1
2616
+ break
2617
+ elif nlpos < crpos:
2618
+ # Found \n
2619
+ endpos = nlpos + 1
2620
+ break
2621
+ elif nlpos == crpos + 1:
2622
+ # Found \r\n
2623
+ endpos = crpos + 2
2624
+ break
2625
+ else:
2626
+ # Found \r
2627
+ endpos = crpos + 1
2628
+ break
2629
+ else:
2630
+ # non-universal
2631
+ pos = line.find(self._readnl)
2632
+ if pos >= 0:
2633
+ endpos = pos + len(self._readnl)
2634
+ break
2635
+
2636
+ if size >= 0 and len(line) >= size:
2637
+ endpos = size # reached length size
2638
+ break
2639
+
2640
+ # No line ending seen yet - get more data'
2641
+ while self._read_chunk():
2642
+ if self._decoded_chars:
2643
+ break
2644
+ if self._decoded_chars:
2645
+ line += self._get_decoded_chars()
2646
+ else:
2647
+ # end of file
2648
+ self._set_decoded_chars('')
2649
+ self._snapshot = None
2650
+ return line
2651
+
2652
+ if size >= 0 and endpos > size:
2653
+ endpos = size # don't exceed size
2654
+
2655
+ # Rewind _decoded_chars to just after the line ending we found.
2656
+ self._rewind_decoded_chars(len(line) - endpos)
2657
+ return line[:endpos]
2658
+
2659
+ @property
2660
+ def newlines(self):
2661
+ return self._decoder.newlines if self._decoder else None
2662
+
2663
+
2664
+ class StringIO(TextIOWrapper):
2665
+ """Text I/O implementation using an in-memory buffer.
2666
+
2667
+ The initial_value argument sets the value of object. The newline
2668
+ argument is like the one of TextIOWrapper's constructor.
2669
+ """
2670
+
2671
+ def __init__(self, initial_value="", newline="\n"):
2672
+ super(StringIO, self).__init__(BytesIO(),
2673
+ encoding="utf-8",
2674
+ errors="surrogatepass",
2675
+ newline=newline)
2676
+ # Issue #5645: make universal newlines semantics the same as in the
2677
+ # C version, even under Windows.
2678
+ if newline is None:
2679
+ self._writetranslate = False
2680
+ if initial_value is not None:
2681
+ if not isinstance(initial_value, str):
2682
+ raise TypeError("initial_value must be str or None, not {0}"
2683
+ .format(type(initial_value).__name__))
2684
+ self.write(initial_value)
2685
+ self.seek(0)
2686
+
2687
+ def getvalue(self):
2688
+ self.flush()
2689
+ decoder = self._decoder or self._get_decoder()
2690
+ old_state = decoder.getstate()
2691
+ decoder.reset()
2692
+ try:
2693
+ return decoder.decode(self.buffer.getvalue(), final=True)
2694
+ finally:
2695
+ decoder.setstate(old_state)
2696
+
2697
+ def __repr__(self):
2698
+ # TextIOWrapper tells the encoding in its repr. In StringIO,
2699
+ # that's an implementation detail.
2700
+ return object.__repr__(self)
2701
+
2702
+ @property
2703
+ def errors(self):
2704
+ return None
2705
+
2706
+ @property
2707
+ def encoding(self):
2708
+ return None
2709
+
2710
+ def detach(self):
2711
+ # This doesn't make sense on StringIO.
2712
+ self._unsupported("detach")
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_sitebuiltins.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The objects used by the site module to add custom builtins.
3
+ """
4
+
5
+ # Those objects are almost immortal and they keep a reference to their module
6
+ # globals. Defining them in the site module would keep too many references
7
+ # alive.
8
+ # Note this means this module should also avoid keep things alive in its
9
+ # globals.
10
+
11
+ import sys
12
+
13
+ class Quitter(object):
14
+ def __init__(self, name, eof):
15
+ self.name = name
16
+ self.eof = eof
17
+ def __repr__(self):
18
+ return 'Use %s() or %s to exit' % (self.name, self.eof)
19
+ def __call__(self, code=None):
20
+ # Shells like IDLE catch the SystemExit, but listen when their
21
+ # stdin wrapper is closed.
22
+ try:
23
+ sys.stdin.close()
24
+ except:
25
+ pass
26
+ raise SystemExit(code)
27
+
28
+
29
+ class _Printer(object):
30
+ """interactive prompt objects for printing the license text, a list of
31
+ contributors and the copyright notice."""
32
+
33
+ MAXLINES = 23
34
+
35
+ def __init__(self, name, data, files=(), dirs=()):
36
+ import os
37
+ self.__name = name
38
+ self.__data = data
39
+ self.__lines = None
40
+ self.__filenames = [os.path.join(dir, filename)
41
+ for dir in dirs
42
+ for filename in files]
43
+
44
+ def __setup(self):
45
+ if self.__lines:
46
+ return
47
+ data = None
48
+ for filename in self.__filenames:
49
+ try:
50
+ with open(filename, encoding='utf-8') as fp:
51
+ data = fp.read()
52
+ break
53
+ except OSError:
54
+ pass
55
+ if not data:
56
+ data = self.__data
57
+ self.__lines = data.split('\n')
58
+ self.__linecnt = len(self.__lines)
59
+
60
+ def __repr__(self):
61
+ self.__setup()
62
+ if len(self.__lines) <= self.MAXLINES:
63
+ return "\n".join(self.__lines)
64
+ else:
65
+ return "Type %s() to see the full %s text" % ((self.__name,)*2)
66
+
67
+ def __call__(self):
68
+ self.__setup()
69
+ prompt = 'Hit Return for more, or q (and Return) to quit: '
70
+ lineno = 0
71
+ while 1:
72
+ try:
73
+ for i in range(lineno, lineno + self.MAXLINES):
74
+ print(self.__lines[i])
75
+ except IndexError:
76
+ break
77
+ else:
78
+ lineno += self.MAXLINES
79
+ key = None
80
+ while key is None:
81
+ key = input(prompt)
82
+ if key not in ('', 'q'):
83
+ key = None
84
+ if key == 'q':
85
+ break
86
+
87
+
88
+ class _Helper(object):
89
+ """Define the builtin 'help'.
90
+
91
+ This is a wrapper around pydoc.help that provides a helpful message
92
+ when 'help' is typed at the Python interactive prompt.
93
+
94
+ Calling help() at the Python prompt starts an interactive help session.
95
+ Calling help(thing) prints help for the python object 'thing'.
96
+ """
97
+
98
+ def __repr__(self):
99
+ return "Type help() for interactive help, " \
100
+ "or help(object) for help about object."
101
+ def __call__(self, *args, **kwds):
102
+ import pydoc
103
+ return pydoc.help(*args, **kwds)
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_strptime.py ADDED
@@ -0,0 +1,578 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Strptime-related classes and functions.
2
+
3
+ CLASSES:
4
+ LocaleTime -- Discovers and stores locale-specific time information
5
+ TimeRE -- Creates regexes for pattern matching a string of text containing
6
+ time information
7
+
8
+ FUNCTIONS:
9
+ _getlang -- Figure out what language is being used for the locale
10
+ strptime -- Calculates the time struct represented by the passed-in string
11
+
12
+ """
13
+ import time
14
+ import locale
15
+ import calendar
16
+ from re import compile as re_compile
17
+ from re import IGNORECASE
18
+ from re import escape as re_escape
19
+ from datetime import (date as datetime_date,
20
+ timedelta as datetime_timedelta,
21
+ timezone as datetime_timezone)
22
+ from _thread import allocate_lock as _thread_allocate_lock
23
+
24
+ __all__ = []
25
+
26
+ def _getlang():
27
+ # Figure out what the current language is set to.
28
+ return locale.getlocale(locale.LC_TIME)
29
+
30
+ class LocaleTime(object):
31
+ """Stores and handles locale-specific information related to time.
32
+
33
+ ATTRIBUTES:
34
+ f_weekday -- full weekday names (7-item list)
35
+ a_weekday -- abbreviated weekday names (7-item list)
36
+ f_month -- full month names (13-item list; dummy value in [0], which
37
+ is added by code)
38
+ a_month -- abbreviated month names (13-item list, dummy value in
39
+ [0], which is added by code)
40
+ am_pm -- AM/PM representation (2-item list)
41
+ LC_date_time -- format string for date/time representation (string)
42
+ LC_date -- format string for date representation (string)
43
+ LC_time -- format string for time representation (string)
44
+ timezone -- daylight- and non-daylight-savings timezone representation
45
+ (2-item list of sets)
46
+ lang -- Language used by instance (2-item tuple)
47
+ """
48
+
49
+ def __init__(self):
50
+ """Set all attributes.
51
+
52
+ Order of methods called matters for dependency reasons.
53
+
54
+ The locale language is set at the offset and then checked again before
55
+ exiting. This is to make sure that the attributes were not set with a
56
+ mix of information from more than one locale. This would most likely
57
+ happen when using threads where one thread calls a locale-dependent
58
+ function while another thread changes the locale while the function in
59
+ the other thread is still running. Proper coding would call for
60
+ locks to prevent changing the locale while locale-dependent code is
61
+ running. The check here is done in case someone does not think about
62
+ doing this.
63
+
64
+ Only other possible issue is if someone changed the timezone and did
65
+ not call tz.tzset . That is an issue for the programmer, though,
66
+ since changing the timezone is worthless without that call.
67
+
68
+ """
69
+ self.lang = _getlang()
70
+ self.__calc_weekday()
71
+ self.__calc_month()
72
+ self.__calc_am_pm()
73
+ self.__calc_timezone()
74
+ self.__calc_date_time()
75
+ if _getlang() != self.lang:
76
+ raise ValueError("locale changed during initialization")
77
+ if time.tzname != self.tzname or time.daylight != self.daylight:
78
+ raise ValueError("timezone changed during initialization")
79
+
80
+ def __calc_weekday(self):
81
+ # Set self.a_weekday and self.f_weekday using the calendar
82
+ # module.
83
+ a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]
84
+ f_weekday = [calendar.day_name[i].lower() for i in range(7)]
85
+ self.a_weekday = a_weekday
86
+ self.f_weekday = f_weekday
87
+
88
+ def __calc_month(self):
89
+ # Set self.f_month and self.a_month using the calendar module.
90
+ a_month = [calendar.month_abbr[i].lower() for i in range(13)]
91
+ f_month = [calendar.month_name[i].lower() for i in range(13)]
92
+ self.a_month = a_month
93
+ self.f_month = f_month
94
+
95
+ def __calc_am_pm(self):
96
+ # Set self.am_pm by using time.strftime().
97
+
98
+ # The magic date (1999,3,17,hour,44,55,2,76,0) is not really that
99
+ # magical; just happened to have used it everywhere else where a
100
+ # static date was needed.
101
+ am_pm = []
102
+ for hour in (1, 22):
103
+ time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0))
104
+ am_pm.append(time.strftime("%p", time_tuple).lower())
105
+ self.am_pm = am_pm
106
+
107
+ def __calc_date_time(self):
108
+ # Set self.date_time, self.date, & self.time by using
109
+ # time.strftime().
110
+
111
+ # Use (1999,3,17,22,44,55,2,76,0) for magic date because the amount of
112
+ # overloaded numbers is minimized. The order in which searches for
113
+ # values within the format string is very important; it eliminates
114
+ # possible ambiguity for what something represents.
115
+ time_tuple = time.struct_time((1999,3,17,22,44,55,2,76,0))
116
+ date_time = [None, None, None]
117
+ date_time[0] = time.strftime("%c", time_tuple).lower()
118
+ date_time[1] = time.strftime("%x", time_tuple).lower()
119
+ date_time[2] = time.strftime("%X", time_tuple).lower()
120
+ replacement_pairs = [('%', '%%'), (self.f_weekday[2], '%A'),
121
+ (self.f_month[3], '%B'), (self.a_weekday[2], '%a'),
122
+ (self.a_month[3], '%b'), (self.am_pm[1], '%p'),
123
+ ('1999', '%Y'), ('99', '%y'), ('22', '%H'),
124
+ ('44', '%M'), ('55', '%S'), ('76', '%j'),
125
+ ('17', '%d'), ('03', '%m'), ('3', '%m'),
126
+ # '3' needed for when no leading zero.
127
+ ('2', '%w'), ('10', '%I')]
128
+ replacement_pairs.extend([(tz, "%Z") for tz_values in self.timezone
129
+ for tz in tz_values])
130
+ for offset,directive in ((0,'%c'), (1,'%x'), (2,'%X')):
131
+ current_format = date_time[offset]
132
+ for old, new in replacement_pairs:
133
+ # Must deal with possible lack of locale info
134
+ # manifesting itself as the empty string (e.g., Swedish's
135
+ # lack of AM/PM info) or a platform returning a tuple of empty
136
+ # strings (e.g., MacOS 9 having timezone as ('','')).
137
+ if old:
138
+ current_format = current_format.replace(old, new)
139
+ # If %W is used, then Sunday, 2005-01-03 will fall on week 0 since
140
+ # 2005-01-03 occurs before the first Monday of the year. Otherwise
141
+ # %U is used.
142
+ time_tuple = time.struct_time((1999,1,3,1,1,1,6,3,0))
143
+ if '00' in time.strftime(directive, time_tuple):
144
+ U_W = '%W'
145
+ else:
146
+ U_W = '%U'
147
+ date_time[offset] = current_format.replace('11', U_W)
148
+ self.LC_date_time = date_time[0]
149
+ self.LC_date = date_time[1]
150
+ self.LC_time = date_time[2]
151
+
152
+ def __calc_timezone(self):
153
+ # Set self.timezone by using time.tzname.
154
+ # Do not worry about possibility of time.tzname[0] == time.tzname[1]
155
+ # and time.daylight; handle that in strptime.
156
+ try:
157
+ time.tzset()
158
+ except AttributeError:
159
+ pass
160
+ self.tzname = time.tzname
161
+ self.daylight = time.daylight
162
+ no_saving = frozenset({"utc", "gmt", self.tzname[0].lower()})
163
+ if self.daylight:
164
+ has_saving = frozenset({self.tzname[1].lower()})
165
+ else:
166
+ has_saving = frozenset()
167
+ self.timezone = (no_saving, has_saving)
168
+
169
+
170
+ class TimeRE(dict):
171
+ """Handle conversion from format directives to regexes."""
172
+
173
+ def __init__(self, locale_time=None):
174
+ """Create keys/values.
175
+
176
+ Order of execution is important for dependency reasons.
177
+
178
+ """
179
+ if locale_time:
180
+ self.locale_time = locale_time
181
+ else:
182
+ self.locale_time = LocaleTime()
183
+ base = super()
184
+ base.__init__({
185
+ # The " [1-9]" part of the regex is to make %c from ANSI C work
186
+ 'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])",
187
+ 'f': r"(?P<f>[0-9]{1,6})",
188
+ 'H': r"(?P<H>2[0-3]|[0-1]\d|\d)",
189
+ 'I': r"(?P<I>1[0-2]|0[1-9]|[1-9])",
190
+ 'G': r"(?P<G>\d\d\d\d)",
191
+ 'j': r"(?P<j>36[0-6]|3[0-5]\d|[1-2]\d\d|0[1-9]\d|00[1-9]|[1-9]\d|0[1-9]|[1-9])",
192
+ 'm': r"(?P<m>1[0-2]|0[1-9]|[1-9])",
193
+ 'M': r"(?P<M>[0-5]\d|\d)",
194
+ 'S': r"(?P<S>6[0-1]|[0-5]\d|\d)",
195
+ 'U': r"(?P<U>5[0-3]|[0-4]\d|\d)",
196
+ 'w': r"(?P<w>[0-6])",
197
+ 'u': r"(?P<u>[1-7])",
198
+ 'V': r"(?P<V>5[0-3]|0[1-9]|[1-4]\d|\d)",
199
+ # W is set below by using 'U'
200
+ 'y': r"(?P<y>\d\d)",
201
+ #XXX: Does 'Y' need to worry about having less or more than
202
+ # 4 digits?
203
+ 'Y': r"(?P<Y>\d\d\d\d)",
204
+ 'z': r"(?P<z>[+-]\d\d:?[0-5]\d(:?[0-5]\d(\.\d{1,6})?)?|(?-i:Z))",
205
+ 'A': self.__seqToRE(self.locale_time.f_weekday, 'A'),
206
+ 'a': self.__seqToRE(self.locale_time.a_weekday, 'a'),
207
+ 'B': self.__seqToRE(self.locale_time.f_month[1:], 'B'),
208
+ 'b': self.__seqToRE(self.locale_time.a_month[1:], 'b'),
209
+ 'p': self.__seqToRE(self.locale_time.am_pm, 'p'),
210
+ 'Z': self.__seqToRE((tz for tz_names in self.locale_time.timezone
211
+ for tz in tz_names),
212
+ 'Z'),
213
+ '%': '%'})
214
+ base.__setitem__('W', base.__getitem__('U').replace('U', 'W'))
215
+ base.__setitem__('c', self.pattern(self.locale_time.LC_date_time))
216
+ base.__setitem__('x', self.pattern(self.locale_time.LC_date))
217
+ base.__setitem__('X', self.pattern(self.locale_time.LC_time))
218
+
219
+ def __seqToRE(self, to_convert, directive):
220
+ """Convert a list to a regex string for matching a directive.
221
+
222
+ Want possible matching values to be from longest to shortest. This
223
+ prevents the possibility of a match occurring for a value that also
224
+ a substring of a larger value that should have matched (e.g., 'abc'
225
+ matching when 'abcdef' should have been the match).
226
+
227
+ """
228
+ to_convert = sorted(to_convert, key=len, reverse=True)
229
+ for value in to_convert:
230
+ if value != '':
231
+ break
232
+ else:
233
+ return ''
234
+ regex = '|'.join(re_escape(stuff) for stuff in to_convert)
235
+ regex = '(?P<%s>%s' % (directive, regex)
236
+ return '%s)' % regex
237
+
238
+ def pattern(self, format):
239
+ """Return regex pattern for the format string.
240
+
241
+ Need to make sure that any characters that might be interpreted as
242
+ regex syntax are escaped.
243
+
244
+ """
245
+ processed_format = ''
246
+ # The sub() call escapes all characters that might be misconstrued
247
+ # as regex syntax. Cannot use re.escape since we have to deal with
248
+ # format directives (%m, etc.).
249
+ regex_chars = re_compile(r"([\\.^$*+?\(\){}\[\]|])")
250
+ format = regex_chars.sub(r"\\\1", format)
251
+ whitespace_replacement = re_compile(r'\s+')
252
+ format = whitespace_replacement.sub(r'\\s+', format)
253
+ while '%' in format:
254
+ directive_index = format.index('%')+1
255
+ processed_format = "%s%s%s" % (processed_format,
256
+ format[:directive_index-1],
257
+ self[format[directive_index]])
258
+ format = format[directive_index+1:]
259
+ return "%s%s" % (processed_format, format)
260
+
261
+ def compile(self, format):
262
+ """Return a compiled re object for the format string."""
263
+ return re_compile(self.pattern(format), IGNORECASE)
264
+
265
+ _cache_lock = _thread_allocate_lock()
266
+ # DO NOT modify _TimeRE_cache or _regex_cache without acquiring the cache lock
267
+ # first!
268
+ _TimeRE_cache = TimeRE()
269
+ _CACHE_MAX_SIZE = 5 # Max number of regexes stored in _regex_cache
270
+ _regex_cache = {}
271
+
272
+ def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon):
273
+ """Calculate the Julian day based on the year, week of the year, and day of
274
+ the week, with week_start_day representing whether the week of the year
275
+ assumes the week starts on Sunday or Monday (6 or 0)."""
276
+ first_weekday = datetime_date(year, 1, 1).weekday()
277
+ # If we are dealing with the %U directive (week starts on Sunday), it's
278
+ # easier to just shift the view to Sunday being the first day of the
279
+ # week.
280
+ if not week_starts_Mon:
281
+ first_weekday = (first_weekday + 1) % 7
282
+ day_of_week = (day_of_week + 1) % 7
283
+ # Need to watch out for a week 0 (when the first day of the year is not
284
+ # the same as that specified by %U or %W).
285
+ week_0_length = (7 - first_weekday) % 7
286
+ if week_of_year == 0:
287
+ return 1 + day_of_week - first_weekday
288
+ else:
289
+ days_to_week = week_0_length + (7 * (week_of_year - 1))
290
+ return 1 + days_to_week + day_of_week
291
+
292
+
293
+ def _calc_julian_from_V(iso_year, iso_week, iso_weekday):
294
+ """Calculate the Julian day based on the ISO 8601 year, week, and weekday.
295
+ ISO weeks start on Mondays, with week 01 being the week containing 4 Jan.
296
+ ISO week days range from 1 (Monday) to 7 (Sunday).
297
+ """
298
+ correction = datetime_date(iso_year, 1, 4).isoweekday() + 3
299
+ ordinal = (iso_week * 7) + iso_weekday - correction
300
+ # ordinal may be negative or 0 now, which means the date is in the previous
301
+ # calendar year
302
+ if ordinal < 1:
303
+ ordinal += datetime_date(iso_year, 1, 1).toordinal()
304
+ iso_year -= 1
305
+ ordinal -= datetime_date(iso_year, 1, 1).toordinal()
306
+ return iso_year, ordinal
307
+
308
+
309
+ def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
310
+ """Return a 2-tuple consisting of a time struct and an int containing
311
+ the number of microseconds based on the input string and the
312
+ format string."""
313
+
314
+ for index, arg in enumerate([data_string, format]):
315
+ if not isinstance(arg, str):
316
+ msg = "strptime() argument {} must be str, not {}"
317
+ raise TypeError(msg.format(index, type(arg)))
318
+
319
+ global _TimeRE_cache, _regex_cache
320
+ with _cache_lock:
321
+ locale_time = _TimeRE_cache.locale_time
322
+ if (_getlang() != locale_time.lang or
323
+ time.tzname != locale_time.tzname or
324
+ time.daylight != locale_time.daylight):
325
+ _TimeRE_cache = TimeRE()
326
+ _regex_cache.clear()
327
+ locale_time = _TimeRE_cache.locale_time
328
+ if len(_regex_cache) > _CACHE_MAX_SIZE:
329
+ _regex_cache.clear()
330
+ format_regex = _regex_cache.get(format)
331
+ if not format_regex:
332
+ try:
333
+ format_regex = _TimeRE_cache.compile(format)
334
+ # KeyError raised when a bad format is found; can be specified as
335
+ # \\, in which case it was a stray % but with a space after it
336
+ except KeyError as err:
337
+ bad_directive = err.args[0]
338
+ if bad_directive == "\\":
339
+ bad_directive = "%"
340
+ del err
341
+ raise ValueError("'%s' is a bad directive in format '%s'" %
342
+ (bad_directive, format)) from None
343
+ # IndexError only occurs when the format string is "%"
344
+ except IndexError:
345
+ raise ValueError("stray %% in format '%s'" % format) from None
346
+ _regex_cache[format] = format_regex
347
+ found = format_regex.match(data_string)
348
+ if not found:
349
+ raise ValueError("time data %r does not match format %r" %
350
+ (data_string, format))
351
+ if len(data_string) != found.end():
352
+ raise ValueError("unconverted data remains: %s" %
353
+ data_string[found.end():])
354
+
355
+ iso_year = year = None
356
+ month = day = 1
357
+ hour = minute = second = fraction = 0
358
+ tz = -1
359
+ gmtoff = None
360
+ gmtoff_fraction = 0
361
+ iso_week = week_of_year = None
362
+ week_of_year_start = None
363
+ # weekday and julian defaulted to None so as to signal need to calculate
364
+ # values
365
+ weekday = julian = None
366
+ found_dict = found.groupdict()
367
+ for group_key in found_dict.keys():
368
+ # Directives not explicitly handled below:
369
+ # c, x, X
370
+ # handled by making out of other directives
371
+ # U, W
372
+ # worthless without day of the week
373
+ if group_key == 'y':
374
+ year = int(found_dict['y'])
375
+ # Open Group specification for strptime() states that a %y
376
+ #value in the range of [00, 68] is in the century 2000, while
377
+ #[69,99] is in the century 1900
378
+ if year <= 68:
379
+ year += 2000
380
+ else:
381
+ year += 1900
382
+ elif group_key == 'Y':
383
+ year = int(found_dict['Y'])
384
+ elif group_key == 'G':
385
+ iso_year = int(found_dict['G'])
386
+ elif group_key == 'm':
387
+ month = int(found_dict['m'])
388
+ elif group_key == 'B':
389
+ month = locale_time.f_month.index(found_dict['B'].lower())
390
+ elif group_key == 'b':
391
+ month = locale_time.a_month.index(found_dict['b'].lower())
392
+ elif group_key == 'd':
393
+ day = int(found_dict['d'])
394
+ elif group_key == 'H':
395
+ hour = int(found_dict['H'])
396
+ elif group_key == 'I':
397
+ hour = int(found_dict['I'])
398
+ ampm = found_dict.get('p', '').lower()
399
+ # If there was no AM/PM indicator, we'll treat this like AM
400
+ if ampm in ('', locale_time.am_pm[0]):
401
+ # We're in AM so the hour is correct unless we're
402
+ # looking at 12 midnight.
403
+ # 12 midnight == 12 AM == hour 0
404
+ if hour == 12:
405
+ hour = 0
406
+ elif ampm == locale_time.am_pm[1]:
407
+ # We're in PM so we need to add 12 to the hour unless
408
+ # we're looking at 12 noon.
409
+ # 12 noon == 12 PM == hour 12
410
+ if hour != 12:
411
+ hour += 12
412
+ elif group_key == 'M':
413
+ minute = int(found_dict['M'])
414
+ elif group_key == 'S':
415
+ second = int(found_dict['S'])
416
+ elif group_key == 'f':
417
+ s = found_dict['f']
418
+ # Pad to always return microseconds.
419
+ s += "0" * (6 - len(s))
420
+ fraction = int(s)
421
+ elif group_key == 'A':
422
+ weekday = locale_time.f_weekday.index(found_dict['A'].lower())
423
+ elif group_key == 'a':
424
+ weekday = locale_time.a_weekday.index(found_dict['a'].lower())
425
+ elif group_key == 'w':
426
+ weekday = int(found_dict['w'])
427
+ if weekday == 0:
428
+ weekday = 6
429
+ else:
430
+ weekday -= 1
431
+ elif group_key == 'u':
432
+ weekday = int(found_dict['u'])
433
+ weekday -= 1
434
+ elif group_key == 'j':
435
+ julian = int(found_dict['j'])
436
+ elif group_key in ('U', 'W'):
437
+ week_of_year = int(found_dict[group_key])
438
+ if group_key == 'U':
439
+ # U starts week on Sunday.
440
+ week_of_year_start = 6
441
+ else:
442
+ # W starts week on Monday.
443
+ week_of_year_start = 0
444
+ elif group_key == 'V':
445
+ iso_week = int(found_dict['V'])
446
+ elif group_key == 'z':
447
+ z = found_dict['z']
448
+ if z == 'Z':
449
+ gmtoff = 0
450
+ else:
451
+ if z[3] == ':':
452
+ z = z[:3] + z[4:]
453
+ if len(z) > 5:
454
+ if z[5] != ':':
455
+ msg = f"Inconsistent use of : in {found_dict['z']}"
456
+ raise ValueError(msg)
457
+ z = z[:5] + z[6:]
458
+ hours = int(z[1:3])
459
+ minutes = int(z[3:5])
460
+ seconds = int(z[5:7] or 0)
461
+ gmtoff = (hours * 60 * 60) + (minutes * 60) + seconds
462
+ gmtoff_remainder = z[8:]
463
+ # Pad to always return microseconds.
464
+ gmtoff_remainder_padding = "0" * (6 - len(gmtoff_remainder))
465
+ gmtoff_fraction = int(gmtoff_remainder + gmtoff_remainder_padding)
466
+ if z.startswith("-"):
467
+ gmtoff = -gmtoff
468
+ gmtoff_fraction = -gmtoff_fraction
469
+ elif group_key == 'Z':
470
+ # Since -1 is default value only need to worry about setting tz if
471
+ # it can be something other than -1.
472
+ found_zone = found_dict['Z'].lower()
473
+ for value, tz_values in enumerate(locale_time.timezone):
474
+ if found_zone in tz_values:
475
+ # Deal with bad locale setup where timezone names are the
476
+ # same and yet time.daylight is true; too ambiguous to
477
+ # be able to tell what timezone has daylight savings
478
+ if (time.tzname[0] == time.tzname[1] and
479
+ time.daylight and found_zone not in ("utc", "gmt")):
480
+ break
481
+ else:
482
+ tz = value
483
+ break
484
+ # Deal with the cases where ambiguities arize
485
+ # don't assume default values for ISO week/year
486
+ if iso_year is not None:
487
+ if julian is not None:
488
+ raise ValueError("Day of the year directive '%j' is not "
489
+ "compatible with ISO year directive '%G'. "
490
+ "Use '%Y' instead.")
491
+ elif iso_week is None or weekday is None:
492
+ raise ValueError("ISO year directive '%G' must be used with "
493
+ "the ISO week directive '%V' and a weekday "
494
+ "directive ('%A', '%a', '%w', or '%u').")
495
+ elif iso_week is not None:
496
+ if year is None or weekday is None:
497
+ raise ValueError("ISO week directive '%V' must be used with "
498
+ "the ISO year directive '%G' and a weekday "
499
+ "directive ('%A', '%a', '%w', or '%u').")
500
+ else:
501
+ raise ValueError("ISO week directive '%V' is incompatible with "
502
+ "the year directive '%Y'. Use the ISO year '%G' "
503
+ "instead.")
504
+
505
+ leap_year_fix = False
506
+ if year is None:
507
+ if month == 2 and day == 29:
508
+ year = 1904 # 1904 is first leap year of 20th century
509
+ leap_year_fix = True
510
+ else:
511
+ year = 1900
512
+
513
+
514
+ # If we know the week of the year and what day of that week, we can figure
515
+ # out the Julian day of the year.
516
+ if julian is None and weekday is not None:
517
+ if week_of_year is not None:
518
+ week_starts_Mon = True if week_of_year_start == 0 else False
519
+ julian = _calc_julian_from_U_or_W(year, week_of_year, weekday,
520
+ week_starts_Mon)
521
+ elif iso_year is not None and iso_week is not None:
522
+ year, julian = _calc_julian_from_V(iso_year, iso_week, weekday + 1)
523
+ if julian is not None and julian <= 0:
524
+ year -= 1
525
+ yday = 366 if calendar.isleap(year) else 365
526
+ julian += yday
527
+
528
+ if julian is None:
529
+ # Cannot pre-calculate datetime_date() since can change in Julian
530
+ # calculation and thus could have different value for the day of
531
+ # the week calculation.
532
+ # Need to add 1 to result since first day of the year is 1, not 0.
533
+ julian = datetime_date(year, month, day).toordinal() - \
534
+ datetime_date(year, 1, 1).toordinal() + 1
535
+ else: # Assume that if they bothered to include Julian day (or if it was
536
+ # calculated above with year/week/weekday) it will be accurate.
537
+ datetime_result = datetime_date.fromordinal(
538
+ (julian - 1) +
539
+ datetime_date(year, 1, 1).toordinal())
540
+ year = datetime_result.year
541
+ month = datetime_result.month
542
+ day = datetime_result.day
543
+ if weekday is None:
544
+ weekday = datetime_date(year, month, day).weekday()
545
+ # Add timezone info
546
+ tzname = found_dict.get("Z")
547
+
548
+ if leap_year_fix:
549
+ # the caller didn't supply a year but asked for Feb 29th. We couldn't
550
+ # use the default of 1900 for computations. We set it back to ensure
551
+ # that February 29th is smaller than March 1st.
552
+ year = 1900
553
+
554
+ return (year, month, day,
555
+ hour, minute, second,
556
+ weekday, julian, tz, tzname, gmtoff), fraction, gmtoff_fraction
557
+
558
+ def _strptime_time(data_string, format="%a %b %d %H:%M:%S %Y"):
559
+ """Return a time struct based on the input string and the
560
+ format string."""
561
+ tt = _strptime(data_string, format)[0]
562
+ return time.struct_time(tt[:time._STRUCT_TM_ITEMS])
563
+
564
+ def _strptime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"):
565
+ """Return a class cls instance based on the input string and the
566
+ format string."""
567
+ tt, fraction, gmtoff_fraction = _strptime(data_string, format)
568
+ tzname, gmtoff = tt[-2:]
569
+ args = tt[:6] + (fraction,)
570
+ if gmtoff is not None:
571
+ tzdelta = datetime_timedelta(seconds=gmtoff, microseconds=gmtoff_fraction)
572
+ if tzname:
573
+ tz = datetime_timezone(tzdelta, tzname)
574
+ else:
575
+ tz = datetime_timezone(tzdelta)
576
+ args += (tz,)
577
+
578
+ return cls(*args)
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_threading_local.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Thread-local objects.
2
+
3
+ (Note that this module provides a Python version of the threading.local
4
+ class. Depending on the version of Python you're using, there may be a
5
+ faster one available. You should always import the `local` class from
6
+ `threading`.)
7
+
8
+ Thread-local objects support the management of thread-local data.
9
+ If you have data that you want to be local to a thread, simply create
10
+ a thread-local object and use its attributes:
11
+
12
+ >>> mydata = local()
13
+ >>> mydata.number = 42
14
+ >>> mydata.number
15
+ 42
16
+
17
+ You can also access the local-object's dictionary:
18
+
19
+ >>> mydata.__dict__
20
+ {'number': 42}
21
+ >>> mydata.__dict__.setdefault('widgets', [])
22
+ []
23
+ >>> mydata.widgets
24
+ []
25
+
26
+ What's important about thread-local objects is that their data are
27
+ local to a thread. If we access the data in a different thread:
28
+
29
+ >>> log = []
30
+ >>> def f():
31
+ ... items = sorted(mydata.__dict__.items())
32
+ ... log.append(items)
33
+ ... mydata.number = 11
34
+ ... log.append(mydata.number)
35
+
36
+ >>> import threading
37
+ >>> thread = threading.Thread(target=f)
38
+ >>> thread.start()
39
+ >>> thread.join()
40
+ >>> log
41
+ [[], 11]
42
+
43
+ we get different data. Furthermore, changes made in the other thread
44
+ don't affect data seen in this thread:
45
+
46
+ >>> mydata.number
47
+ 42
48
+
49
+ Of course, values you get from a local object, including a __dict__
50
+ attribute, are for whatever thread was current at the time the
51
+ attribute was read. For that reason, you generally don't want to save
52
+ these values across threads, as they apply only to the thread they
53
+ came from.
54
+
55
+ You can create custom local objects by subclassing the local class:
56
+
57
+ >>> class MyLocal(local):
58
+ ... number = 2
59
+ ... def __init__(self, /, **kw):
60
+ ... self.__dict__.update(kw)
61
+ ... def squared(self):
62
+ ... return self.number ** 2
63
+
64
+ This can be useful to support default values, methods and
65
+ initialization. Note that if you define an __init__ method, it will be
66
+ called each time the local object is used in a separate thread. This
67
+ is necessary to initialize each thread's dictionary.
68
+
69
+ Now if we create a local object:
70
+
71
+ >>> mydata = MyLocal(color='red')
72
+
73
+ Now we have a default number:
74
+
75
+ >>> mydata.number
76
+ 2
77
+
78
+ an initial color:
79
+
80
+ >>> mydata.color
81
+ 'red'
82
+ >>> del mydata.color
83
+
84
+ And a method that operates on the data:
85
+
86
+ >>> mydata.squared()
87
+ 4
88
+
89
+ As before, we can access the data in a separate thread:
90
+
91
+ >>> log = []
92
+ >>> thread = threading.Thread(target=f)
93
+ >>> thread.start()
94
+ >>> thread.join()
95
+ >>> log
96
+ [[('color', 'red')], 11]
97
+
98
+ without affecting this thread's data:
99
+
100
+ >>> mydata.number
101
+ 2
102
+ >>> mydata.color
103
+ Traceback (most recent call last):
104
+ ...
105
+ AttributeError: 'MyLocal' object has no attribute 'color'
106
+
107
+ Note that subclasses can define slots, but they are not thread
108
+ local. They are shared across threads:
109
+
110
+ >>> class MyLocal(local):
111
+ ... __slots__ = 'number'
112
+
113
+ >>> mydata = MyLocal()
114
+ >>> mydata.number = 42
115
+ >>> mydata.color = 'red'
116
+
117
+ So, the separate thread:
118
+
119
+ >>> thread = threading.Thread(target=f)
120
+ >>> thread.start()
121
+ >>> thread.join()
122
+
123
+ affects what we see:
124
+
125
+ >>> mydata.number
126
+ 11
127
+
128
+ >>> del mydata
129
+ """
130
+
131
+ from weakref import ref
132
+ from contextlib import contextmanager
133
+
134
+ __all__ = ["local"]
135
+
136
+ # We need to use objects from the threading module, but the threading
137
+ # module may also want to use our `local` class, if support for locals
138
+ # isn't compiled in to the `thread` module. This creates potential problems
139
+ # with circular imports. For that reason, we don't import `threading`
140
+ # until the bottom of this file (a hack sufficient to worm around the
141
+ # potential problems). Note that all platforms on CPython do have support
142
+ # for locals in the `thread` module, and there is no circular import problem
143
+ # then, so problems introduced by fiddling the order of imports here won't
144
+ # manifest.
145
+
146
+ class _localimpl:
147
+ """A class managing thread-local dicts"""
148
+ __slots__ = 'key', 'dicts', 'localargs', 'locallock', '__weakref__'
149
+
150
+ def __init__(self):
151
+ # The key used in the Thread objects' attribute dicts.
152
+ # We keep it a string for speed but make it unlikely to clash with
153
+ # a "real" attribute.
154
+ self.key = '_threading_local._localimpl.' + str(id(self))
155
+ # { id(Thread) -> (ref(Thread), thread-local dict) }
156
+ self.dicts = {}
157
+
158
+ def get_dict(self):
159
+ """Return the dict for the current thread. Raises KeyError if none
160
+ defined."""
161
+ thread = current_thread()
162
+ return self.dicts[id(thread)][1]
163
+
164
+ def create_dict(self):
165
+ """Create a new dict for the current thread, and return it."""
166
+ localdict = {}
167
+ key = self.key
168
+ thread = current_thread()
169
+ idt = id(thread)
170
+ def local_deleted(_, key=key):
171
+ # When the localimpl is deleted, remove the thread attribute.
172
+ thread = wrthread()
173
+ if thread is not None:
174
+ del thread.__dict__[key]
175
+ def thread_deleted(_, idt=idt):
176
+ # When the thread is deleted, remove the local dict.
177
+ # Note that this is suboptimal if the thread object gets
178
+ # caught in a reference loop. We would like to be called
179
+ # as soon as the OS-level thread ends instead.
180
+ local = wrlocal()
181
+ if local is not None:
182
+ dct = local.dicts.pop(idt)
183
+ wrlocal = ref(self, local_deleted)
184
+ wrthread = ref(thread, thread_deleted)
185
+ thread.__dict__[key] = wrlocal
186
+ self.dicts[idt] = wrthread, localdict
187
+ return localdict
188
+
189
+
190
+ @contextmanager
191
+ def _patch(self):
192
+ impl = object.__getattribute__(self, '_local__impl')
193
+ try:
194
+ dct = impl.get_dict()
195
+ except KeyError:
196
+ dct = impl.create_dict()
197
+ args, kw = impl.localargs
198
+ self.__init__(*args, **kw)
199
+ with impl.locallock:
200
+ object.__setattr__(self, '__dict__', dct)
201
+ yield
202
+
203
+
204
+ class local:
205
+ __slots__ = '_local__impl', '__dict__'
206
+
207
+ def __new__(cls, /, *args, **kw):
208
+ if (args or kw) and (cls.__init__ is object.__init__):
209
+ raise TypeError("Initialization arguments are not supported")
210
+ self = object.__new__(cls)
211
+ impl = _localimpl()
212
+ impl.localargs = (args, kw)
213
+ impl.locallock = RLock()
214
+ object.__setattr__(self, '_local__impl', impl)
215
+ # We need to create the thread dict in anticipation of
216
+ # __init__ being called, to make sure we don't call it
217
+ # again ourselves.
218
+ impl.create_dict()
219
+ return self
220
+
221
+ def __getattribute__(self, name):
222
+ with _patch(self):
223
+ return object.__getattribute__(self, name)
224
+
225
+ def __setattr__(self, name, value):
226
+ if name == '__dict__':
227
+ raise AttributeError(
228
+ "%r object attribute '__dict__' is read-only"
229
+ % self.__class__.__name__)
230
+ with _patch(self):
231
+ return object.__setattr__(self, name, value)
232
+
233
+ def __delattr__(self, name):
234
+ if name == '__dict__':
235
+ raise AttributeError(
236
+ "%r object attribute '__dict__' is read-only"
237
+ % self.__class__.__name__)
238
+ with _patch(self):
239
+ return object.__delattr__(self, name)
240
+
241
+
242
+ from threading import current_thread, RLock
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/_weakrefset.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Access WeakSet through the weakref module.
2
+ # This code is separated-out because it is needed
3
+ # by abc.py to load everything else at startup.
4
+
5
+ from _weakref import ref
6
+ from types import GenericAlias
7
+
8
+ __all__ = ['WeakSet']
9
+
10
+
11
+ class _IterationGuard:
12
+ # This context manager registers itself in the current iterators of the
13
+ # weak container, such as to delay all removals until the context manager
14
+ # exits.
15
+ # This technique should be relatively thread-safe (since sets are).
16
+
17
+ def __init__(self, weakcontainer):
18
+ # Don't create cycles
19
+ self.weakcontainer = ref(weakcontainer)
20
+
21
+ def __enter__(self):
22
+ w = self.weakcontainer()
23
+ if w is not None:
24
+ w._iterating.add(self)
25
+ return self
26
+
27
+ def __exit__(self, e, t, b):
28
+ w = self.weakcontainer()
29
+ if w is not None:
30
+ s = w._iterating
31
+ s.remove(self)
32
+ if not s:
33
+ w._commit_removals()
34
+
35
+
36
+ class WeakSet:
37
+ def __init__(self, data=None):
38
+ self.data = set()
39
+ def _remove(item, selfref=ref(self)):
40
+ self = selfref()
41
+ if self is not None:
42
+ if self._iterating:
43
+ self._pending_removals.append(item)
44
+ else:
45
+ self.data.discard(item)
46
+ self._remove = _remove
47
+ # A list of keys to be removed
48
+ self._pending_removals = []
49
+ self._iterating = set()
50
+ if data is not None:
51
+ self.update(data)
52
+
53
+ def _commit_removals(self):
54
+ pop = self._pending_removals.pop
55
+ discard = self.data.discard
56
+ while True:
57
+ try:
58
+ item = pop()
59
+ except IndexError:
60
+ return
61
+ discard(item)
62
+
63
+ def __iter__(self):
64
+ with _IterationGuard(self):
65
+ for itemref in self.data:
66
+ item = itemref()
67
+ if item is not None:
68
+ # Caveat: the iterator will keep a strong reference to
69
+ # `item` until it is resumed or closed.
70
+ yield item
71
+
72
+ def __len__(self):
73
+ return len(self.data) - len(self._pending_removals)
74
+
75
+ def __contains__(self, item):
76
+ try:
77
+ wr = ref(item)
78
+ except TypeError:
79
+ return False
80
+ return wr in self.data
81
+
82
+ def __reduce__(self):
83
+ return self.__class__, (list(self),), self.__getstate__()
84
+
85
+ def add(self, item):
86
+ if self._pending_removals:
87
+ self._commit_removals()
88
+ self.data.add(ref(item, self._remove))
89
+
90
+ def clear(self):
91
+ if self._pending_removals:
92
+ self._commit_removals()
93
+ self.data.clear()
94
+
95
+ def copy(self):
96
+ return self.__class__(self)
97
+
98
+ def pop(self):
99
+ if self._pending_removals:
100
+ self._commit_removals()
101
+ while True:
102
+ try:
103
+ itemref = self.data.pop()
104
+ except KeyError:
105
+ raise KeyError('pop from empty WeakSet') from None
106
+ item = itemref()
107
+ if item is not None:
108
+ return item
109
+
110
+ def remove(self, item):
111
+ if self._pending_removals:
112
+ self._commit_removals()
113
+ self.data.remove(ref(item))
114
+
115
+ def discard(self, item):
116
+ if self._pending_removals:
117
+ self._commit_removals()
118
+ self.data.discard(ref(item))
119
+
120
+ def update(self, other):
121
+ if self._pending_removals:
122
+ self._commit_removals()
123
+ for element in other:
124
+ self.add(element)
125
+
126
+ def __ior__(self, other):
127
+ self.update(other)
128
+ return self
129
+
130
+ def difference(self, other):
131
+ newset = self.copy()
132
+ newset.difference_update(other)
133
+ return newset
134
+ __sub__ = difference
135
+
136
+ def difference_update(self, other):
137
+ self.__isub__(other)
138
+ def __isub__(self, other):
139
+ if self._pending_removals:
140
+ self._commit_removals()
141
+ if self is other:
142
+ self.data.clear()
143
+ else:
144
+ self.data.difference_update(ref(item) for item in other)
145
+ return self
146
+
147
+ def intersection(self, other):
148
+ return self.__class__(item for item in other if item in self)
149
+ __and__ = intersection
150
+
151
+ def intersection_update(self, other):
152
+ self.__iand__(other)
153
+ def __iand__(self, other):
154
+ if self._pending_removals:
155
+ self._commit_removals()
156
+ self.data.intersection_update(ref(item) for item in other)
157
+ return self
158
+
159
+ def issubset(self, other):
160
+ return self.data.issubset(ref(item) for item in other)
161
+ __le__ = issubset
162
+
163
+ def __lt__(self, other):
164
+ return self.data < set(map(ref, other))
165
+
166
+ def issuperset(self, other):
167
+ return self.data.issuperset(ref(item) for item in other)
168
+ __ge__ = issuperset
169
+
170
+ def __gt__(self, other):
171
+ return self.data > set(map(ref, other))
172
+
173
+ def __eq__(self, other):
174
+ if not isinstance(other, self.__class__):
175
+ return NotImplemented
176
+ return self.data == set(map(ref, other))
177
+
178
+ def symmetric_difference(self, other):
179
+ newset = self.copy()
180
+ newset.symmetric_difference_update(other)
181
+ return newset
182
+ __xor__ = symmetric_difference
183
+
184
+ def symmetric_difference_update(self, other):
185
+ self.__ixor__(other)
186
+ def __ixor__(self, other):
187
+ if self._pending_removals:
188
+ self._commit_removals()
189
+ if self is other:
190
+ self.data.clear()
191
+ else:
192
+ self.data.symmetric_difference_update(ref(item, self._remove) for item in other)
193
+ return self
194
+
195
+ def union(self, other):
196
+ return self.__class__(e for s in (self, other) for e in s)
197
+ __or__ = union
198
+
199
+ def isdisjoint(self, other):
200
+ return len(self.intersection(other)) == 0
201
+
202
+ def __repr__(self):
203
+ return repr(self.data)
204
+
205
+ __class_getitem__ = classmethod(GenericAlias)
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/abc.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2007 Google, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Abstract Base Classes (ABCs) according to PEP 3119."""
5
+
6
+
7
+ def abstractmethod(funcobj):
8
+ """A decorator indicating abstract methods.
9
+
10
+ Requires that the metaclass is ABCMeta or derived from it. A
11
+ class that has a metaclass derived from ABCMeta cannot be
12
+ instantiated unless all of its abstract methods are overridden.
13
+ The abstract methods can be called using any of the normal
14
+ 'super' call mechanisms. abstractmethod() may be used to declare
15
+ abstract methods for properties and descriptors.
16
+
17
+ Usage:
18
+
19
+ class C(metaclass=ABCMeta):
20
+ @abstractmethod
21
+ def my_abstract_method(self, arg1, arg2, argN):
22
+ ...
23
+ """
24
+ funcobj.__isabstractmethod__ = True
25
+ return funcobj
26
+
27
+
28
+ class abstractclassmethod(classmethod):
29
+ """A decorator indicating abstract classmethods.
30
+
31
+ Deprecated, use 'classmethod' with 'abstractmethod' instead:
32
+
33
+ class C(ABC):
34
+ @classmethod
35
+ @abstractmethod
36
+ def my_abstract_classmethod(cls, ...):
37
+ ...
38
+
39
+ """
40
+
41
+ __isabstractmethod__ = True
42
+
43
+ def __init__(self, callable):
44
+ callable.__isabstractmethod__ = True
45
+ super().__init__(callable)
46
+
47
+
48
+ class abstractstaticmethod(staticmethod):
49
+ """A decorator indicating abstract staticmethods.
50
+
51
+ Deprecated, use 'staticmethod' with 'abstractmethod' instead:
52
+
53
+ class C(ABC):
54
+ @staticmethod
55
+ @abstractmethod
56
+ def my_abstract_staticmethod(...):
57
+ ...
58
+
59
+ """
60
+
61
+ __isabstractmethod__ = True
62
+
63
+ def __init__(self, callable):
64
+ callable.__isabstractmethod__ = True
65
+ super().__init__(callable)
66
+
67
+
68
+ class abstractproperty(property):
69
+ """A decorator indicating abstract properties.
70
+
71
+ Deprecated, use 'property' with 'abstractmethod' instead:
72
+
73
+ class C(ABC):
74
+ @property
75
+ @abstractmethod
76
+ def my_abstract_property(self):
77
+ ...
78
+
79
+ """
80
+
81
+ __isabstractmethod__ = True
82
+
83
+
84
+ try:
85
+ from _abc import (get_cache_token, _abc_init, _abc_register,
86
+ _abc_instancecheck, _abc_subclasscheck, _get_dump,
87
+ _reset_registry, _reset_caches)
88
+ except ImportError:
89
+ from _py_abc import ABCMeta, get_cache_token
90
+ ABCMeta.__module__ = 'abc'
91
+ else:
92
+ class ABCMeta(type):
93
+ """Metaclass for defining Abstract Base Classes (ABCs).
94
+
95
+ Use this metaclass to create an ABC. An ABC can be subclassed
96
+ directly, and then acts as a mix-in class. You can also register
97
+ unrelated concrete classes (even built-in classes) and unrelated
98
+ ABCs as 'virtual subclasses' -- these and their descendants will
99
+ be considered subclasses of the registering ABC by the built-in
100
+ issubclass() function, but the registering ABC won't show up in
101
+ their MRO (Method Resolution Order) nor will method
102
+ implementations defined by the registering ABC be callable (not
103
+ even via super()).
104
+ """
105
+ def __new__(mcls, name, bases, namespace, /, **kwargs):
106
+ cls = super().__new__(mcls, name, bases, namespace, **kwargs)
107
+ _abc_init(cls)
108
+ return cls
109
+
110
+ def register(cls, subclass):
111
+ """Register a virtual subclass of an ABC.
112
+
113
+ Returns the subclass, to allow usage as a class decorator.
114
+ """
115
+ return _abc_register(cls, subclass)
116
+
117
+ def __instancecheck__(cls, instance):
118
+ """Override for isinstance(instance, cls)."""
119
+ return _abc_instancecheck(cls, instance)
120
+
121
+ def __subclasscheck__(cls, subclass):
122
+ """Override for issubclass(subclass, cls)."""
123
+ return _abc_subclasscheck(cls, subclass)
124
+
125
+ def _dump_registry(cls, file=None):
126
+ """Debug helper to print the ABC registry."""
127
+ print(f"Class: {cls.__module__}.{cls.__qualname__}", file=file)
128
+ print(f"Inv. counter: {get_cache_token()}", file=file)
129
+ (_abc_registry, _abc_cache, _abc_negative_cache,
130
+ _abc_negative_cache_version) = _get_dump(cls)
131
+ print(f"_abc_registry: {_abc_registry!r}", file=file)
132
+ print(f"_abc_cache: {_abc_cache!r}", file=file)
133
+ print(f"_abc_negative_cache: {_abc_negative_cache!r}", file=file)
134
+ print(f"_abc_negative_cache_version: {_abc_negative_cache_version!r}",
135
+ file=file)
136
+
137
+ def _abc_registry_clear(cls):
138
+ """Clear the registry (for debugging or testing)."""
139
+ _reset_registry(cls)
140
+
141
+ def _abc_caches_clear(cls):
142
+ """Clear the caches (for debugging or testing)."""
143
+ _reset_caches(cls)
144
+
145
+
146
+ def update_abstractmethods(cls):
147
+ """Recalculate the set of abstract methods of an abstract class.
148
+
149
+ If a class has had one of its abstract methods implemented after the
150
+ class was created, the method will not be considered implemented until
151
+ this function is called. Alternatively, if a new abstract method has been
152
+ added to the class, it will only be considered an abstract method of the
153
+ class after this function is called.
154
+
155
+ This function should be called before any use is made of the class,
156
+ usually in class decorators that add methods to the subject class.
157
+
158
+ Returns cls, to allow usage as a class decorator.
159
+
160
+ If cls is not an instance of ABCMeta, does nothing.
161
+ """
162
+ if not hasattr(cls, '__abstractmethods__'):
163
+ # We check for __abstractmethods__ here because cls might by a C
164
+ # implementation or a python implementation (especially during
165
+ # testing), and we want to handle both cases.
166
+ return cls
167
+
168
+ abstracts = set()
169
+ # Check the existing abstract methods of the parents, keep only the ones
170
+ # that are not implemented.
171
+ for scls in cls.__bases__:
172
+ for name in getattr(scls, '__abstractmethods__', ()):
173
+ value = getattr(cls, name, None)
174
+ if getattr(value, "__isabstractmethod__", False):
175
+ abstracts.add(name)
176
+ # Also add any other newly added abstract methods.
177
+ for name, value in cls.__dict__.items():
178
+ if getattr(value, "__isabstractmethod__", False):
179
+ abstracts.add(name)
180
+ cls.__abstractmethods__ = frozenset(abstracts)
181
+ return cls
182
+
183
+
184
+ class ABC(metaclass=ABCMeta):
185
+ """Helper class that provides a standard way to create an ABC using
186
+ inheritance.
187
+ """
188
+ __slots__ = ()
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/aifc.py ADDED
@@ -0,0 +1,984 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stuff to parse AIFF-C and AIFF files.
2
+
3
+ Unless explicitly stated otherwise, the description below is true
4
+ both for AIFF-C files and AIFF files.
5
+
6
+ An AIFF-C file has the following structure.
7
+
8
+ +-----------------+
9
+ | FORM |
10
+ +-----------------+
11
+ | <size> |
12
+ +----+------------+
13
+ | | AIFC |
14
+ | +------------+
15
+ | | <chunks> |
16
+ | | . |
17
+ | | . |
18
+ | | . |
19
+ +----+------------+
20
+
21
+ An AIFF file has the string "AIFF" instead of "AIFC".
22
+
23
+ A chunk consists of an identifier (4 bytes) followed by a size (4 bytes,
24
+ big endian order), followed by the data. The size field does not include
25
+ the size of the 8 byte header.
26
+
27
+ The following chunk types are recognized.
28
+
29
+ FVER
30
+ <version number of AIFF-C defining document> (AIFF-C only).
31
+ MARK
32
+ <# of markers> (2 bytes)
33
+ list of markers:
34
+ <marker ID> (2 bytes, must be > 0)
35
+ <position> (4 bytes)
36
+ <marker name> ("pstring")
37
+ COMM
38
+ <# of channels> (2 bytes)
39
+ <# of sound frames> (4 bytes)
40
+ <size of the samples> (2 bytes)
41
+ <sampling frequency> (10 bytes, IEEE 80-bit extended
42
+ floating point)
43
+ in AIFF-C files only:
44
+ <compression type> (4 bytes)
45
+ <human-readable version of compression type> ("pstring")
46
+ SSND
47
+ <offset> (4 bytes, not used by this program)
48
+ <blocksize> (4 bytes, not used by this program)
49
+ <sound data>
50
+
51
+ A pstring consists of 1 byte length, a string of characters, and 0 or 1
52
+ byte pad to make the total length even.
53
+
54
+ Usage.
55
+
56
+ Reading AIFF files:
57
+ f = aifc.open(file, 'r')
58
+ where file is either the name of a file or an open file pointer.
59
+ The open file pointer must have methods read(), seek(), and close().
60
+ In some types of audio files, if the setpos() method is not used,
61
+ the seek() method is not necessary.
62
+
63
+ This returns an instance of a class with the following public methods:
64
+ getnchannels() -- returns number of audio channels (1 for
65
+ mono, 2 for stereo)
66
+ getsampwidth() -- returns sample width in bytes
67
+ getframerate() -- returns sampling frequency
68
+ getnframes() -- returns number of audio frames
69
+ getcomptype() -- returns compression type ('NONE' for AIFF files)
70
+ getcompname() -- returns human-readable version of
71
+ compression type ('not compressed' for AIFF files)
72
+ getparams() -- returns a namedtuple consisting of all of the
73
+ above in the above order
74
+ getmarkers() -- get the list of marks in the audio file or None
75
+ if there are no marks
76
+ getmark(id) -- get mark with the specified id (raises an error
77
+ if the mark does not exist)
78
+ readframes(n) -- returns at most n frames of audio
79
+ rewind() -- rewind to the beginning of the audio stream
80
+ setpos(pos) -- seek to the specified position
81
+ tell() -- return the current position
82
+ close() -- close the instance (make it unusable)
83
+ The position returned by tell(), the position given to setpos() and
84
+ the position of marks are all compatible and have nothing to do with
85
+ the actual position in the file.
86
+ The close() method is called automatically when the class instance
87
+ is destroyed.
88
+
89
+ Writing AIFF files:
90
+ f = aifc.open(file, 'w')
91
+ where file is either the name of a file or an open file pointer.
92
+ The open file pointer must have methods write(), tell(), seek(), and
93
+ close().
94
+
95
+ This returns an instance of a class with the following public methods:
96
+ aiff() -- create an AIFF file (AIFF-C default)
97
+ aifc() -- create an AIFF-C file
98
+ setnchannels(n) -- set the number of channels
99
+ setsampwidth(n) -- set the sample width
100
+ setframerate(n) -- set the frame rate
101
+ setnframes(n) -- set the number of frames
102
+ setcomptype(type, name)
103
+ -- set the compression type and the
104
+ human-readable compression type
105
+ setparams(tuple)
106
+ -- set all parameters at once
107
+ setmark(id, pos, name)
108
+ -- add specified mark to the list of marks
109
+ tell() -- return current position in output file (useful
110
+ in combination with setmark())
111
+ writeframesraw(data)
112
+ -- write audio frames without pathing up the
113
+ file header
114
+ writeframes(data)
115
+ -- write audio frames and patch up the file header
116
+ close() -- patch up the file header and close the
117
+ output file
118
+ You should set the parameters before the first writeframesraw or
119
+ writeframes. The total number of frames does not need to be set,
120
+ but when it is set to the correct value, the header does not have to
121
+ be patched up.
122
+ It is best to first set all parameters, perhaps possibly the
123
+ compression type, and then write audio frames using writeframesraw.
124
+ When all frames have been written, either call writeframes(b'') or
125
+ close() to patch up the sizes in the header.
126
+ Marks can be added anytime. If there are any marks, you must call
127
+ close() after all frames have been written.
128
+ The close() method is called automatically when the class instance
129
+ is destroyed.
130
+
131
+ When a file is opened with the extension '.aiff', an AIFF file is
132
+ written, otherwise an AIFF-C file is written. This default can be
133
+ changed by calling aiff() or aifc() before the first writeframes or
134
+ writeframesraw.
135
+ """
136
+
137
+ import struct
138
+ import builtins
139
+ import warnings
140
+
141
+ __all__ = ["Error", "open"]
142
+
143
+
144
+ warnings._deprecated(__name__, remove=(3, 13))
145
+
146
+
147
+ class Error(Exception):
148
+ pass
149
+
150
+ _AIFC_version = 0xA2805140 # Version 1 of AIFF-C
151
+
152
+ def _read_long(file):
153
+ try:
154
+ return struct.unpack('>l', file.read(4))[0]
155
+ except struct.error:
156
+ raise EOFError from None
157
+
158
+ def _read_ulong(file):
159
+ try:
160
+ return struct.unpack('>L', file.read(4))[0]
161
+ except struct.error:
162
+ raise EOFError from None
163
+
164
+ def _read_short(file):
165
+ try:
166
+ return struct.unpack('>h', file.read(2))[0]
167
+ except struct.error:
168
+ raise EOFError from None
169
+
170
+ def _read_ushort(file):
171
+ try:
172
+ return struct.unpack('>H', file.read(2))[0]
173
+ except struct.error:
174
+ raise EOFError from None
175
+
176
+ def _read_string(file):
177
+ length = ord(file.read(1))
178
+ if length == 0:
179
+ data = b''
180
+ else:
181
+ data = file.read(length)
182
+ if length & 1 == 0:
183
+ dummy = file.read(1)
184
+ return data
185
+
186
+ _HUGE_VAL = 1.79769313486231e+308 # See <limits.h>
187
+
188
+ def _read_float(f): # 10 bytes
189
+ expon = _read_short(f) # 2 bytes
190
+ sign = 1
191
+ if expon < 0:
192
+ sign = -1
193
+ expon = expon + 0x8000
194
+ himant = _read_ulong(f) # 4 bytes
195
+ lomant = _read_ulong(f) # 4 bytes
196
+ if expon == himant == lomant == 0:
197
+ f = 0.0
198
+ elif expon == 0x7FFF:
199
+ f = _HUGE_VAL
200
+ else:
201
+ expon = expon - 16383
202
+ f = (himant * 0x100000000 + lomant) * pow(2.0, expon - 63)
203
+ return sign * f
204
+
205
+ def _write_short(f, x):
206
+ f.write(struct.pack('>h', x))
207
+
208
+ def _write_ushort(f, x):
209
+ f.write(struct.pack('>H', x))
210
+
211
+ def _write_long(f, x):
212
+ f.write(struct.pack('>l', x))
213
+
214
+ def _write_ulong(f, x):
215
+ f.write(struct.pack('>L', x))
216
+
217
+ def _write_string(f, s):
218
+ if len(s) > 255:
219
+ raise ValueError("string exceeds maximum pstring length")
220
+ f.write(struct.pack('B', len(s)))
221
+ f.write(s)
222
+ if len(s) & 1 == 0:
223
+ f.write(b'\x00')
224
+
225
+ def _write_float(f, x):
226
+ import math
227
+ if x < 0:
228
+ sign = 0x8000
229
+ x = x * -1
230
+ else:
231
+ sign = 0
232
+ if x == 0:
233
+ expon = 0
234
+ himant = 0
235
+ lomant = 0
236
+ else:
237
+ fmant, expon = math.frexp(x)
238
+ if expon > 16384 or fmant >= 1 or fmant != fmant: # Infinity or NaN
239
+ expon = sign|0x7FFF
240
+ himant = 0
241
+ lomant = 0
242
+ else: # Finite
243
+ expon = expon + 16382
244
+ if expon < 0: # denormalized
245
+ fmant = math.ldexp(fmant, expon)
246
+ expon = 0
247
+ expon = expon | sign
248
+ fmant = math.ldexp(fmant, 32)
249
+ fsmant = math.floor(fmant)
250
+ himant = int(fsmant)
251
+ fmant = math.ldexp(fmant - fsmant, 32)
252
+ fsmant = math.floor(fmant)
253
+ lomant = int(fsmant)
254
+ _write_ushort(f, expon)
255
+ _write_ulong(f, himant)
256
+ _write_ulong(f, lomant)
257
+
258
+ with warnings.catch_warnings():
259
+ warnings.simplefilter("ignore", DeprecationWarning)
260
+ from chunk import Chunk
261
+ from collections import namedtuple
262
+
263
+ _aifc_params = namedtuple('_aifc_params',
264
+ 'nchannels sampwidth framerate nframes comptype compname')
265
+
266
+ _aifc_params.nchannels.__doc__ = 'Number of audio channels (1 for mono, 2 for stereo)'
267
+ _aifc_params.sampwidth.__doc__ = 'Sample width in bytes'
268
+ _aifc_params.framerate.__doc__ = 'Sampling frequency'
269
+ _aifc_params.nframes.__doc__ = 'Number of audio frames'
270
+ _aifc_params.comptype.__doc__ = 'Compression type ("NONE" for AIFF files)'
271
+ _aifc_params.compname.__doc__ = ("""\
272
+ A human-readable version of the compression type
273
+ ('not compressed' for AIFF files)""")
274
+
275
+
276
+ class Aifc_read:
277
+ # Variables used in this class:
278
+ #
279
+ # These variables are available to the user though appropriate
280
+ # methods of this class:
281
+ # _file -- the open file with methods read(), close(), and seek()
282
+ # set through the __init__() method
283
+ # _nchannels -- the number of audio channels
284
+ # available through the getnchannels() method
285
+ # _nframes -- the number of audio frames
286
+ # available through the getnframes() method
287
+ # _sampwidth -- the number of bytes per audio sample
288
+ # available through the getsampwidth() method
289
+ # _framerate -- the sampling frequency
290
+ # available through the getframerate() method
291
+ # _comptype -- the AIFF-C compression type ('NONE' if AIFF)
292
+ # available through the getcomptype() method
293
+ # _compname -- the human-readable AIFF-C compression type
294
+ # available through the getcomptype() method
295
+ # _markers -- the marks in the audio file
296
+ # available through the getmarkers() and getmark()
297
+ # methods
298
+ # _soundpos -- the position in the audio stream
299
+ # available through the tell() method, set through the
300
+ # setpos() method
301
+ #
302
+ # These variables are used internally only:
303
+ # _version -- the AIFF-C version number
304
+ # _decomp -- the decompressor from builtin module cl
305
+ # _comm_chunk_read -- 1 iff the COMM chunk has been read
306
+ # _aifc -- 1 iff reading an AIFF-C file
307
+ # _ssnd_seek_needed -- 1 iff positioned correctly in audio
308
+ # file for readframes()
309
+ # _ssnd_chunk -- instantiation of a chunk class for the SSND chunk
310
+ # _framesize -- size of one frame in the file
311
+
312
+ _file = None # Set here since __del__ checks it
313
+
314
+ def initfp(self, file):
315
+ self._version = 0
316
+ self._convert = None
317
+ self._markers = []
318
+ self._soundpos = 0
319
+ self._file = file
320
+ chunk = Chunk(file)
321
+ if chunk.getname() != b'FORM':
322
+ raise Error('file does not start with FORM id')
323
+ formdata = chunk.read(4)
324
+ if formdata == b'AIFF':
325
+ self._aifc = 0
326
+ elif formdata == b'AIFC':
327
+ self._aifc = 1
328
+ else:
329
+ raise Error('not an AIFF or AIFF-C file')
330
+ self._comm_chunk_read = 0
331
+ self._ssnd_chunk = None
332
+ while 1:
333
+ self._ssnd_seek_needed = 1
334
+ try:
335
+ chunk = Chunk(self._file)
336
+ except EOFError:
337
+ break
338
+ chunkname = chunk.getname()
339
+ if chunkname == b'COMM':
340
+ self._read_comm_chunk(chunk)
341
+ self._comm_chunk_read = 1
342
+ elif chunkname == b'SSND':
343
+ self._ssnd_chunk = chunk
344
+ dummy = chunk.read(8)
345
+ self._ssnd_seek_needed = 0
346
+ elif chunkname == b'FVER':
347
+ self._version = _read_ulong(chunk)
348
+ elif chunkname == b'MARK':
349
+ self._readmark(chunk)
350
+ chunk.skip()
351
+ if not self._comm_chunk_read or not self._ssnd_chunk:
352
+ raise Error('COMM chunk and/or SSND chunk missing')
353
+
354
+ def __init__(self, f):
355
+ if isinstance(f, str):
356
+ file_object = builtins.open(f, 'rb')
357
+ try:
358
+ self.initfp(file_object)
359
+ except:
360
+ file_object.close()
361
+ raise
362
+ else:
363
+ # assume it is an open file object already
364
+ self.initfp(f)
365
+
366
+ def __enter__(self):
367
+ return self
368
+
369
+ def __exit__(self, *args):
370
+ self.close()
371
+
372
+ #
373
+ # User visible methods.
374
+ #
375
+ def getfp(self):
376
+ return self._file
377
+
378
+ def rewind(self):
379
+ self._ssnd_seek_needed = 1
380
+ self._soundpos = 0
381
+
382
+ def close(self):
383
+ file = self._file
384
+ if file is not None:
385
+ self._file = None
386
+ file.close()
387
+
388
+ def tell(self):
389
+ return self._soundpos
390
+
391
+ def getnchannels(self):
392
+ return self._nchannels
393
+
394
+ def getnframes(self):
395
+ return self._nframes
396
+
397
+ def getsampwidth(self):
398
+ return self._sampwidth
399
+
400
+ def getframerate(self):
401
+ return self._framerate
402
+
403
+ def getcomptype(self):
404
+ return self._comptype
405
+
406
+ def getcompname(self):
407
+ return self._compname
408
+
409
+ ## def getversion(self):
410
+ ## return self._version
411
+
412
+ def getparams(self):
413
+ return _aifc_params(self.getnchannels(), self.getsampwidth(),
414
+ self.getframerate(), self.getnframes(),
415
+ self.getcomptype(), self.getcompname())
416
+
417
+ def getmarkers(self):
418
+ if len(self._markers) == 0:
419
+ return None
420
+ return self._markers
421
+
422
+ def getmark(self, id):
423
+ for marker in self._markers:
424
+ if id == marker[0]:
425
+ return marker
426
+ raise Error('marker {0!r} does not exist'.format(id))
427
+
428
+ def setpos(self, pos):
429
+ if pos < 0 or pos > self._nframes:
430
+ raise Error('position not in range')
431
+ self._soundpos = pos
432
+ self._ssnd_seek_needed = 1
433
+
434
+ def readframes(self, nframes):
435
+ if self._ssnd_seek_needed:
436
+ self._ssnd_chunk.seek(0)
437
+ dummy = self._ssnd_chunk.read(8)
438
+ pos = self._soundpos * self._framesize
439
+ if pos:
440
+ self._ssnd_chunk.seek(pos + 8)
441
+ self._ssnd_seek_needed = 0
442
+ if nframes == 0:
443
+ return b''
444
+ data = self._ssnd_chunk.read(nframes * self._framesize)
445
+ if self._convert and data:
446
+ data = self._convert(data)
447
+ self._soundpos = self._soundpos + len(data) // (self._nchannels
448
+ * self._sampwidth)
449
+ return data
450
+
451
+ #
452
+ # Internal methods.
453
+ #
454
+
455
+ def _alaw2lin(self, data):
456
+ with warnings.catch_warnings():
457
+ warnings.simplefilter('ignore', category=DeprecationWarning)
458
+ import audioop
459
+ return audioop.alaw2lin(data, 2)
460
+
461
+ def _ulaw2lin(self, data):
462
+ with warnings.catch_warnings():
463
+ warnings.simplefilter('ignore', category=DeprecationWarning)
464
+ import audioop
465
+ return audioop.ulaw2lin(data, 2)
466
+
467
+ def _adpcm2lin(self, data):
468
+ with warnings.catch_warnings():
469
+ warnings.simplefilter('ignore', category=DeprecationWarning)
470
+ import audioop
471
+ if not hasattr(self, '_adpcmstate'):
472
+ # first time
473
+ self._adpcmstate = None
474
+ data, self._adpcmstate = audioop.adpcm2lin(data, 2, self._adpcmstate)
475
+ return data
476
+
477
+ def _sowt2lin(self, data):
478
+ with warnings.catch_warnings():
479
+ warnings.simplefilter('ignore', category=DeprecationWarning)
480
+ import audioop
481
+ return audioop.byteswap(data, 2)
482
+
483
+ def _read_comm_chunk(self, chunk):
484
+ self._nchannels = _read_short(chunk)
485
+ self._nframes = _read_long(chunk)
486
+ self._sampwidth = (_read_short(chunk) + 7) // 8
487
+ self._framerate = int(_read_float(chunk))
488
+ if self._sampwidth <= 0:
489
+ raise Error('bad sample width')
490
+ if self._nchannels <= 0:
491
+ raise Error('bad # of channels')
492
+ self._framesize = self._nchannels * self._sampwidth
493
+ if self._aifc:
494
+ #DEBUG: SGI's soundeditor produces a bad size :-(
495
+ kludge = 0
496
+ if chunk.chunksize == 18:
497
+ kludge = 1
498
+ warnings.warn('Warning: bad COMM chunk size')
499
+ chunk.chunksize = 23
500
+ #DEBUG end
501
+ self._comptype = chunk.read(4)
502
+ #DEBUG start
503
+ if kludge:
504
+ length = ord(chunk.file.read(1))
505
+ if length & 1 == 0:
506
+ length = length + 1
507
+ chunk.chunksize = chunk.chunksize + length
508
+ chunk.file.seek(-1, 1)
509
+ #DEBUG end
510
+ self._compname = _read_string(chunk)
511
+ if self._comptype != b'NONE':
512
+ if self._comptype == b'G722':
513
+ self._convert = self._adpcm2lin
514
+ elif self._comptype in (b'ulaw', b'ULAW'):
515
+ self._convert = self._ulaw2lin
516
+ elif self._comptype in (b'alaw', b'ALAW'):
517
+ self._convert = self._alaw2lin
518
+ elif self._comptype in (b'sowt', b'SOWT'):
519
+ self._convert = self._sowt2lin
520
+ else:
521
+ raise Error('unsupported compression type')
522
+ self._sampwidth = 2
523
+ else:
524
+ self._comptype = b'NONE'
525
+ self._compname = b'not compressed'
526
+
527
+ def _readmark(self, chunk):
528
+ nmarkers = _read_short(chunk)
529
+ # Some files appear to contain invalid counts.
530
+ # Cope with this by testing for EOF.
531
+ try:
532
+ for i in range(nmarkers):
533
+ id = _read_short(chunk)
534
+ pos = _read_long(chunk)
535
+ name = _read_string(chunk)
536
+ if pos or name:
537
+ # some files appear to have
538
+ # dummy markers consisting of
539
+ # a position 0 and name ''
540
+ self._markers.append((id, pos, name))
541
+ except EOFError:
542
+ w = ('Warning: MARK chunk contains only %s marker%s instead of %s' %
543
+ (len(self._markers), '' if len(self._markers) == 1 else 's',
544
+ nmarkers))
545
+ warnings.warn(w)
546
+
547
+ class Aifc_write:
548
+ # Variables used in this class:
549
+ #
550
+ # These variables are user settable through appropriate methods
551
+ # of this class:
552
+ # _file -- the open file with methods write(), close(), tell(), seek()
553
+ # set through the __init__() method
554
+ # _comptype -- the AIFF-C compression type ('NONE' in AIFF)
555
+ # set through the setcomptype() or setparams() method
556
+ # _compname -- the human-readable AIFF-C compression type
557
+ # set through the setcomptype() or setparams() method
558
+ # _nchannels -- the number of audio channels
559
+ # set through the setnchannels() or setparams() method
560
+ # _sampwidth -- the number of bytes per audio sample
561
+ # set through the setsampwidth() or setparams() method
562
+ # _framerate -- the sampling frequency
563
+ # set through the setframerate() or setparams() method
564
+ # _nframes -- the number of audio frames written to the header
565
+ # set through the setnframes() or setparams() method
566
+ # _aifc -- whether we're writing an AIFF-C file or an AIFF file
567
+ # set through the aifc() method, reset through the
568
+ # aiff() method
569
+ #
570
+ # These variables are used internally only:
571
+ # _version -- the AIFF-C version number
572
+ # _comp -- the compressor from builtin module cl
573
+ # _nframeswritten -- the number of audio frames actually written
574
+ # _datalength -- the size of the audio samples written to the header
575
+ # _datawritten -- the size of the audio samples actually written
576
+
577
+ _file = None # Set here since __del__ checks it
578
+
579
+ def __init__(self, f):
580
+ if isinstance(f, str):
581
+ file_object = builtins.open(f, 'wb')
582
+ try:
583
+ self.initfp(file_object)
584
+ except:
585
+ file_object.close()
586
+ raise
587
+
588
+ # treat .aiff file extensions as non-compressed audio
589
+ if f.endswith('.aiff'):
590
+ self._aifc = 0
591
+ else:
592
+ # assume it is an open file object already
593
+ self.initfp(f)
594
+
595
+ def initfp(self, file):
596
+ self._file = file
597
+ self._version = _AIFC_version
598
+ self._comptype = b'NONE'
599
+ self._compname = b'not compressed'
600
+ self._convert = None
601
+ self._nchannels = 0
602
+ self._sampwidth = 0
603
+ self._framerate = 0
604
+ self._nframes = 0
605
+ self._nframeswritten = 0
606
+ self._datawritten = 0
607
+ self._datalength = 0
608
+ self._markers = []
609
+ self._marklength = 0
610
+ self._aifc = 1 # AIFF-C is default
611
+
612
+ def __del__(self):
613
+ self.close()
614
+
615
+ def __enter__(self):
616
+ return self
617
+
618
+ def __exit__(self, *args):
619
+ self.close()
620
+
621
+ #
622
+ # User visible methods.
623
+ #
624
+ def aiff(self):
625
+ if self._nframeswritten:
626
+ raise Error('cannot change parameters after starting to write')
627
+ self._aifc = 0
628
+
629
+ def aifc(self):
630
+ if self._nframeswritten:
631
+ raise Error('cannot change parameters after starting to write')
632
+ self._aifc = 1
633
+
634
+ def setnchannels(self, nchannels):
635
+ if self._nframeswritten:
636
+ raise Error('cannot change parameters after starting to write')
637
+ if nchannels < 1:
638
+ raise Error('bad # of channels')
639
+ self._nchannels = nchannels
640
+
641
+ def getnchannels(self):
642
+ if not self._nchannels:
643
+ raise Error('number of channels not set')
644
+ return self._nchannels
645
+
646
+ def setsampwidth(self, sampwidth):
647
+ if self._nframeswritten:
648
+ raise Error('cannot change parameters after starting to write')
649
+ if sampwidth < 1 or sampwidth > 4:
650
+ raise Error('bad sample width')
651
+ self._sampwidth = sampwidth
652
+
653
+ def getsampwidth(self):
654
+ if not self._sampwidth:
655
+ raise Error('sample width not set')
656
+ return self._sampwidth
657
+
658
+ def setframerate(self, framerate):
659
+ if self._nframeswritten:
660
+ raise Error('cannot change parameters after starting to write')
661
+ if framerate <= 0:
662
+ raise Error('bad frame rate')
663
+ self._framerate = framerate
664
+
665
+ def getframerate(self):
666
+ if not self._framerate:
667
+ raise Error('frame rate not set')
668
+ return self._framerate
669
+
670
+ def setnframes(self, nframes):
671
+ if self._nframeswritten:
672
+ raise Error('cannot change parameters after starting to write')
673
+ self._nframes = nframes
674
+
675
+ def getnframes(self):
676
+ return self._nframeswritten
677
+
678
+ def setcomptype(self, comptype, compname):
679
+ if self._nframeswritten:
680
+ raise Error('cannot change parameters after starting to write')
681
+ if comptype not in (b'NONE', b'ulaw', b'ULAW',
682
+ b'alaw', b'ALAW', b'G722', b'sowt', b'SOWT'):
683
+ raise Error('unsupported compression type')
684
+ self._comptype = comptype
685
+ self._compname = compname
686
+
687
+ def getcomptype(self):
688
+ return self._comptype
689
+
690
+ def getcompname(self):
691
+ return self._compname
692
+
693
+ ## def setversion(self, version):
694
+ ## if self._nframeswritten:
695
+ ## raise Error, 'cannot change parameters after starting to write'
696
+ ## self._version = version
697
+
698
+ def setparams(self, params):
699
+ nchannels, sampwidth, framerate, nframes, comptype, compname = params
700
+ if self._nframeswritten:
701
+ raise Error('cannot change parameters after starting to write')
702
+ if comptype not in (b'NONE', b'ulaw', b'ULAW',
703
+ b'alaw', b'ALAW', b'G722', b'sowt', b'SOWT'):
704
+ raise Error('unsupported compression type')
705
+ self.setnchannels(nchannels)
706
+ self.setsampwidth(sampwidth)
707
+ self.setframerate(framerate)
708
+ self.setnframes(nframes)
709
+ self.setcomptype(comptype, compname)
710
+
711
+ def getparams(self):
712
+ if not self._nchannels or not self._sampwidth or not self._framerate:
713
+ raise Error('not all parameters set')
714
+ return _aifc_params(self._nchannels, self._sampwidth, self._framerate,
715
+ self._nframes, self._comptype, self._compname)
716
+
717
+ def setmark(self, id, pos, name):
718
+ if id <= 0:
719
+ raise Error('marker ID must be > 0')
720
+ if pos < 0:
721
+ raise Error('marker position must be >= 0')
722
+ if not isinstance(name, bytes):
723
+ raise Error('marker name must be bytes')
724
+ for i in range(len(self._markers)):
725
+ if id == self._markers[i][0]:
726
+ self._markers[i] = id, pos, name
727
+ return
728
+ self._markers.append((id, pos, name))
729
+
730
+ def getmark(self, id):
731
+ for marker in self._markers:
732
+ if id == marker[0]:
733
+ return marker
734
+ raise Error('marker {0!r} does not exist'.format(id))
735
+
736
+ def getmarkers(self):
737
+ if len(self._markers) == 0:
738
+ return None
739
+ return self._markers
740
+
741
+ def tell(self):
742
+ return self._nframeswritten
743
+
744
+ def writeframesraw(self, data):
745
+ if not isinstance(data, (bytes, bytearray)):
746
+ data = memoryview(data).cast('B')
747
+ self._ensure_header_written(len(data))
748
+ nframes = len(data) // (self._sampwidth * self._nchannels)
749
+ if self._convert:
750
+ data = self._convert(data)
751
+ self._file.write(data)
752
+ self._nframeswritten = self._nframeswritten + nframes
753
+ self._datawritten = self._datawritten + len(data)
754
+
755
+ def writeframes(self, data):
756
+ self.writeframesraw(data)
757
+ if self._nframeswritten != self._nframes or \
758
+ self._datalength != self._datawritten:
759
+ self._patchheader()
760
+
761
+ def close(self):
762
+ if self._file is None:
763
+ return
764
+ try:
765
+ self._ensure_header_written(0)
766
+ if self._datawritten & 1:
767
+ # quick pad to even size
768
+ self._file.write(b'\x00')
769
+ self._datawritten = self._datawritten + 1
770
+ self._writemarkers()
771
+ if self._nframeswritten != self._nframes or \
772
+ self._datalength != self._datawritten or \
773
+ self._marklength:
774
+ self._patchheader()
775
+ finally:
776
+ # Prevent ref cycles
777
+ self._convert = None
778
+ f = self._file
779
+ self._file = None
780
+ f.close()
781
+
782
+ #
783
+ # Internal methods.
784
+ #
785
+
786
+ def _lin2alaw(self, data):
787
+ with warnings.catch_warnings():
788
+ warnings.simplefilter('ignore', category=DeprecationWarning)
789
+ import audioop
790
+ return audioop.lin2alaw(data, 2)
791
+
792
+ def _lin2ulaw(self, data):
793
+ with warnings.catch_warnings():
794
+ warnings.simplefilter('ignore', category=DeprecationWarning)
795
+ import audioop
796
+ return audioop.lin2ulaw(data, 2)
797
+
798
+ def _lin2adpcm(self, data):
799
+ with warnings.catch_warnings():
800
+ warnings.simplefilter('ignore', category=DeprecationWarning)
801
+ import audioop
802
+ if not hasattr(self, '_adpcmstate'):
803
+ self._adpcmstate = None
804
+ data, self._adpcmstate = audioop.lin2adpcm(data, 2, self._adpcmstate)
805
+ return data
806
+
807
+ def _lin2sowt(self, data):
808
+ with warnings.catch_warnings():
809
+ warnings.simplefilter('ignore', category=DeprecationWarning)
810
+ import audioop
811
+ return audioop.byteswap(data, 2)
812
+
813
+ def _ensure_header_written(self, datasize):
814
+ if not self._nframeswritten:
815
+ if self._comptype in (b'ULAW', b'ulaw',
816
+ b'ALAW', b'alaw', b'G722',
817
+ b'sowt', b'SOWT'):
818
+ if not self._sampwidth:
819
+ self._sampwidth = 2
820
+ if self._sampwidth != 2:
821
+ raise Error('sample width must be 2 when compressing '
822
+ 'with ulaw/ULAW, alaw/ALAW, sowt/SOWT '
823
+ 'or G7.22 (ADPCM)')
824
+ if not self._nchannels:
825
+ raise Error('# channels not specified')
826
+ if not self._sampwidth:
827
+ raise Error('sample width not specified')
828
+ if not self._framerate:
829
+ raise Error('sampling rate not specified')
830
+ self._write_header(datasize)
831
+
832
+ def _init_compression(self):
833
+ if self._comptype == b'G722':
834
+ self._convert = self._lin2adpcm
835
+ elif self._comptype in (b'ulaw', b'ULAW'):
836
+ self._convert = self._lin2ulaw
837
+ elif self._comptype in (b'alaw', b'ALAW'):
838
+ self._convert = self._lin2alaw
839
+ elif self._comptype in (b'sowt', b'SOWT'):
840
+ self._convert = self._lin2sowt
841
+
842
+ def _write_header(self, initlength):
843
+ if self._aifc and self._comptype != b'NONE':
844
+ self._init_compression()
845
+ self._file.write(b'FORM')
846
+ if not self._nframes:
847
+ self._nframes = initlength // (self._nchannels * self._sampwidth)
848
+ self._datalength = self._nframes * self._nchannels * self._sampwidth
849
+ if self._datalength & 1:
850
+ self._datalength = self._datalength + 1
851
+ if self._aifc:
852
+ if self._comptype in (b'ulaw', b'ULAW', b'alaw', b'ALAW'):
853
+ self._datalength = self._datalength // 2
854
+ if self._datalength & 1:
855
+ self._datalength = self._datalength + 1
856
+ elif self._comptype == b'G722':
857
+ self._datalength = (self._datalength + 3) // 4
858
+ if self._datalength & 1:
859
+ self._datalength = self._datalength + 1
860
+ try:
861
+ self._form_length_pos = self._file.tell()
862
+ except (AttributeError, OSError):
863
+ self._form_length_pos = None
864
+ commlength = self._write_form_length(self._datalength)
865
+ if self._aifc:
866
+ self._file.write(b'AIFC')
867
+ self._file.write(b'FVER')
868
+ _write_ulong(self._file, 4)
869
+ _write_ulong(self._file, self._version)
870
+ else:
871
+ self._file.write(b'AIFF')
872
+ self._file.write(b'COMM')
873
+ _write_ulong(self._file, commlength)
874
+ _write_short(self._file, self._nchannels)
875
+ if self._form_length_pos is not None:
876
+ self._nframes_pos = self._file.tell()
877
+ _write_ulong(self._file, self._nframes)
878
+ if self._comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'):
879
+ _write_short(self._file, 8)
880
+ else:
881
+ _write_short(self._file, self._sampwidth * 8)
882
+ _write_float(self._file, self._framerate)
883
+ if self._aifc:
884
+ self._file.write(self._comptype)
885
+ _write_string(self._file, self._compname)
886
+ self._file.write(b'SSND')
887
+ if self._form_length_pos is not None:
888
+ self._ssnd_length_pos = self._file.tell()
889
+ _write_ulong(self._file, self._datalength + 8)
890
+ _write_ulong(self._file, 0)
891
+ _write_ulong(self._file, 0)
892
+
893
+ def _write_form_length(self, datalength):
894
+ if self._aifc:
895
+ commlength = 18 + 5 + len(self._compname)
896
+ if commlength & 1:
897
+ commlength = commlength + 1
898
+ verslength = 12
899
+ else:
900
+ commlength = 18
901
+ verslength = 0
902
+ _write_ulong(self._file, 4 + verslength + self._marklength + \
903
+ 8 + commlength + 16 + datalength)
904
+ return commlength
905
+
906
+ def _patchheader(self):
907
+ curpos = self._file.tell()
908
+ if self._datawritten & 1:
909
+ datalength = self._datawritten + 1
910
+ self._file.write(b'\x00')
911
+ else:
912
+ datalength = self._datawritten
913
+ if datalength == self._datalength and \
914
+ self._nframes == self._nframeswritten and \
915
+ self._marklength == 0:
916
+ self._file.seek(curpos, 0)
917
+ return
918
+ self._file.seek(self._form_length_pos, 0)
919
+ dummy = self._write_form_length(datalength)
920
+ self._file.seek(self._nframes_pos, 0)
921
+ _write_ulong(self._file, self._nframeswritten)
922
+ self._file.seek(self._ssnd_length_pos, 0)
923
+ _write_ulong(self._file, datalength + 8)
924
+ self._file.seek(curpos, 0)
925
+ self._nframes = self._nframeswritten
926
+ self._datalength = datalength
927
+
928
+ def _writemarkers(self):
929
+ if len(self._markers) == 0:
930
+ return
931
+ self._file.write(b'MARK')
932
+ length = 2
933
+ for marker in self._markers:
934
+ id, pos, name = marker
935
+ length = length + len(name) + 1 + 6
936
+ if len(name) & 1 == 0:
937
+ length = length + 1
938
+ _write_ulong(self._file, length)
939
+ self._marklength = length + 8
940
+ _write_short(self._file, len(self._markers))
941
+ for marker in self._markers:
942
+ id, pos, name = marker
943
+ _write_short(self._file, id)
944
+ _write_ulong(self._file, pos)
945
+ _write_string(self._file, name)
946
+
947
+ def open(f, mode=None):
948
+ if mode is None:
949
+ if hasattr(f, 'mode'):
950
+ mode = f.mode
951
+ else:
952
+ mode = 'rb'
953
+ if mode in ('r', 'rb'):
954
+ return Aifc_read(f)
955
+ elif mode in ('w', 'wb'):
956
+ return Aifc_write(f)
957
+ else:
958
+ raise Error("mode must be 'r', 'rb', 'w', or 'wb'")
959
+
960
+
961
+ if __name__ == '__main__':
962
+ import sys
963
+ if not sys.argv[1:]:
964
+ sys.argv.append('/usr/demos/data/audio/bach.aiff')
965
+ fn = sys.argv[1]
966
+ with open(fn, 'r') as f:
967
+ print("Reading", fn)
968
+ print("nchannels =", f.getnchannels())
969
+ print("nframes =", f.getnframes())
970
+ print("sampwidth =", f.getsampwidth())
971
+ print("framerate =", f.getframerate())
972
+ print("comptype =", f.getcomptype())
973
+ print("compname =", f.getcompname())
974
+ if sys.argv[2:]:
975
+ gn = sys.argv[2]
976
+ print("Writing", gn)
977
+ with open(gn, 'w') as g:
978
+ g.setparams(f.getparams())
979
+ while 1:
980
+ data = f.readframes(1024)
981
+ if not data:
982
+ break
983
+ g.writeframes(data)
984
+ print("Done.")
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/antigravity.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import webbrowser
3
+ import hashlib
4
+
5
+ webbrowser.open("https://xkcd.com/353/")
6
+
7
+ def geohash(latitude, longitude, datedow):
8
+ '''Compute geohash() using the Munroe algorithm.
9
+
10
+ >>> geohash(37.421542, -122.085589, b'2005-05-26-10458.68')
11
+ 37.857713 -122.544543
12
+
13
+ '''
14
+ # https://xkcd.com/426/
15
+ h = hashlib.md5(datedow, usedforsecurity=False).hexdigest()
16
+ p, q = [('%f' % float.fromhex('0.' + x)) for x in (h[:16], h[16:32])]
17
+ print('%d%s %d%s' % (latitude, p[1:], longitude, q[1:]))
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/argparse.py ADDED
The diff for this file is too large to render. See raw diff
 
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/ast.py ADDED
@@ -0,0 +1,1752 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ast
3
+ ~~~
4
+
5
+ The `ast` module helps Python applications to process trees of the Python
6
+ abstract syntax grammar. The abstract syntax itself might change with
7
+ each Python release; this module helps to find out programmatically what
8
+ the current grammar looks like and allows modifications of it.
9
+
10
+ An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as
11
+ a flag to the `compile()` builtin function or by using the `parse()`
12
+ function from this module. The result will be a tree of objects whose
13
+ classes all inherit from `ast.AST`.
14
+
15
+ A modified abstract syntax tree can be compiled into a Python code object
16
+ using the built-in `compile()` function.
17
+
18
+ Additionally various helper functions are provided that make working with
19
+ the trees simpler. The main intention of the helper functions and this
20
+ module in general is to provide an easy to use interface for libraries
21
+ that work tightly with the python syntax (template engines for example).
22
+
23
+
24
+ :copyright: Copyright 2008 by Armin Ronacher.
25
+ :license: Python License.
26
+ """
27
+ import sys
28
+ from _ast import *
29
+ from contextlib import contextmanager, nullcontext
30
+ from enum import IntEnum, auto, _simple_enum
31
+
32
+
33
+ def parse(source, filename='<unknown>', mode='exec', *,
34
+ type_comments=False, feature_version=None):
35
+ """
36
+ Parse the source into an AST node.
37
+ Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
38
+ Pass type_comments=True to get back type comments where the syntax allows.
39
+ """
40
+ flags = PyCF_ONLY_AST
41
+ if type_comments:
42
+ flags |= PyCF_TYPE_COMMENTS
43
+ if isinstance(feature_version, tuple):
44
+ major, minor = feature_version # Should be a 2-tuple.
45
+ assert major == 3
46
+ feature_version = minor
47
+ elif feature_version is None:
48
+ feature_version = -1
49
+ # Else it should be an int giving the minor version for 3.x.
50
+ return compile(source, filename, mode, flags,
51
+ _feature_version=feature_version)
52
+
53
+
54
+ def literal_eval(node_or_string):
55
+ """
56
+ Evaluate an expression node or a string containing only a Python
57
+ expression. The string or node provided may only consist of the following
58
+ Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
59
+ sets, booleans, and None.
60
+
61
+ Caution: A complex expression can overflow the C stack and cause a crash.
62
+ """
63
+ if isinstance(node_or_string, str):
64
+ node_or_string = parse(node_or_string.lstrip(" \t"), mode='eval')
65
+ if isinstance(node_or_string, Expression):
66
+ node_or_string = node_or_string.body
67
+ def _raise_malformed_node(node):
68
+ msg = "malformed node or string"
69
+ if lno := getattr(node, 'lineno', None):
70
+ msg += f' on line {lno}'
71
+ raise ValueError(msg + f': {node!r}')
72
+ def _convert_num(node):
73
+ if not isinstance(node, Constant) or type(node.value) not in (int, float, complex):
74
+ _raise_malformed_node(node)
75
+ return node.value
76
+ def _convert_signed_num(node):
77
+ if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)):
78
+ operand = _convert_num(node.operand)
79
+ if isinstance(node.op, UAdd):
80
+ return + operand
81
+ else:
82
+ return - operand
83
+ return _convert_num(node)
84
+ def _convert(node):
85
+ if isinstance(node, Constant):
86
+ return node.value
87
+ elif isinstance(node, Tuple):
88
+ return tuple(map(_convert, node.elts))
89
+ elif isinstance(node, List):
90
+ return list(map(_convert, node.elts))
91
+ elif isinstance(node, Set):
92
+ return set(map(_convert, node.elts))
93
+ elif (isinstance(node, Call) and isinstance(node.func, Name) and
94
+ node.func.id == 'set' and node.args == node.keywords == []):
95
+ return set()
96
+ elif isinstance(node, Dict):
97
+ if len(node.keys) != len(node.values):
98
+ _raise_malformed_node(node)
99
+ return dict(zip(map(_convert, node.keys),
100
+ map(_convert, node.values)))
101
+ elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):
102
+ left = _convert_signed_num(node.left)
103
+ right = _convert_num(node.right)
104
+ if isinstance(left, (int, float)) and isinstance(right, complex):
105
+ if isinstance(node.op, Add):
106
+ return left + right
107
+ else:
108
+ return left - right
109
+ return _convert_signed_num(node)
110
+ return _convert(node_or_string)
111
+
112
+
113
+ def dump(node, annotate_fields=True, include_attributes=False, *, indent=None):
114
+ """
115
+ Return a formatted dump of the tree in node. This is mainly useful for
116
+ debugging purposes. If annotate_fields is true (by default),
117
+ the returned string will show the names and the values for fields.
118
+ If annotate_fields is false, the result string will be more compact by
119
+ omitting unambiguous field names. Attributes such as line
120
+ numbers and column offsets are not dumped by default. If this is wanted,
121
+ include_attributes can be set to true. If indent is a non-negative
122
+ integer or string, then the tree will be pretty-printed with that indent
123
+ level. None (the default) selects the single line representation.
124
+ """
125
+ def _format(node, level=0):
126
+ if indent is not None:
127
+ level += 1
128
+ prefix = '\n' + indent * level
129
+ sep = ',\n' + indent * level
130
+ else:
131
+ prefix = ''
132
+ sep = ', '
133
+ if isinstance(node, AST):
134
+ cls = type(node)
135
+ args = []
136
+ allsimple = True
137
+ keywords = annotate_fields
138
+ for name in node._fields:
139
+ try:
140
+ value = getattr(node, name)
141
+ except AttributeError:
142
+ keywords = True
143
+ continue
144
+ if value is None and getattr(cls, name, ...) is None:
145
+ keywords = True
146
+ continue
147
+ value, simple = _format(value, level)
148
+ allsimple = allsimple and simple
149
+ if keywords:
150
+ args.append('%s=%s' % (name, value))
151
+ else:
152
+ args.append(value)
153
+ if include_attributes and node._attributes:
154
+ for name in node._attributes:
155
+ try:
156
+ value = getattr(node, name)
157
+ except AttributeError:
158
+ continue
159
+ if value is None and getattr(cls, name, ...) is None:
160
+ continue
161
+ value, simple = _format(value, level)
162
+ allsimple = allsimple and simple
163
+ args.append('%s=%s' % (name, value))
164
+ if allsimple and len(args) <= 3:
165
+ return '%s(%s)' % (node.__class__.__name__, ', '.join(args)), not args
166
+ return '%s(%s%s)' % (node.__class__.__name__, prefix, sep.join(args)), False
167
+ elif isinstance(node, list):
168
+ if not node:
169
+ return '[]', True
170
+ return '[%s%s]' % (prefix, sep.join(_format(x, level)[0] for x in node)), False
171
+ return repr(node), True
172
+
173
+ if not isinstance(node, AST):
174
+ raise TypeError('expected AST, got %r' % node.__class__.__name__)
175
+ if indent is not None and not isinstance(indent, str):
176
+ indent = ' ' * indent
177
+ return _format(node)[0]
178
+
179
+
180
+ def copy_location(new_node, old_node):
181
+ """
182
+ Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset`
183
+ attributes) from *old_node* to *new_node* if possible, and return *new_node*.
184
+ """
185
+ for attr in 'lineno', 'col_offset', 'end_lineno', 'end_col_offset':
186
+ if attr in old_node._attributes and attr in new_node._attributes:
187
+ value = getattr(old_node, attr, None)
188
+ # end_lineno and end_col_offset are optional attributes, and they
189
+ # should be copied whether the value is None or not.
190
+ if value is not None or (
191
+ hasattr(old_node, attr) and attr.startswith("end_")
192
+ ):
193
+ setattr(new_node, attr, value)
194
+ return new_node
195
+
196
+
197
+ def fix_missing_locations(node):
198
+ """
199
+ When you compile a node tree with compile(), the compiler expects lineno and
200
+ col_offset attributes for every node that supports them. This is rather
201
+ tedious to fill in for generated nodes, so this helper adds these attributes
202
+ recursively where not already set, by setting them to the values of the
203
+ parent node. It works recursively starting at *node*.
204
+ """
205
+ def _fix(node, lineno, col_offset, end_lineno, end_col_offset):
206
+ if 'lineno' in node._attributes:
207
+ if not hasattr(node, 'lineno'):
208
+ node.lineno = lineno
209
+ else:
210
+ lineno = node.lineno
211
+ if 'end_lineno' in node._attributes:
212
+ if getattr(node, 'end_lineno', None) is None:
213
+ node.end_lineno = end_lineno
214
+ else:
215
+ end_lineno = node.end_lineno
216
+ if 'col_offset' in node._attributes:
217
+ if not hasattr(node, 'col_offset'):
218
+ node.col_offset = col_offset
219
+ else:
220
+ col_offset = node.col_offset
221
+ if 'end_col_offset' in node._attributes:
222
+ if getattr(node, 'end_col_offset', None) is None:
223
+ node.end_col_offset = end_col_offset
224
+ else:
225
+ end_col_offset = node.end_col_offset
226
+ for child in iter_child_nodes(node):
227
+ _fix(child, lineno, col_offset, end_lineno, end_col_offset)
228
+ _fix(node, 1, 0, 1, 0)
229
+ return node
230
+
231
+
232
+ def increment_lineno(node, n=1):
233
+ """
234
+ Increment the line number and end line number of each node in the tree
235
+ starting at *node* by *n*. This is useful to "move code" to a different
236
+ location in a file.
237
+ """
238
+ for child in walk(node):
239
+ # TypeIgnore is a special case where lineno is not an attribute
240
+ # but rather a field of the node itself.
241
+ if isinstance(child, TypeIgnore):
242
+ child.lineno = getattr(child, 'lineno', 0) + n
243
+ continue
244
+
245
+ if 'lineno' in child._attributes:
246
+ child.lineno = getattr(child, 'lineno', 0) + n
247
+ if (
248
+ "end_lineno" in child._attributes
249
+ and (end_lineno := getattr(child, "end_lineno", 0)) is not None
250
+ ):
251
+ child.end_lineno = end_lineno + n
252
+ return node
253
+
254
+
255
+ def iter_fields(node):
256
+ """
257
+ Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
258
+ that is present on *node*.
259
+ """
260
+ for field in node._fields:
261
+ try:
262
+ yield field, getattr(node, field)
263
+ except AttributeError:
264
+ pass
265
+
266
+
267
+ def iter_child_nodes(node):
268
+ """
269
+ Yield all direct child nodes of *node*, that is, all fields that are nodes
270
+ and all items of fields that are lists of nodes.
271
+ """
272
+ for name, field in iter_fields(node):
273
+ if isinstance(field, AST):
274
+ yield field
275
+ elif isinstance(field, list):
276
+ for item in field:
277
+ if isinstance(item, AST):
278
+ yield item
279
+
280
+
281
+ def get_docstring(node, clean=True):
282
+ """
283
+ Return the docstring for the given node or None if no docstring can
284
+ be found. If the node provided does not have docstrings a TypeError
285
+ will be raised.
286
+
287
+ If *clean* is `True`, all tabs are expanded to spaces and any whitespace
288
+ that can be uniformly removed from the second line onwards is removed.
289
+ """
290
+ if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):
291
+ raise TypeError("%r can't have docstrings" % node.__class__.__name__)
292
+ if not(node.body and isinstance(node.body[0], Expr)):
293
+ return None
294
+ node = node.body[0].value
295
+ if isinstance(node, Str):
296
+ text = node.s
297
+ elif isinstance(node, Constant) and isinstance(node.value, str):
298
+ text = node.value
299
+ else:
300
+ return None
301
+ if clean:
302
+ import inspect
303
+ text = inspect.cleandoc(text)
304
+ return text
305
+
306
+
307
+ def _splitlines_no_ff(source):
308
+ """Split a string into lines ignoring form feed and other chars.
309
+
310
+ This mimics how the Python parser splits source code.
311
+ """
312
+ idx = 0
313
+ lines = []
314
+ next_line = ''
315
+ while idx < len(source):
316
+ c = source[idx]
317
+ next_line += c
318
+ idx += 1
319
+ # Keep \r\n together
320
+ if c == '\r' and idx < len(source) and source[idx] == '\n':
321
+ next_line += '\n'
322
+ idx += 1
323
+ if c in '\r\n':
324
+ lines.append(next_line)
325
+ next_line = ''
326
+
327
+ if next_line:
328
+ lines.append(next_line)
329
+ return lines
330
+
331
+
332
+ def _pad_whitespace(source):
333
+ r"""Replace all chars except '\f\t' in a line with spaces."""
334
+ result = ''
335
+ for c in source:
336
+ if c in '\f\t':
337
+ result += c
338
+ else:
339
+ result += ' '
340
+ return result
341
+
342
+
343
+ def get_source_segment(source, node, *, padded=False):
344
+ """Get source code segment of the *source* that generated *node*.
345
+
346
+ If some location information (`lineno`, `end_lineno`, `col_offset`,
347
+ or `end_col_offset`) is missing, return None.
348
+
349
+ If *padded* is `True`, the first line of a multi-line statement will
350
+ be padded with spaces to match its original position.
351
+ """
352
+ try:
353
+ if node.end_lineno is None or node.end_col_offset is None:
354
+ return None
355
+ lineno = node.lineno - 1
356
+ end_lineno = node.end_lineno - 1
357
+ col_offset = node.col_offset
358
+ end_col_offset = node.end_col_offset
359
+ except AttributeError:
360
+ return None
361
+
362
+ lines = _splitlines_no_ff(source)
363
+ if end_lineno == lineno:
364
+ return lines[lineno].encode()[col_offset:end_col_offset].decode()
365
+
366
+ if padded:
367
+ padding = _pad_whitespace(lines[lineno].encode()[:col_offset].decode())
368
+ else:
369
+ padding = ''
370
+
371
+ first = padding + lines[lineno].encode()[col_offset:].decode()
372
+ last = lines[end_lineno].encode()[:end_col_offset].decode()
373
+ lines = lines[lineno+1:end_lineno]
374
+
375
+ lines.insert(0, first)
376
+ lines.append(last)
377
+ return ''.join(lines)
378
+
379
+
380
+ def walk(node):
381
+ """
382
+ Recursively yield all descendant nodes in the tree starting at *node*
383
+ (including *node* itself), in no specified order. This is useful if you
384
+ only want to modify nodes in place and don't care about the context.
385
+ """
386
+ from collections import deque
387
+ todo = deque([node])
388
+ while todo:
389
+ node = todo.popleft()
390
+ todo.extend(iter_child_nodes(node))
391
+ yield node
392
+
393
+
394
+ class NodeVisitor(object):
395
+ """
396
+ A node visitor base class that walks the abstract syntax tree and calls a
397
+ visitor function for every node found. This function may return a value
398
+ which is forwarded by the `visit` method.
399
+
400
+ This class is meant to be subclassed, with the subclass adding visitor
401
+ methods.
402
+
403
+ Per default the visitor functions for the nodes are ``'visit_'`` +
404
+ class name of the node. So a `TryFinally` node visit function would
405
+ be `visit_TryFinally`. This behavior can be changed by overriding
406
+ the `visit` method. If no visitor function exists for a node
407
+ (return value `None`) the `generic_visit` visitor is used instead.
408
+
409
+ Don't use the `NodeVisitor` if you want to apply changes to nodes during
410
+ traversing. For this a special visitor exists (`NodeTransformer`) that
411
+ allows modifications.
412
+ """
413
+
414
+ def visit(self, node):
415
+ """Visit a node."""
416
+ method = 'visit_' + node.__class__.__name__
417
+ visitor = getattr(self, method, self.generic_visit)
418
+ return visitor(node)
419
+
420
+ def generic_visit(self, node):
421
+ """Called if no explicit visitor function exists for a node."""
422
+ for field, value in iter_fields(node):
423
+ if isinstance(value, list):
424
+ for item in value:
425
+ if isinstance(item, AST):
426
+ self.visit(item)
427
+ elif isinstance(value, AST):
428
+ self.visit(value)
429
+
430
+ def visit_Constant(self, node):
431
+ value = node.value
432
+ type_name = _const_node_type_names.get(type(value))
433
+ if type_name is None:
434
+ for cls, name in _const_node_type_names.items():
435
+ if isinstance(value, cls):
436
+ type_name = name
437
+ break
438
+ if type_name is not None:
439
+ method = 'visit_' + type_name
440
+ try:
441
+ visitor = getattr(self, method)
442
+ except AttributeError:
443
+ pass
444
+ else:
445
+ import warnings
446
+ warnings.warn(f"{method} is deprecated; add visit_Constant",
447
+ DeprecationWarning, 2)
448
+ return visitor(node)
449
+ return self.generic_visit(node)
450
+
451
+
452
+ class NodeTransformer(NodeVisitor):
453
+ """
454
+ A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
455
+ allows modification of nodes.
456
+
457
+ The `NodeTransformer` will walk the AST and use the return value of the
458
+ visitor methods to replace or remove the old node. If the return value of
459
+ the visitor method is ``None``, the node will be removed from its location,
460
+ otherwise it is replaced with the return value. The return value may be the
461
+ original node in which case no replacement takes place.
462
+
463
+ Here is an example transformer that rewrites all occurrences of name lookups
464
+ (``foo``) to ``data['foo']``::
465
+
466
+ class RewriteName(NodeTransformer):
467
+
468
+ def visit_Name(self, node):
469
+ return Subscript(
470
+ value=Name(id='data', ctx=Load()),
471
+ slice=Constant(value=node.id),
472
+ ctx=node.ctx
473
+ )
474
+
475
+ Keep in mind that if the node you're operating on has child nodes you must
476
+ either transform the child nodes yourself or call the :meth:`generic_visit`
477
+ method for the node first.
478
+
479
+ For nodes that were part of a collection of statements (that applies to all
480
+ statement nodes), the visitor may also return a list of nodes rather than
481
+ just a single node.
482
+
483
+ Usually you use the transformer like this::
484
+
485
+ node = YourTransformer().visit(node)
486
+ """
487
+
488
+ def generic_visit(self, node):
489
+ for field, old_value in iter_fields(node):
490
+ if isinstance(old_value, list):
491
+ new_values = []
492
+ for value in old_value:
493
+ if isinstance(value, AST):
494
+ value = self.visit(value)
495
+ if value is None:
496
+ continue
497
+ elif not isinstance(value, AST):
498
+ new_values.extend(value)
499
+ continue
500
+ new_values.append(value)
501
+ old_value[:] = new_values
502
+ elif isinstance(old_value, AST):
503
+ new_node = self.visit(old_value)
504
+ if new_node is None:
505
+ delattr(node, field)
506
+ else:
507
+ setattr(node, field, new_node)
508
+ return node
509
+
510
+
511
+ # If the ast module is loaded more than once, only add deprecated methods once
512
+ if not hasattr(Constant, 'n'):
513
+ # The following code is for backward compatibility.
514
+ # It will be removed in future.
515
+
516
+ def _getter(self):
517
+ """Deprecated. Use value instead."""
518
+ return self.value
519
+
520
+ def _setter(self, value):
521
+ self.value = value
522
+
523
+ Constant.n = property(_getter, _setter)
524
+ Constant.s = property(_getter, _setter)
525
+
526
+ class _ABC(type):
527
+
528
+ def __init__(cls, *args):
529
+ cls.__doc__ = """Deprecated AST node class. Use ast.Constant instead"""
530
+
531
+ def __instancecheck__(cls, inst):
532
+ if not isinstance(inst, Constant):
533
+ return False
534
+ if cls in _const_types:
535
+ try:
536
+ value = inst.value
537
+ except AttributeError:
538
+ return False
539
+ else:
540
+ return (
541
+ isinstance(value, _const_types[cls]) and
542
+ not isinstance(value, _const_types_not.get(cls, ()))
543
+ )
544
+ return type.__instancecheck__(cls, inst)
545
+
546
+ def _new(cls, *args, **kwargs):
547
+ for key in kwargs:
548
+ if key not in cls._fields:
549
+ # arbitrary keyword arguments are accepted
550
+ continue
551
+ pos = cls._fields.index(key)
552
+ if pos < len(args):
553
+ raise TypeError(f"{cls.__name__} got multiple values for argument {key!r}")
554
+ if cls in _const_types:
555
+ return Constant(*args, **kwargs)
556
+ return Constant.__new__(cls, *args, **kwargs)
557
+
558
+ class Num(Constant, metaclass=_ABC):
559
+ _fields = ('n',)
560
+ __new__ = _new
561
+
562
+ class Str(Constant, metaclass=_ABC):
563
+ _fields = ('s',)
564
+ __new__ = _new
565
+
566
+ class Bytes(Constant, metaclass=_ABC):
567
+ _fields = ('s',)
568
+ __new__ = _new
569
+
570
+ class NameConstant(Constant, metaclass=_ABC):
571
+ __new__ = _new
572
+
573
+ class Ellipsis(Constant, metaclass=_ABC):
574
+ _fields = ()
575
+
576
+ def __new__(cls, *args, **kwargs):
577
+ if cls is Ellipsis:
578
+ return Constant(..., *args, **kwargs)
579
+ return Constant.__new__(cls, *args, **kwargs)
580
+
581
+ _const_types = {
582
+ Num: (int, float, complex),
583
+ Str: (str,),
584
+ Bytes: (bytes,),
585
+ NameConstant: (type(None), bool),
586
+ Ellipsis: (type(...),),
587
+ }
588
+ _const_types_not = {
589
+ Num: (bool,),
590
+ }
591
+
592
+ _const_node_type_names = {
593
+ bool: 'NameConstant', # should be before int
594
+ type(None): 'NameConstant',
595
+ int: 'Num',
596
+ float: 'Num',
597
+ complex: 'Num',
598
+ str: 'Str',
599
+ bytes: 'Bytes',
600
+ type(...): 'Ellipsis',
601
+ }
602
+
603
+ class slice(AST):
604
+ """Deprecated AST node class."""
605
+
606
+ class Index(slice):
607
+ """Deprecated AST node class. Use the index value directly instead."""
608
+ def __new__(cls, value, **kwargs):
609
+ return value
610
+
611
+ class ExtSlice(slice):
612
+ """Deprecated AST node class. Use ast.Tuple instead."""
613
+ def __new__(cls, dims=(), **kwargs):
614
+ return Tuple(list(dims), Load(), **kwargs)
615
+
616
+ # If the ast module is loaded more than once, only add deprecated methods once
617
+ if not hasattr(Tuple, 'dims'):
618
+ # The following code is for backward compatibility.
619
+ # It will be removed in future.
620
+
621
+ def _dims_getter(self):
622
+ """Deprecated. Use elts instead."""
623
+ return self.elts
624
+
625
+ def _dims_setter(self, value):
626
+ self.elts = value
627
+
628
+ Tuple.dims = property(_dims_getter, _dims_setter)
629
+
630
+ class Suite(mod):
631
+ """Deprecated AST node class. Unused in Python 3."""
632
+
633
+ class AugLoad(expr_context):
634
+ """Deprecated AST node class. Unused in Python 3."""
635
+
636
+ class AugStore(expr_context):
637
+ """Deprecated AST node class. Unused in Python 3."""
638
+
639
+ class Param(expr_context):
640
+ """Deprecated AST node class. Unused in Python 3."""
641
+
642
+
643
+ # Large float and imaginary literals get turned into infinities in the AST.
644
+ # We unparse those infinities to INFSTR.
645
+ _INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1)
646
+
647
+ @_simple_enum(IntEnum)
648
+ class _Precedence:
649
+ """Precedence table that originated from python grammar."""
650
+
651
+ NAMED_EXPR = auto() # <target> := <expr1>
652
+ TUPLE = auto() # <expr1>, <expr2>
653
+ YIELD = auto() # 'yield', 'yield from'
654
+ TEST = auto() # 'if'-'else', 'lambda'
655
+ OR = auto() # 'or'
656
+ AND = auto() # 'and'
657
+ NOT = auto() # 'not'
658
+ CMP = auto() # '<', '>', '==', '>=', '<=', '!=',
659
+ # 'in', 'not in', 'is', 'is not'
660
+ EXPR = auto()
661
+ BOR = EXPR # '|'
662
+ BXOR = auto() # '^'
663
+ BAND = auto() # '&'
664
+ SHIFT = auto() # '<<', '>>'
665
+ ARITH = auto() # '+', '-'
666
+ TERM = auto() # '*', '@', '/', '%', '//'
667
+ FACTOR = auto() # unary '+', '-', '~'
668
+ POWER = auto() # '**'
669
+ AWAIT = auto() # 'await'
670
+ ATOM = auto()
671
+
672
+ def next(self):
673
+ try:
674
+ return self.__class__(self + 1)
675
+ except ValueError:
676
+ return self
677
+
678
+
679
+ _SINGLE_QUOTES = ("'", '"')
680
+ _MULTI_QUOTES = ('"""', "'''")
681
+ _ALL_QUOTES = (*_SINGLE_QUOTES, *_MULTI_QUOTES)
682
+
683
+ class _Unparser(NodeVisitor):
684
+ """Methods in this class recursively traverse an AST and
685
+ output source code for the abstract syntax; original formatting
686
+ is disregarded."""
687
+
688
+ def __init__(self, *, _avoid_backslashes=False):
689
+ self._source = []
690
+ self._precedences = {}
691
+ self._type_ignores = {}
692
+ self._indent = 0
693
+ self._avoid_backslashes = _avoid_backslashes
694
+ self._in_try_star = False
695
+
696
+ def interleave(self, inter, f, seq):
697
+ """Call f on each item in seq, calling inter() in between."""
698
+ seq = iter(seq)
699
+ try:
700
+ f(next(seq))
701
+ except StopIteration:
702
+ pass
703
+ else:
704
+ for x in seq:
705
+ inter()
706
+ f(x)
707
+
708
+ def items_view(self, traverser, items):
709
+ """Traverse and separate the given *items* with a comma and append it to
710
+ the buffer. If *items* is a single item sequence, a trailing comma
711
+ will be added."""
712
+ if len(items) == 1:
713
+ traverser(items[0])
714
+ self.write(",")
715
+ else:
716
+ self.interleave(lambda: self.write(", "), traverser, items)
717
+
718
+ def maybe_newline(self):
719
+ """Adds a newline if it isn't the start of generated source"""
720
+ if self._source:
721
+ self.write("\n")
722
+
723
+ def fill(self, text=""):
724
+ """Indent a piece of text and append it, according to the current
725
+ indentation level"""
726
+ self.maybe_newline()
727
+ self.write(" " * self._indent + text)
728
+
729
+ def write(self, *text):
730
+ """Add new source parts"""
731
+ self._source.extend(text)
732
+
733
+ @contextmanager
734
+ def buffered(self, buffer = None):
735
+ if buffer is None:
736
+ buffer = []
737
+
738
+ original_source = self._source
739
+ self._source = buffer
740
+ yield buffer
741
+ self._source = original_source
742
+
743
+ @contextmanager
744
+ def block(self, *, extra = None):
745
+ """A context manager for preparing the source for blocks. It adds
746
+ the character':', increases the indentation on enter and decreases
747
+ the indentation on exit. If *extra* is given, it will be directly
748
+ appended after the colon character.
749
+ """
750
+ self.write(":")
751
+ if extra:
752
+ self.write(extra)
753
+ self._indent += 1
754
+ yield
755
+ self._indent -= 1
756
+
757
+ @contextmanager
758
+ def delimit(self, start, end):
759
+ """A context manager for preparing the source for expressions. It adds
760
+ *start* to the buffer and enters, after exit it adds *end*."""
761
+
762
+ self.write(start)
763
+ yield
764
+ self.write(end)
765
+
766
+ def delimit_if(self, start, end, condition):
767
+ if condition:
768
+ return self.delimit(start, end)
769
+ else:
770
+ return nullcontext()
771
+
772
+ def require_parens(self, precedence, node):
773
+ """Shortcut to adding precedence related parens"""
774
+ return self.delimit_if("(", ")", self.get_precedence(node) > precedence)
775
+
776
+ def get_precedence(self, node):
777
+ return self._precedences.get(node, _Precedence.TEST)
778
+
779
+ def set_precedence(self, precedence, *nodes):
780
+ for node in nodes:
781
+ self._precedences[node] = precedence
782
+
783
+ def get_raw_docstring(self, node):
784
+ """If a docstring node is found in the body of the *node* parameter,
785
+ return that docstring node, None otherwise.
786
+
787
+ Logic mirrored from ``_PyAST_GetDocString``."""
788
+ if not isinstance(
789
+ node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)
790
+ ) or len(node.body) < 1:
791
+ return None
792
+ node = node.body[0]
793
+ if not isinstance(node, Expr):
794
+ return None
795
+ node = node.value
796
+ if isinstance(node, Constant) and isinstance(node.value, str):
797
+ return node
798
+
799
+ def get_type_comment(self, node):
800
+ comment = self._type_ignores.get(node.lineno) or node.type_comment
801
+ if comment is not None:
802
+ return f" # type: {comment}"
803
+
804
+ def traverse(self, node):
805
+ if isinstance(node, list):
806
+ for item in node:
807
+ self.traverse(item)
808
+ else:
809
+ super().visit(node)
810
+
811
+ # Note: as visit() resets the output text, do NOT rely on
812
+ # NodeVisitor.generic_visit to handle any nodes (as it calls back in to
813
+ # the subclass visit() method, which resets self._source to an empty list)
814
+ def visit(self, node):
815
+ """Outputs a source code string that, if converted back to an ast
816
+ (using ast.parse) will generate an AST equivalent to *node*"""
817
+ self._source = []
818
+ self.traverse(node)
819
+ return "".join(self._source)
820
+
821
+ def _write_docstring_and_traverse_body(self, node):
822
+ if (docstring := self.get_raw_docstring(node)):
823
+ self._write_docstring(docstring)
824
+ self.traverse(node.body[1:])
825
+ else:
826
+ self.traverse(node.body)
827
+
828
+ def visit_Module(self, node):
829
+ self._type_ignores = {
830
+ ignore.lineno: f"ignore{ignore.tag}"
831
+ for ignore in node.type_ignores
832
+ }
833
+ self._write_docstring_and_traverse_body(node)
834
+ self._type_ignores.clear()
835
+
836
+ def visit_FunctionType(self, node):
837
+ with self.delimit("(", ")"):
838
+ self.interleave(
839
+ lambda: self.write(", "), self.traverse, node.argtypes
840
+ )
841
+
842
+ self.write(" -> ")
843
+ self.traverse(node.returns)
844
+
845
+ def visit_Expr(self, node):
846
+ self.fill()
847
+ self.set_precedence(_Precedence.YIELD, node.value)
848
+ self.traverse(node.value)
849
+
850
+ def visit_NamedExpr(self, node):
851
+ with self.require_parens(_Precedence.NAMED_EXPR, node):
852
+ self.set_precedence(_Precedence.ATOM, node.target, node.value)
853
+ self.traverse(node.target)
854
+ self.write(" := ")
855
+ self.traverse(node.value)
856
+
857
+ def visit_Import(self, node):
858
+ self.fill("import ")
859
+ self.interleave(lambda: self.write(", "), self.traverse, node.names)
860
+
861
+ def visit_ImportFrom(self, node):
862
+ self.fill("from ")
863
+ self.write("." * (node.level or 0))
864
+ if node.module:
865
+ self.write(node.module)
866
+ self.write(" import ")
867
+ self.interleave(lambda: self.write(", "), self.traverse, node.names)
868
+
869
+ def visit_Assign(self, node):
870
+ self.fill()
871
+ for target in node.targets:
872
+ self.set_precedence(_Precedence.TUPLE, target)
873
+ self.traverse(target)
874
+ self.write(" = ")
875
+ self.traverse(node.value)
876
+ if type_comment := self.get_type_comment(node):
877
+ self.write(type_comment)
878
+
879
+ def visit_AugAssign(self, node):
880
+ self.fill()
881
+ self.traverse(node.target)
882
+ self.write(" " + self.binop[node.op.__class__.__name__] + "= ")
883
+ self.traverse(node.value)
884
+
885
+ def visit_AnnAssign(self, node):
886
+ self.fill()
887
+ with self.delimit_if("(", ")", not node.simple and isinstance(node.target, Name)):
888
+ self.traverse(node.target)
889
+ self.write(": ")
890
+ self.traverse(node.annotation)
891
+ if node.value:
892
+ self.write(" = ")
893
+ self.traverse(node.value)
894
+
895
+ def visit_Return(self, node):
896
+ self.fill("return")
897
+ if node.value:
898
+ self.write(" ")
899
+ self.traverse(node.value)
900
+
901
+ def visit_Pass(self, node):
902
+ self.fill("pass")
903
+
904
+ def visit_Break(self, node):
905
+ self.fill("break")
906
+
907
+ def visit_Continue(self, node):
908
+ self.fill("continue")
909
+
910
+ def visit_Delete(self, node):
911
+ self.fill("del ")
912
+ self.interleave(lambda: self.write(", "), self.traverse, node.targets)
913
+
914
+ def visit_Assert(self, node):
915
+ self.fill("assert ")
916
+ self.traverse(node.test)
917
+ if node.msg:
918
+ self.write(", ")
919
+ self.traverse(node.msg)
920
+
921
+ def visit_Global(self, node):
922
+ self.fill("global ")
923
+ self.interleave(lambda: self.write(", "), self.write, node.names)
924
+
925
+ def visit_Nonlocal(self, node):
926
+ self.fill("nonlocal ")
927
+ self.interleave(lambda: self.write(", "), self.write, node.names)
928
+
929
+ def visit_Await(self, node):
930
+ with self.require_parens(_Precedence.AWAIT, node):
931
+ self.write("await")
932
+ if node.value:
933
+ self.write(" ")
934
+ self.set_precedence(_Precedence.ATOM, node.value)
935
+ self.traverse(node.value)
936
+
937
+ def visit_Yield(self, node):
938
+ with self.require_parens(_Precedence.YIELD, node):
939
+ self.write("yield")
940
+ if node.value:
941
+ self.write(" ")
942
+ self.set_precedence(_Precedence.ATOM, node.value)
943
+ self.traverse(node.value)
944
+
945
+ def visit_YieldFrom(self, node):
946
+ with self.require_parens(_Precedence.YIELD, node):
947
+ self.write("yield from ")
948
+ if not node.value:
949
+ raise ValueError("Node can't be used without a value attribute.")
950
+ self.set_precedence(_Precedence.ATOM, node.value)
951
+ self.traverse(node.value)
952
+
953
+ def visit_Raise(self, node):
954
+ self.fill("raise")
955
+ if not node.exc:
956
+ if node.cause:
957
+ raise ValueError(f"Node can't use cause without an exception.")
958
+ return
959
+ self.write(" ")
960
+ self.traverse(node.exc)
961
+ if node.cause:
962
+ self.write(" from ")
963
+ self.traverse(node.cause)
964
+
965
+ def do_visit_try(self, node):
966
+ self.fill("try")
967
+ with self.block():
968
+ self.traverse(node.body)
969
+ for ex in node.handlers:
970
+ self.traverse(ex)
971
+ if node.orelse:
972
+ self.fill("else")
973
+ with self.block():
974
+ self.traverse(node.orelse)
975
+ if node.finalbody:
976
+ self.fill("finally")
977
+ with self.block():
978
+ self.traverse(node.finalbody)
979
+
980
+ def visit_Try(self, node):
981
+ prev_in_try_star = self._in_try_star
982
+ try:
983
+ self._in_try_star = False
984
+ self.do_visit_try(node)
985
+ finally:
986
+ self._in_try_star = prev_in_try_star
987
+
988
+ def visit_TryStar(self, node):
989
+ prev_in_try_star = self._in_try_star
990
+ try:
991
+ self._in_try_star = True
992
+ self.do_visit_try(node)
993
+ finally:
994
+ self._in_try_star = prev_in_try_star
995
+
996
+ def visit_ExceptHandler(self, node):
997
+ self.fill("except*" if self._in_try_star else "except")
998
+ if node.type:
999
+ self.write(" ")
1000
+ self.traverse(node.type)
1001
+ if node.name:
1002
+ self.write(" as ")
1003
+ self.write(node.name)
1004
+ with self.block():
1005
+ self.traverse(node.body)
1006
+
1007
+ def visit_ClassDef(self, node):
1008
+ self.maybe_newline()
1009
+ for deco in node.decorator_list:
1010
+ self.fill("@")
1011
+ self.traverse(deco)
1012
+ self.fill("class " + node.name)
1013
+ with self.delimit_if("(", ")", condition = node.bases or node.keywords):
1014
+ comma = False
1015
+ for e in node.bases:
1016
+ if comma:
1017
+ self.write(", ")
1018
+ else:
1019
+ comma = True
1020
+ self.traverse(e)
1021
+ for e in node.keywords:
1022
+ if comma:
1023
+ self.write(", ")
1024
+ else:
1025
+ comma = True
1026
+ self.traverse(e)
1027
+
1028
+ with self.block():
1029
+ self._write_docstring_and_traverse_body(node)
1030
+
1031
+ def visit_FunctionDef(self, node):
1032
+ self._function_helper(node, "def")
1033
+
1034
+ def visit_AsyncFunctionDef(self, node):
1035
+ self._function_helper(node, "async def")
1036
+
1037
+ def _function_helper(self, node, fill_suffix):
1038
+ self.maybe_newline()
1039
+ for deco in node.decorator_list:
1040
+ self.fill("@")
1041
+ self.traverse(deco)
1042
+ def_str = fill_suffix + " " + node.name
1043
+ self.fill(def_str)
1044
+ with self.delimit("(", ")"):
1045
+ self.traverse(node.args)
1046
+ if node.returns:
1047
+ self.write(" -> ")
1048
+ self.traverse(node.returns)
1049
+ with self.block(extra=self.get_type_comment(node)):
1050
+ self._write_docstring_and_traverse_body(node)
1051
+
1052
+ def visit_For(self, node):
1053
+ self._for_helper("for ", node)
1054
+
1055
+ def visit_AsyncFor(self, node):
1056
+ self._for_helper("async for ", node)
1057
+
1058
+ def _for_helper(self, fill, node):
1059
+ self.fill(fill)
1060
+ self.set_precedence(_Precedence.TUPLE, node.target)
1061
+ self.traverse(node.target)
1062
+ self.write(" in ")
1063
+ self.traverse(node.iter)
1064
+ with self.block(extra=self.get_type_comment(node)):
1065
+ self.traverse(node.body)
1066
+ if node.orelse:
1067
+ self.fill("else")
1068
+ with self.block():
1069
+ self.traverse(node.orelse)
1070
+
1071
+ def visit_If(self, node):
1072
+ self.fill("if ")
1073
+ self.traverse(node.test)
1074
+ with self.block():
1075
+ self.traverse(node.body)
1076
+ # collapse nested ifs into equivalent elifs.
1077
+ while node.orelse and len(node.orelse) == 1 and isinstance(node.orelse[0], If):
1078
+ node = node.orelse[0]
1079
+ self.fill("elif ")
1080
+ self.traverse(node.test)
1081
+ with self.block():
1082
+ self.traverse(node.body)
1083
+ # final else
1084
+ if node.orelse:
1085
+ self.fill("else")
1086
+ with self.block():
1087
+ self.traverse(node.orelse)
1088
+
1089
+ def visit_While(self, node):
1090
+ self.fill("while ")
1091
+ self.traverse(node.test)
1092
+ with self.block():
1093
+ self.traverse(node.body)
1094
+ if node.orelse:
1095
+ self.fill("else")
1096
+ with self.block():
1097
+ self.traverse(node.orelse)
1098
+
1099
+ def visit_With(self, node):
1100
+ self.fill("with ")
1101
+ self.interleave(lambda: self.write(", "), self.traverse, node.items)
1102
+ with self.block(extra=self.get_type_comment(node)):
1103
+ self.traverse(node.body)
1104
+
1105
+ def visit_AsyncWith(self, node):
1106
+ self.fill("async with ")
1107
+ self.interleave(lambda: self.write(", "), self.traverse, node.items)
1108
+ with self.block(extra=self.get_type_comment(node)):
1109
+ self.traverse(node.body)
1110
+
1111
+ def _str_literal_helper(
1112
+ self, string, *, quote_types=_ALL_QUOTES, escape_special_whitespace=False
1113
+ ):
1114
+ """Helper for writing string literals, minimizing escapes.
1115
+ Returns the tuple (string literal to write, possible quote types).
1116
+ """
1117
+ def escape_char(c):
1118
+ # \n and \t are non-printable, but we only escape them if
1119
+ # escape_special_whitespace is True
1120
+ if not escape_special_whitespace and c in "\n\t":
1121
+ return c
1122
+ # Always escape backslashes and other non-printable characters
1123
+ if c == "\\" or not c.isprintable():
1124
+ return c.encode("unicode_escape").decode("ascii")
1125
+ return c
1126
+
1127
+ escaped_string = "".join(map(escape_char, string))
1128
+ possible_quotes = quote_types
1129
+ if "\n" in escaped_string:
1130
+ possible_quotes = [q for q in possible_quotes if q in _MULTI_QUOTES]
1131
+ possible_quotes = [q for q in possible_quotes if q not in escaped_string]
1132
+ if not possible_quotes:
1133
+ # If there aren't any possible_quotes, fallback to using repr
1134
+ # on the original string. Try to use a quote from quote_types,
1135
+ # e.g., so that we use triple quotes for docstrings.
1136
+ string = repr(string)
1137
+ quote = next((q for q in quote_types if string[0] in q), string[0])
1138
+ return string[1:-1], [quote]
1139
+ if escaped_string:
1140
+ # Sort so that we prefer '''"''' over """\""""
1141
+ possible_quotes.sort(key=lambda q: q[0] == escaped_string[-1])
1142
+ # If we're using triple quotes and we'd need to escape a final
1143
+ # quote, escape it
1144
+ if possible_quotes[0][0] == escaped_string[-1]:
1145
+ assert len(possible_quotes[0]) == 3
1146
+ escaped_string = escaped_string[:-1] + "\\" + escaped_string[-1]
1147
+ return escaped_string, possible_quotes
1148
+
1149
+ def _write_str_avoiding_backslashes(self, string, *, quote_types=_ALL_QUOTES):
1150
+ """Write string literal value with a best effort attempt to avoid backslashes."""
1151
+ string, quote_types = self._str_literal_helper(string, quote_types=quote_types)
1152
+ quote_type = quote_types[0]
1153
+ self.write(f"{quote_type}{string}{quote_type}")
1154
+
1155
+ def visit_JoinedStr(self, node):
1156
+ self.write("f")
1157
+ if self._avoid_backslashes:
1158
+ with self.buffered() as buffer:
1159
+ self._write_fstring_inner(node)
1160
+ return self._write_str_avoiding_backslashes("".join(buffer))
1161
+
1162
+ # If we don't need to avoid backslashes globally (i.e., we only need
1163
+ # to avoid them inside FormattedValues), it's cosmetically preferred
1164
+ # to use escaped whitespace. That is, it's preferred to use backslashes
1165
+ # for cases like: f"{x}\n". To accomplish this, we keep track of what
1166
+ # in our buffer corresponds to FormattedValues and what corresponds to
1167
+ # Constant parts of the f-string, and allow escapes accordingly.
1168
+ fstring_parts = []
1169
+ for value in node.values:
1170
+ with self.buffered() as buffer:
1171
+ self._write_fstring_inner(value)
1172
+ fstring_parts.append(
1173
+ ("".join(buffer), isinstance(value, Constant))
1174
+ )
1175
+
1176
+ new_fstring_parts = []
1177
+ quote_types = list(_ALL_QUOTES)
1178
+ fallback_to_repr = False
1179
+ for value, is_constant in fstring_parts:
1180
+ value, new_quote_types = self._str_literal_helper(
1181
+ value,
1182
+ quote_types=quote_types,
1183
+ escape_special_whitespace=is_constant,
1184
+ )
1185
+ new_fstring_parts.append(value)
1186
+ if set(new_quote_types).isdisjoint(quote_types):
1187
+ fallback_to_repr = True
1188
+ break
1189
+ quote_types = new_quote_types
1190
+
1191
+ if fallback_to_repr:
1192
+ # If we weren't able to find a quote type that works for all parts
1193
+ # of the JoinedStr, fallback to using repr and triple single quotes.
1194
+ quote_types = ["'''"]
1195
+ new_fstring_parts.clear()
1196
+ for value, is_constant in fstring_parts:
1197
+ value = repr('"' + value) # force repr to use single quotes
1198
+ expected_prefix = "'\""
1199
+ assert value.startswith(expected_prefix), repr(value)
1200
+ new_fstring_parts.append(value[len(expected_prefix):-1])
1201
+
1202
+ value = "".join(new_fstring_parts)
1203
+ quote_type = quote_types[0]
1204
+ self.write(f"{quote_type}{value}{quote_type}")
1205
+
1206
+ def _write_fstring_inner(self, node):
1207
+ if isinstance(node, JoinedStr):
1208
+ # for both the f-string itself, and format_spec
1209
+ for value in node.values:
1210
+ self._write_fstring_inner(value)
1211
+ elif isinstance(node, Constant) and isinstance(node.value, str):
1212
+ value = node.value.replace("{", "{{").replace("}", "}}")
1213
+ self.write(value)
1214
+ elif isinstance(node, FormattedValue):
1215
+ self.visit_FormattedValue(node)
1216
+ else:
1217
+ raise ValueError(f"Unexpected node inside JoinedStr, {node!r}")
1218
+
1219
+ def visit_FormattedValue(self, node):
1220
+ def unparse_inner(inner):
1221
+ unparser = type(self)(_avoid_backslashes=True)
1222
+ unparser.set_precedence(_Precedence.TEST.next(), inner)
1223
+ return unparser.visit(inner)
1224
+
1225
+ with self.delimit("{", "}"):
1226
+ expr = unparse_inner(node.value)
1227
+ if "\\" in expr:
1228
+ raise ValueError(
1229
+ "Unable to avoid backslash in f-string expression part"
1230
+ )
1231
+ if expr.startswith("{"):
1232
+ # Separate pair of opening brackets as "{ {"
1233
+ self.write(" ")
1234
+ self.write(expr)
1235
+ if node.conversion != -1:
1236
+ self.write(f"!{chr(node.conversion)}")
1237
+ if node.format_spec:
1238
+ self.write(":")
1239
+ self._write_fstring_inner(node.format_spec)
1240
+
1241
+ def visit_Name(self, node):
1242
+ self.write(node.id)
1243
+
1244
+ def _write_docstring(self, node):
1245
+ self.fill()
1246
+ if node.kind == "u":
1247
+ self.write("u")
1248
+ self._write_str_avoiding_backslashes(node.value, quote_types=_MULTI_QUOTES)
1249
+
1250
+ def _write_constant(self, value):
1251
+ if isinstance(value, (float, complex)):
1252
+ # Substitute overflowing decimal literal for AST infinities,
1253
+ # and inf - inf for NaNs.
1254
+ self.write(
1255
+ repr(value)
1256
+ .replace("inf", _INFSTR)
1257
+ .replace("nan", f"({_INFSTR}-{_INFSTR})")
1258
+ )
1259
+ elif self._avoid_backslashes and isinstance(value, str):
1260
+ self._write_str_avoiding_backslashes(value)
1261
+ else:
1262
+ self.write(repr(value))
1263
+
1264
+ def visit_Constant(self, node):
1265
+ value = node.value
1266
+ if isinstance(value, tuple):
1267
+ with self.delimit("(", ")"):
1268
+ self.items_view(self._write_constant, value)
1269
+ elif value is ...:
1270
+ self.write("...")
1271
+ else:
1272
+ if node.kind == "u":
1273
+ self.write("u")
1274
+ self._write_constant(node.value)
1275
+
1276
+ def visit_List(self, node):
1277
+ with self.delimit("[", "]"):
1278
+ self.interleave(lambda: self.write(", "), self.traverse, node.elts)
1279
+
1280
+ def visit_ListComp(self, node):
1281
+ with self.delimit("[", "]"):
1282
+ self.traverse(node.elt)
1283
+ for gen in node.generators:
1284
+ self.traverse(gen)
1285
+
1286
+ def visit_GeneratorExp(self, node):
1287
+ with self.delimit("(", ")"):
1288
+ self.traverse(node.elt)
1289
+ for gen in node.generators:
1290
+ self.traverse(gen)
1291
+
1292
+ def visit_SetComp(self, node):
1293
+ with self.delimit("{", "}"):
1294
+ self.traverse(node.elt)
1295
+ for gen in node.generators:
1296
+ self.traverse(gen)
1297
+
1298
+ def visit_DictComp(self, node):
1299
+ with self.delimit("{", "}"):
1300
+ self.traverse(node.key)
1301
+ self.write(": ")
1302
+ self.traverse(node.value)
1303
+ for gen in node.generators:
1304
+ self.traverse(gen)
1305
+
1306
+ def visit_comprehension(self, node):
1307
+ if node.is_async:
1308
+ self.write(" async for ")
1309
+ else:
1310
+ self.write(" for ")
1311
+ self.set_precedence(_Precedence.TUPLE, node.target)
1312
+ self.traverse(node.target)
1313
+ self.write(" in ")
1314
+ self.set_precedence(_Precedence.TEST.next(), node.iter, *node.ifs)
1315
+ self.traverse(node.iter)
1316
+ for if_clause in node.ifs:
1317
+ self.write(" if ")
1318
+ self.traverse(if_clause)
1319
+
1320
+ def visit_IfExp(self, node):
1321
+ with self.require_parens(_Precedence.TEST, node):
1322
+ self.set_precedence(_Precedence.TEST.next(), node.body, node.test)
1323
+ self.traverse(node.body)
1324
+ self.write(" if ")
1325
+ self.traverse(node.test)
1326
+ self.write(" else ")
1327
+ self.set_precedence(_Precedence.TEST, node.orelse)
1328
+ self.traverse(node.orelse)
1329
+
1330
+ def visit_Set(self, node):
1331
+ if node.elts:
1332
+ with self.delimit("{", "}"):
1333
+ self.interleave(lambda: self.write(", "), self.traverse, node.elts)
1334
+ else:
1335
+ # `{}` would be interpreted as a dictionary literal, and
1336
+ # `set` might be shadowed. Thus:
1337
+ self.write('{*()}')
1338
+
1339
+ def visit_Dict(self, node):
1340
+ def write_key_value_pair(k, v):
1341
+ self.traverse(k)
1342
+ self.write(": ")
1343
+ self.traverse(v)
1344
+
1345
+ def write_item(item):
1346
+ k, v = item
1347
+ if k is None:
1348
+ # for dictionary unpacking operator in dicts {**{'y': 2}}
1349
+ # see PEP 448 for details
1350
+ self.write("**")
1351
+ self.set_precedence(_Precedence.EXPR, v)
1352
+ self.traverse(v)
1353
+ else:
1354
+ write_key_value_pair(k, v)
1355
+
1356
+ with self.delimit("{", "}"):
1357
+ self.interleave(
1358
+ lambda: self.write(", "), write_item, zip(node.keys, node.values)
1359
+ )
1360
+
1361
+ def visit_Tuple(self, node):
1362
+ with self.delimit_if(
1363
+ "(",
1364
+ ")",
1365
+ len(node.elts) == 0 or self.get_precedence(node) > _Precedence.TUPLE
1366
+ ):
1367
+ self.items_view(self.traverse, node.elts)
1368
+
1369
+ unop = {"Invert": "~", "Not": "not", "UAdd": "+", "USub": "-"}
1370
+ unop_precedence = {
1371
+ "not": _Precedence.NOT,
1372
+ "~": _Precedence.FACTOR,
1373
+ "+": _Precedence.FACTOR,
1374
+ "-": _Precedence.FACTOR,
1375
+ }
1376
+
1377
+ def visit_UnaryOp(self, node):
1378
+ operator = self.unop[node.op.__class__.__name__]
1379
+ operator_precedence = self.unop_precedence[operator]
1380
+ with self.require_parens(operator_precedence, node):
1381
+ self.write(operator)
1382
+ # factor prefixes (+, -, ~) shouldn't be separated
1383
+ # from the value they belong, (e.g: +1 instead of + 1)
1384
+ if operator_precedence is not _Precedence.FACTOR:
1385
+ self.write(" ")
1386
+ self.set_precedence(operator_precedence, node.operand)
1387
+ self.traverse(node.operand)
1388
+
1389
+ binop = {
1390
+ "Add": "+",
1391
+ "Sub": "-",
1392
+ "Mult": "*",
1393
+ "MatMult": "@",
1394
+ "Div": "/",
1395
+ "Mod": "%",
1396
+ "LShift": "<<",
1397
+ "RShift": ">>",
1398
+ "BitOr": "|",
1399
+ "BitXor": "^",
1400
+ "BitAnd": "&",
1401
+ "FloorDiv": "//",
1402
+ "Pow": "**",
1403
+ }
1404
+
1405
+ binop_precedence = {
1406
+ "+": _Precedence.ARITH,
1407
+ "-": _Precedence.ARITH,
1408
+ "*": _Precedence.TERM,
1409
+ "@": _Precedence.TERM,
1410
+ "/": _Precedence.TERM,
1411
+ "%": _Precedence.TERM,
1412
+ "<<": _Precedence.SHIFT,
1413
+ ">>": _Precedence.SHIFT,
1414
+ "|": _Precedence.BOR,
1415
+ "^": _Precedence.BXOR,
1416
+ "&": _Precedence.BAND,
1417
+ "//": _Precedence.TERM,
1418
+ "**": _Precedence.POWER,
1419
+ }
1420
+
1421
+ binop_rassoc = frozenset(("**",))
1422
+ def visit_BinOp(self, node):
1423
+ operator = self.binop[node.op.__class__.__name__]
1424
+ operator_precedence = self.binop_precedence[operator]
1425
+ with self.require_parens(operator_precedence, node):
1426
+ if operator in self.binop_rassoc:
1427
+ left_precedence = operator_precedence.next()
1428
+ right_precedence = operator_precedence
1429
+ else:
1430
+ left_precedence = operator_precedence
1431
+ right_precedence = operator_precedence.next()
1432
+
1433
+ self.set_precedence(left_precedence, node.left)
1434
+ self.traverse(node.left)
1435
+ self.write(f" {operator} ")
1436
+ self.set_precedence(right_precedence, node.right)
1437
+ self.traverse(node.right)
1438
+
1439
+ cmpops = {
1440
+ "Eq": "==",
1441
+ "NotEq": "!=",
1442
+ "Lt": "<",
1443
+ "LtE": "<=",
1444
+ "Gt": ">",
1445
+ "GtE": ">=",
1446
+ "Is": "is",
1447
+ "IsNot": "is not",
1448
+ "In": "in",
1449
+ "NotIn": "not in",
1450
+ }
1451
+
1452
+ def visit_Compare(self, node):
1453
+ with self.require_parens(_Precedence.CMP, node):
1454
+ self.set_precedence(_Precedence.CMP.next(), node.left, *node.comparators)
1455
+ self.traverse(node.left)
1456
+ for o, e in zip(node.ops, node.comparators):
1457
+ self.write(" " + self.cmpops[o.__class__.__name__] + " ")
1458
+ self.traverse(e)
1459
+
1460
+ boolops = {"And": "and", "Or": "or"}
1461
+ boolop_precedence = {"and": _Precedence.AND, "or": _Precedence.OR}
1462
+
1463
+ def visit_BoolOp(self, node):
1464
+ operator = self.boolops[node.op.__class__.__name__]
1465
+ operator_precedence = self.boolop_precedence[operator]
1466
+
1467
+ def increasing_level_traverse(node):
1468
+ nonlocal operator_precedence
1469
+ operator_precedence = operator_precedence.next()
1470
+ self.set_precedence(operator_precedence, node)
1471
+ self.traverse(node)
1472
+
1473
+ with self.require_parens(operator_precedence, node):
1474
+ s = f" {operator} "
1475
+ self.interleave(lambda: self.write(s), increasing_level_traverse, node.values)
1476
+
1477
+ def visit_Attribute(self, node):
1478
+ self.set_precedence(_Precedence.ATOM, node.value)
1479
+ self.traverse(node.value)
1480
+ # Special case: 3.__abs__() is a syntax error, so if node.value
1481
+ # is an integer literal then we need to either parenthesize
1482
+ # it or add an extra space to get 3 .__abs__().
1483
+ if isinstance(node.value, Constant) and isinstance(node.value.value, int):
1484
+ self.write(" ")
1485
+ self.write(".")
1486
+ self.write(node.attr)
1487
+
1488
+ def visit_Call(self, node):
1489
+ self.set_precedence(_Precedence.ATOM, node.func)
1490
+ self.traverse(node.func)
1491
+ with self.delimit("(", ")"):
1492
+ comma = False
1493
+ for e in node.args:
1494
+ if comma:
1495
+ self.write(", ")
1496
+ else:
1497
+ comma = True
1498
+ self.traverse(e)
1499
+ for e in node.keywords:
1500
+ if comma:
1501
+ self.write(", ")
1502
+ else:
1503
+ comma = True
1504
+ self.traverse(e)
1505
+
1506
+ def visit_Subscript(self, node):
1507
+ def is_non_empty_tuple(slice_value):
1508
+ return (
1509
+ isinstance(slice_value, Tuple)
1510
+ and slice_value.elts
1511
+ )
1512
+
1513
+ self.set_precedence(_Precedence.ATOM, node.value)
1514
+ self.traverse(node.value)
1515
+ with self.delimit("[", "]"):
1516
+ if is_non_empty_tuple(node.slice):
1517
+ # parentheses can be omitted if the tuple isn't empty
1518
+ self.items_view(self.traverse, node.slice.elts)
1519
+ else:
1520
+ self.traverse(node.slice)
1521
+
1522
+ def visit_Starred(self, node):
1523
+ self.write("*")
1524
+ self.set_precedence(_Precedence.EXPR, node.value)
1525
+ self.traverse(node.value)
1526
+
1527
+ def visit_Ellipsis(self, node):
1528
+ self.write("...")
1529
+
1530
+ def visit_Slice(self, node):
1531
+ if node.lower:
1532
+ self.traverse(node.lower)
1533
+ self.write(":")
1534
+ if node.upper:
1535
+ self.traverse(node.upper)
1536
+ if node.step:
1537
+ self.write(":")
1538
+ self.traverse(node.step)
1539
+
1540
+ def visit_Match(self, node):
1541
+ self.fill("match ")
1542
+ self.traverse(node.subject)
1543
+ with self.block():
1544
+ for case in node.cases:
1545
+ self.traverse(case)
1546
+
1547
+ def visit_arg(self, node):
1548
+ self.write(node.arg)
1549
+ if node.annotation:
1550
+ self.write(": ")
1551
+ self.traverse(node.annotation)
1552
+
1553
+ def visit_arguments(self, node):
1554
+ first = True
1555
+ # normal arguments
1556
+ all_args = node.posonlyargs + node.args
1557
+ defaults = [None] * (len(all_args) - len(node.defaults)) + node.defaults
1558
+ for index, elements in enumerate(zip(all_args, defaults), 1):
1559
+ a, d = elements
1560
+ if first:
1561
+ first = False
1562
+ else:
1563
+ self.write(", ")
1564
+ self.traverse(a)
1565
+ if d:
1566
+ self.write("=")
1567
+ self.traverse(d)
1568
+ if index == len(node.posonlyargs):
1569
+ self.write(", /")
1570
+
1571
+ # varargs, or bare '*' if no varargs but keyword-only arguments present
1572
+ if node.vararg or node.kwonlyargs:
1573
+ if first:
1574
+ first = False
1575
+ else:
1576
+ self.write(", ")
1577
+ self.write("*")
1578
+ if node.vararg:
1579
+ self.write(node.vararg.arg)
1580
+ if node.vararg.annotation:
1581
+ self.write(": ")
1582
+ self.traverse(node.vararg.annotation)
1583
+
1584
+ # keyword-only arguments
1585
+ if node.kwonlyargs:
1586
+ for a, d in zip(node.kwonlyargs, node.kw_defaults):
1587
+ self.write(", ")
1588
+ self.traverse(a)
1589
+ if d:
1590
+ self.write("=")
1591
+ self.traverse(d)
1592
+
1593
+ # kwargs
1594
+ if node.kwarg:
1595
+ if first:
1596
+ first = False
1597
+ else:
1598
+ self.write(", ")
1599
+ self.write("**" + node.kwarg.arg)
1600
+ if node.kwarg.annotation:
1601
+ self.write(": ")
1602
+ self.traverse(node.kwarg.annotation)
1603
+
1604
+ def visit_keyword(self, node):
1605
+ if node.arg is None:
1606
+ self.write("**")
1607
+ else:
1608
+ self.write(node.arg)
1609
+ self.write("=")
1610
+ self.traverse(node.value)
1611
+
1612
+ def visit_Lambda(self, node):
1613
+ with self.require_parens(_Precedence.TEST, node):
1614
+ self.write("lambda")
1615
+ with self.buffered() as buffer:
1616
+ self.traverse(node.args)
1617
+ if buffer:
1618
+ self.write(" ", *buffer)
1619
+ self.write(": ")
1620
+ self.set_precedence(_Precedence.TEST, node.body)
1621
+ self.traverse(node.body)
1622
+
1623
+ def visit_alias(self, node):
1624
+ self.write(node.name)
1625
+ if node.asname:
1626
+ self.write(" as " + node.asname)
1627
+
1628
+ def visit_withitem(self, node):
1629
+ self.traverse(node.context_expr)
1630
+ if node.optional_vars:
1631
+ self.write(" as ")
1632
+ self.traverse(node.optional_vars)
1633
+
1634
+ def visit_match_case(self, node):
1635
+ self.fill("case ")
1636
+ self.traverse(node.pattern)
1637
+ if node.guard:
1638
+ self.write(" if ")
1639
+ self.traverse(node.guard)
1640
+ with self.block():
1641
+ self.traverse(node.body)
1642
+
1643
+ def visit_MatchValue(self, node):
1644
+ self.traverse(node.value)
1645
+
1646
+ def visit_MatchSingleton(self, node):
1647
+ self._write_constant(node.value)
1648
+
1649
+ def visit_MatchSequence(self, node):
1650
+ with self.delimit("[", "]"):
1651
+ self.interleave(
1652
+ lambda: self.write(", "), self.traverse, node.patterns
1653
+ )
1654
+
1655
+ def visit_MatchStar(self, node):
1656
+ name = node.name
1657
+ if name is None:
1658
+ name = "_"
1659
+ self.write(f"*{name}")
1660
+
1661
+ def visit_MatchMapping(self, node):
1662
+ def write_key_pattern_pair(pair):
1663
+ k, p = pair
1664
+ self.traverse(k)
1665
+ self.write(": ")
1666
+ self.traverse(p)
1667
+
1668
+ with self.delimit("{", "}"):
1669
+ keys = node.keys
1670
+ self.interleave(
1671
+ lambda: self.write(", "),
1672
+ write_key_pattern_pair,
1673
+ zip(keys, node.patterns, strict=True),
1674
+ )
1675
+ rest = node.rest
1676
+ if rest is not None:
1677
+ if keys:
1678
+ self.write(", ")
1679
+ self.write(f"**{rest}")
1680
+
1681
+ def visit_MatchClass(self, node):
1682
+ self.set_precedence(_Precedence.ATOM, node.cls)
1683
+ self.traverse(node.cls)
1684
+ with self.delimit("(", ")"):
1685
+ patterns = node.patterns
1686
+ self.interleave(
1687
+ lambda: self.write(", "), self.traverse, patterns
1688
+ )
1689
+ attrs = node.kwd_attrs
1690
+ if attrs:
1691
+ def write_attr_pattern(pair):
1692
+ attr, pattern = pair
1693
+ self.write(f"{attr}=")
1694
+ self.traverse(pattern)
1695
+
1696
+ if patterns:
1697
+ self.write(", ")
1698
+ self.interleave(
1699
+ lambda: self.write(", "),
1700
+ write_attr_pattern,
1701
+ zip(attrs, node.kwd_patterns, strict=True),
1702
+ )
1703
+
1704
+ def visit_MatchAs(self, node):
1705
+ name = node.name
1706
+ pattern = node.pattern
1707
+ if name is None:
1708
+ self.write("_")
1709
+ elif pattern is None:
1710
+ self.write(node.name)
1711
+ else:
1712
+ with self.require_parens(_Precedence.TEST, node):
1713
+ self.set_precedence(_Precedence.BOR, node.pattern)
1714
+ self.traverse(node.pattern)
1715
+ self.write(f" as {node.name}")
1716
+
1717
+ def visit_MatchOr(self, node):
1718
+ with self.require_parens(_Precedence.BOR, node):
1719
+ self.set_precedence(_Precedence.BOR.next(), *node.patterns)
1720
+ self.interleave(lambda: self.write(" | "), self.traverse, node.patterns)
1721
+
1722
+ def unparse(ast_obj):
1723
+ unparser = _Unparser()
1724
+ return unparser.visit(ast_obj)
1725
+
1726
+
1727
+ def main():
1728
+ import argparse
1729
+
1730
+ parser = argparse.ArgumentParser(prog='python -m ast')
1731
+ parser.add_argument('infile', type=argparse.FileType(mode='rb'), nargs='?',
1732
+ default='-',
1733
+ help='the file to parse; defaults to stdin')
1734
+ parser.add_argument('-m', '--mode', default='exec',
1735
+ choices=('exec', 'single', 'eval', 'func_type'),
1736
+ help='specify what kind of code must be parsed')
1737
+ parser.add_argument('--no-type-comments', default=True, action='store_false',
1738
+ help="don't add information about type comments")
1739
+ parser.add_argument('-a', '--include-attributes', action='store_true',
1740
+ help='include attributes such as line numbers and '
1741
+ 'column offsets')
1742
+ parser.add_argument('-i', '--indent', type=int, default=3,
1743
+ help='indentation of nodes (number of spaces)')
1744
+ args = parser.parse_args()
1745
+
1746
+ with args.infile as infile:
1747
+ source = infile.read()
1748
+ tree = parse(source, args.infile.name, args.mode, type_comments=args.no_type_comments)
1749
+ print(dump(tree, include_attributes=args.include_attributes, indent=args.indent))
1750
+
1751
+ if __name__ == '__main__':
1752
+ main()
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asynchat.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- Mode: Python; tab-width: 4 -*-
2
+ # Id: asynchat.py,v 2.26 2000/09/07 22:29:26 rushing Exp
3
+ # Author: Sam Rushing <rushing@nightmare.com>
4
+
5
+ # ======================================================================
6
+ # Copyright 1996 by Sam Rushing
7
+ #
8
+ # All Rights Reserved
9
+ #
10
+ # Permission to use, copy, modify, and distribute this software and
11
+ # its documentation for any purpose and without fee is hereby
12
+ # granted, provided that the above copyright notice appear in all
13
+ # copies and that both that copyright notice and this permission
14
+ # notice appear in supporting documentation, and that the name of Sam
15
+ # Rushing not be used in advertising or publicity pertaining to
16
+ # distribution of the software without specific, written prior
17
+ # permission.
18
+ #
19
+ # SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
20
+ # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
21
+ # NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
22
+ # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
23
+ # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
24
+ # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
25
+ # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
26
+ # ======================================================================
27
+
28
+ r"""A class supporting chat-style (command/response) protocols.
29
+
30
+ This class adds support for 'chat' style protocols - where one side
31
+ sends a 'command', and the other sends a response (examples would be
32
+ the common internet protocols - smtp, nntp, ftp, etc..).
33
+
34
+ The handle_read() method looks at the input stream for the current
35
+ 'terminator' (usually '\r\n' for single-line responses, '\r\n.\r\n'
36
+ for multi-line output), calling self.found_terminator() on its
37
+ receipt.
38
+
39
+ for example:
40
+ Say you build an async nntp client using this class. At the start
41
+ of the connection, you'll have self.terminator set to '\r\n', in
42
+ order to process the single-line greeting. Just before issuing a
43
+ 'LIST' command you'll set it to '\r\n.\r\n'. The output of the LIST
44
+ command will be accumulated (using your own 'collect_incoming_data'
45
+ method) up to the terminator, and then control will be returned to
46
+ you - by calling your self.found_terminator() method.
47
+ """
48
+ import asyncore
49
+ from collections import deque
50
+
51
+ from warnings import _deprecated
52
+
53
+ _DEPRECATION_MSG = ('The {name} module is deprecated and will be removed in '
54
+ 'Python {remove}. The recommended replacement is asyncio')
55
+ _deprecated(__name__, _DEPRECATION_MSG, remove=(3, 12))
56
+
57
+
58
+
59
+ class async_chat(asyncore.dispatcher):
60
+ """This is an abstract class. You must derive from this class, and add
61
+ the two methods collect_incoming_data() and found_terminator()"""
62
+
63
+ # these are overridable defaults
64
+
65
+ ac_in_buffer_size = 65536
66
+ ac_out_buffer_size = 65536
67
+
68
+ # we don't want to enable the use of encoding by default, because that is a
69
+ # sign of an application bug that we don't want to pass silently
70
+
71
+ use_encoding = 0
72
+ encoding = 'latin-1'
73
+
74
+ def __init__(self, sock=None, map=None):
75
+ # for string terminator matching
76
+ self.ac_in_buffer = b''
77
+
78
+ # we use a list here rather than io.BytesIO for a few reasons...
79
+ # del lst[:] is faster than bio.truncate(0)
80
+ # lst = [] is faster than bio.truncate(0)
81
+ self.incoming = []
82
+
83
+ # we toss the use of the "simple producer" and replace it with
84
+ # a pure deque, which the original fifo was a wrapping of
85
+ self.producer_fifo = deque()
86
+ asyncore.dispatcher.__init__(self, sock, map)
87
+
88
+ def collect_incoming_data(self, data):
89
+ raise NotImplementedError("must be implemented in subclass")
90
+
91
+ def _collect_incoming_data(self, data):
92
+ self.incoming.append(data)
93
+
94
+ def _get_data(self):
95
+ d = b''.join(self.incoming)
96
+ del self.incoming[:]
97
+ return d
98
+
99
+ def found_terminator(self):
100
+ raise NotImplementedError("must be implemented in subclass")
101
+
102
+ def set_terminator(self, term):
103
+ """Set the input delimiter.
104
+
105
+ Can be a fixed string of any length, an integer, or None.
106
+ """
107
+ if isinstance(term, str) and self.use_encoding:
108
+ term = bytes(term, self.encoding)
109
+ elif isinstance(term, int) and term < 0:
110
+ raise ValueError('the number of received bytes must be positive')
111
+ self.terminator = term
112
+
113
+ def get_terminator(self):
114
+ return self.terminator
115
+
116
+ # grab some more data from the socket,
117
+ # throw it to the collector method,
118
+ # check for the terminator,
119
+ # if found, transition to the next state.
120
+
121
+ def handle_read(self):
122
+
123
+ try:
124
+ data = self.recv(self.ac_in_buffer_size)
125
+ except BlockingIOError:
126
+ return
127
+ except OSError:
128
+ self.handle_error()
129
+ return
130
+
131
+ if isinstance(data, str) and self.use_encoding:
132
+ data = bytes(str, self.encoding)
133
+ self.ac_in_buffer = self.ac_in_buffer + data
134
+
135
+ # Continue to search for self.terminator in self.ac_in_buffer,
136
+ # while calling self.collect_incoming_data. The while loop
137
+ # is necessary because we might read several data+terminator
138
+ # combos with a single recv(4096).
139
+
140
+ while self.ac_in_buffer:
141
+ lb = len(self.ac_in_buffer)
142
+ terminator = self.get_terminator()
143
+ if not terminator:
144
+ # no terminator, collect it all
145
+ self.collect_incoming_data(self.ac_in_buffer)
146
+ self.ac_in_buffer = b''
147
+ elif isinstance(terminator, int):
148
+ # numeric terminator
149
+ n = terminator
150
+ if lb < n:
151
+ self.collect_incoming_data(self.ac_in_buffer)
152
+ self.ac_in_buffer = b''
153
+ self.terminator = self.terminator - lb
154
+ else:
155
+ self.collect_incoming_data(self.ac_in_buffer[:n])
156
+ self.ac_in_buffer = self.ac_in_buffer[n:]
157
+ self.terminator = 0
158
+ self.found_terminator()
159
+ else:
160
+ # 3 cases:
161
+ # 1) end of buffer matches terminator exactly:
162
+ # collect data, transition
163
+ # 2) end of buffer matches some prefix:
164
+ # collect data to the prefix
165
+ # 3) end of buffer does not match any prefix:
166
+ # collect data
167
+ terminator_len = len(terminator)
168
+ index = self.ac_in_buffer.find(terminator)
169
+ if index != -1:
170
+ # we found the terminator
171
+ if index > 0:
172
+ # don't bother reporting the empty string
173
+ # (source of subtle bugs)
174
+ self.collect_incoming_data(self.ac_in_buffer[:index])
175
+ self.ac_in_buffer = self.ac_in_buffer[index+terminator_len:]
176
+ # This does the Right Thing if the terminator
177
+ # is changed here.
178
+ self.found_terminator()
179
+ else:
180
+ # check for a prefix of the terminator
181
+ index = find_prefix_at_end(self.ac_in_buffer, terminator)
182
+ if index:
183
+ if index != lb:
184
+ # we found a prefix, collect up to the prefix
185
+ self.collect_incoming_data(self.ac_in_buffer[:-index])
186
+ self.ac_in_buffer = self.ac_in_buffer[-index:]
187
+ break
188
+ else:
189
+ # no prefix, collect it all
190
+ self.collect_incoming_data(self.ac_in_buffer)
191
+ self.ac_in_buffer = b''
192
+
193
+ def handle_write(self):
194
+ self.initiate_send()
195
+
196
+ def handle_close(self):
197
+ self.close()
198
+
199
+ def push(self, data):
200
+ if not isinstance(data, (bytes, bytearray, memoryview)):
201
+ raise TypeError('data argument must be byte-ish (%r)',
202
+ type(data))
203
+ sabs = self.ac_out_buffer_size
204
+ if len(data) > sabs:
205
+ for i in range(0, len(data), sabs):
206
+ self.producer_fifo.append(data[i:i+sabs])
207
+ else:
208
+ self.producer_fifo.append(data)
209
+ self.initiate_send()
210
+
211
+ def push_with_producer(self, producer):
212
+ self.producer_fifo.append(producer)
213
+ self.initiate_send()
214
+
215
+ def readable(self):
216
+ "predicate for inclusion in the readable for select()"
217
+ # cannot use the old predicate, it violates the claim of the
218
+ # set_terminator method.
219
+
220
+ # return (len(self.ac_in_buffer) <= self.ac_in_buffer_size)
221
+ return 1
222
+
223
+ def writable(self):
224
+ "predicate for inclusion in the writable for select()"
225
+ return self.producer_fifo or (not self.connected)
226
+
227
+ def close_when_done(self):
228
+ "automatically close this channel once the outgoing queue is empty"
229
+ self.producer_fifo.append(None)
230
+
231
+ def initiate_send(self):
232
+ while self.producer_fifo and self.connected:
233
+ first = self.producer_fifo[0]
234
+ # handle empty string/buffer or None entry
235
+ if not first:
236
+ del self.producer_fifo[0]
237
+ if first is None:
238
+ self.handle_close()
239
+ return
240
+
241
+ # handle classic producer behavior
242
+ obs = self.ac_out_buffer_size
243
+ try:
244
+ data = first[:obs]
245
+ except TypeError:
246
+ data = first.more()
247
+ if data:
248
+ self.producer_fifo.appendleft(data)
249
+ else:
250
+ del self.producer_fifo[0]
251
+ continue
252
+
253
+ if isinstance(data, str) and self.use_encoding:
254
+ data = bytes(data, self.encoding)
255
+
256
+ # send the data
257
+ try:
258
+ num_sent = self.send(data)
259
+ except OSError:
260
+ self.handle_error()
261
+ return
262
+
263
+ if num_sent:
264
+ if num_sent < len(data) or obs < len(first):
265
+ self.producer_fifo[0] = first[num_sent:]
266
+ else:
267
+ del self.producer_fifo[0]
268
+ # we tried to send some actual data
269
+ return
270
+
271
+ def discard_buffers(self):
272
+ # Emergencies only!
273
+ self.ac_in_buffer = b''
274
+ del self.incoming[:]
275
+ self.producer_fifo.clear()
276
+
277
+
278
+ class simple_producer:
279
+
280
+ def __init__(self, data, buffer_size=512):
281
+ self.data = data
282
+ self.buffer_size = buffer_size
283
+
284
+ def more(self):
285
+ if len(self.data) > self.buffer_size:
286
+ result = self.data[:self.buffer_size]
287
+ self.data = self.data[self.buffer_size:]
288
+ return result
289
+ else:
290
+ result = self.data
291
+ self.data = b''
292
+ return result
293
+
294
+
295
+ # Given 'haystack', see if any prefix of 'needle' is at its end. This
296
+ # assumes an exact match has already been checked. Return the number of
297
+ # characters matched.
298
+ # for example:
299
+ # f_p_a_e("qwerty\r", "\r\n") => 1
300
+ # f_p_a_e("qwertydkjf", "\r\n") => 0
301
+ # f_p_a_e("qwerty\r\n", "\r\n") => <undefined>
302
+
303
+ # this could maybe be made faster with a computed regex?
304
+ # [answer: no; circa Python-2.0, Jan 2001]
305
+ # new python: 28961/s
306
+ # old python: 18307/s
307
+ # re: 12820/s
308
+ # regex: 14035/s
309
+
310
+ def find_prefix_at_end(haystack, needle):
311
+ l = len(needle) - 1
312
+ while l and not haystack.endswith(needle[:l]):
313
+ l -= 1
314
+ return l
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/__init__.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The asyncio package, tracking PEP 3156."""
2
+
3
+ # flake8: noqa
4
+
5
+ import sys
6
+
7
+ # This relies on each of the submodules having an __all__ variable.
8
+ from .base_events import *
9
+ from .coroutines import *
10
+ from .events import *
11
+ from .exceptions import *
12
+ from .futures import *
13
+ from .locks import *
14
+ from .protocols import *
15
+ from .runners import *
16
+ from .queues import *
17
+ from .streams import *
18
+ from .subprocess import *
19
+ from .tasks import *
20
+ from .taskgroups import *
21
+ from .timeouts import *
22
+ from .threads import *
23
+ from .transports import *
24
+
25
+ __all__ = (base_events.__all__ +
26
+ coroutines.__all__ +
27
+ events.__all__ +
28
+ exceptions.__all__ +
29
+ futures.__all__ +
30
+ locks.__all__ +
31
+ protocols.__all__ +
32
+ runners.__all__ +
33
+ queues.__all__ +
34
+ streams.__all__ +
35
+ subprocess.__all__ +
36
+ tasks.__all__ +
37
+ threads.__all__ +
38
+ timeouts.__all__ +
39
+ transports.__all__)
40
+
41
+ if sys.platform == 'win32': # pragma: no cover
42
+ from .windows_events import *
43
+ __all__ += windows_events.__all__
44
+ else:
45
+ from .unix_events import * # pragma: no cover
46
+ __all__ += unix_events.__all__
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/__main__.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import asyncio
3
+ import code
4
+ import concurrent.futures
5
+ import inspect
6
+ import sys
7
+ import threading
8
+ import types
9
+ import warnings
10
+
11
+ from . import futures
12
+
13
+
14
+ class AsyncIOInteractiveConsole(code.InteractiveConsole):
15
+
16
+ def __init__(self, locals, loop):
17
+ super().__init__(locals)
18
+ self.compile.compiler.flags |= ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
19
+
20
+ self.loop = loop
21
+
22
+ def runcode(self, code):
23
+ future = concurrent.futures.Future()
24
+
25
+ def callback():
26
+ global repl_future
27
+ global repl_future_interrupted
28
+
29
+ repl_future = None
30
+ repl_future_interrupted = False
31
+
32
+ func = types.FunctionType(code, self.locals)
33
+ try:
34
+ coro = func()
35
+ except SystemExit:
36
+ raise
37
+ except KeyboardInterrupt as ex:
38
+ repl_future_interrupted = True
39
+ future.set_exception(ex)
40
+ return
41
+ except BaseException as ex:
42
+ future.set_exception(ex)
43
+ return
44
+
45
+ if not inspect.iscoroutine(coro):
46
+ future.set_result(coro)
47
+ return
48
+
49
+ try:
50
+ repl_future = self.loop.create_task(coro)
51
+ futures._chain_future(repl_future, future)
52
+ except BaseException as exc:
53
+ future.set_exception(exc)
54
+
55
+ loop.call_soon_threadsafe(callback)
56
+
57
+ try:
58
+ return future.result()
59
+ except SystemExit:
60
+ raise
61
+ except BaseException:
62
+ if repl_future_interrupted:
63
+ self.write("\nKeyboardInterrupt\n")
64
+ else:
65
+ self.showtraceback()
66
+
67
+
68
+ class REPLThread(threading.Thread):
69
+
70
+ def run(self):
71
+ try:
72
+ banner = (
73
+ f'asyncio REPL {sys.version} on {sys.platform}\n'
74
+ f'Use "await" directly instead of "asyncio.run()".\n'
75
+ f'Type "help", "copyright", "credits" or "license" '
76
+ f'for more information.\n'
77
+ f'{getattr(sys, "ps1", ">>> ")}import asyncio'
78
+ )
79
+
80
+ console.interact(
81
+ banner=banner,
82
+ exitmsg='exiting asyncio REPL...')
83
+ finally:
84
+ warnings.filterwarnings(
85
+ 'ignore',
86
+ message=r'^coroutine .* was never awaited$',
87
+ category=RuntimeWarning)
88
+
89
+ loop.call_soon_threadsafe(loop.stop)
90
+
91
+
92
+ if __name__ == '__main__':
93
+ sys.audit("cpython.run_stdin")
94
+
95
+ loop = asyncio.new_event_loop()
96
+ asyncio.set_event_loop(loop)
97
+
98
+ repl_locals = {'asyncio': asyncio}
99
+ for key in {'__name__', '__package__',
100
+ '__loader__', '__spec__',
101
+ '__builtins__', '__file__'}:
102
+ repl_locals[key] = locals()[key]
103
+
104
+ console = AsyncIOInteractiveConsole(repl_locals, loop)
105
+
106
+ repl_future = None
107
+ repl_future_interrupted = False
108
+
109
+ try:
110
+ import readline # NoQA
111
+ except ImportError:
112
+ pass
113
+
114
+ repl_thread = REPLThread()
115
+ repl_thread.daemon = True
116
+ repl_thread.start()
117
+
118
+ while True:
119
+ try:
120
+ loop.run_forever()
121
+ except KeyboardInterrupt:
122
+ if repl_future and not repl_future.done():
123
+ repl_future.cancel()
124
+ repl_future_interrupted = True
125
+ continue
126
+ else:
127
+ break
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/base_events.py ADDED
@@ -0,0 +1,1961 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base implementation of event loop.
2
+
3
+ The event loop can be broken up into a multiplexer (the part
4
+ responsible for notifying us of I/O events) and the event loop proper,
5
+ which wraps a multiplexer with functionality for scheduling callbacks,
6
+ immediately or at a given time in the future.
7
+
8
+ Whenever a public API takes a callback, subsequent positional
9
+ arguments will be passed to the callback if/when it is called. This
10
+ avoids the proliferation of trivial lambdas implementing closures.
11
+ Keyword arguments for the callback are not supported; this is a
12
+ conscious design decision, leaving the door open for keyword arguments
13
+ to modify the meaning of the API call itself.
14
+ """
15
+
16
+ import collections
17
+ import collections.abc
18
+ import concurrent.futures
19
+ import errno
20
+ import functools
21
+ import heapq
22
+ import itertools
23
+ import os
24
+ import socket
25
+ import stat
26
+ import subprocess
27
+ import threading
28
+ import time
29
+ import traceback
30
+ import sys
31
+ import warnings
32
+ import weakref
33
+
34
+ try:
35
+ import ssl
36
+ except ImportError: # pragma: no cover
37
+ ssl = None
38
+
39
+ from . import constants
40
+ from . import coroutines
41
+ from . import events
42
+ from . import exceptions
43
+ from . import futures
44
+ from . import protocols
45
+ from . import sslproto
46
+ from . import staggered
47
+ from . import tasks
48
+ from . import transports
49
+ from . import trsock
50
+ from .log import logger
51
+
52
+
53
+ __all__ = 'BaseEventLoop','Server',
54
+
55
+
56
+ # Minimum number of _scheduled timer handles before cleanup of
57
+ # cancelled handles is performed.
58
+ _MIN_SCHEDULED_TIMER_HANDLES = 100
59
+
60
+ # Minimum fraction of _scheduled timer handles that are cancelled
61
+ # before cleanup of cancelled handles is performed.
62
+ _MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
63
+
64
+
65
+ _HAS_IPv6 = hasattr(socket, 'AF_INET6')
66
+
67
+ # Maximum timeout passed to select to avoid OS limitations
68
+ MAXIMUM_SELECT_TIMEOUT = 24 * 3600
69
+
70
+
71
+ def _format_handle(handle):
72
+ cb = handle._callback
73
+ if isinstance(getattr(cb, '__self__', None), tasks.Task):
74
+ # format the task
75
+ return repr(cb.__self__)
76
+ else:
77
+ return str(handle)
78
+
79
+
80
+ def _format_pipe(fd):
81
+ if fd == subprocess.PIPE:
82
+ return '<pipe>'
83
+ elif fd == subprocess.STDOUT:
84
+ return '<stdout>'
85
+ else:
86
+ return repr(fd)
87
+
88
+
89
+ def _set_reuseport(sock):
90
+ if not hasattr(socket, 'SO_REUSEPORT'):
91
+ raise ValueError('reuse_port not supported by socket module')
92
+ else:
93
+ try:
94
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
95
+ except OSError:
96
+ raise ValueError('reuse_port not supported by socket module, '
97
+ 'SO_REUSEPORT defined but not implemented.')
98
+
99
+
100
+ def _ipaddr_info(host, port, family, type, proto, flowinfo=0, scopeid=0):
101
+ # Try to skip getaddrinfo if "host" is already an IP. Users might have
102
+ # handled name resolution in their own code and pass in resolved IPs.
103
+ if not hasattr(socket, 'inet_pton'):
104
+ return
105
+
106
+ if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
107
+ host is None:
108
+ return None
109
+
110
+ if type == socket.SOCK_STREAM:
111
+ proto = socket.IPPROTO_TCP
112
+ elif type == socket.SOCK_DGRAM:
113
+ proto = socket.IPPROTO_UDP
114
+ else:
115
+ return None
116
+
117
+ if port is None:
118
+ port = 0
119
+ elif isinstance(port, bytes) and port == b'':
120
+ port = 0
121
+ elif isinstance(port, str) and port == '':
122
+ port = 0
123
+ else:
124
+ # If port's a service name like "http", don't skip getaddrinfo.
125
+ try:
126
+ port = int(port)
127
+ except (TypeError, ValueError):
128
+ return None
129
+
130
+ if family == socket.AF_UNSPEC:
131
+ afs = [socket.AF_INET]
132
+ if _HAS_IPv6:
133
+ afs.append(socket.AF_INET6)
134
+ else:
135
+ afs = [family]
136
+
137
+ if isinstance(host, bytes):
138
+ host = host.decode('idna')
139
+ if '%' in host:
140
+ # Linux's inet_pton doesn't accept an IPv6 zone index after host,
141
+ # like '::1%lo0'.
142
+ return None
143
+
144
+ for af in afs:
145
+ try:
146
+ socket.inet_pton(af, host)
147
+ # The host has already been resolved.
148
+ if _HAS_IPv6 and af == socket.AF_INET6:
149
+ return af, type, proto, '', (host, port, flowinfo, scopeid)
150
+ else:
151
+ return af, type, proto, '', (host, port)
152
+ except OSError:
153
+ pass
154
+
155
+ # "host" is not an IP address.
156
+ return None
157
+
158
+
159
+ def _interleave_addrinfos(addrinfos, first_address_family_count=1):
160
+ """Interleave list of addrinfo tuples by family."""
161
+ # Group addresses by family
162
+ addrinfos_by_family = collections.OrderedDict()
163
+ for addr in addrinfos:
164
+ family = addr[0]
165
+ if family not in addrinfos_by_family:
166
+ addrinfos_by_family[family] = []
167
+ addrinfos_by_family[family].append(addr)
168
+ addrinfos_lists = list(addrinfos_by_family.values())
169
+
170
+ reordered = []
171
+ if first_address_family_count > 1:
172
+ reordered.extend(addrinfos_lists[0][:first_address_family_count - 1])
173
+ del addrinfos_lists[0][:first_address_family_count - 1]
174
+ reordered.extend(
175
+ a for a in itertools.chain.from_iterable(
176
+ itertools.zip_longest(*addrinfos_lists)
177
+ ) if a is not None)
178
+ return reordered
179
+
180
+
181
+ def _run_until_complete_cb(fut):
182
+ if not fut.cancelled():
183
+ exc = fut.exception()
184
+ if isinstance(exc, (SystemExit, KeyboardInterrupt)):
185
+ # Issue #22429: run_forever() already finished, no need to
186
+ # stop it.
187
+ return
188
+ futures._get_loop(fut).stop()
189
+
190
+
191
+ if hasattr(socket, 'TCP_NODELAY'):
192
+ def _set_nodelay(sock):
193
+ if (sock.family in {socket.AF_INET, socket.AF_INET6} and
194
+ sock.type == socket.SOCK_STREAM and
195
+ sock.proto == socket.IPPROTO_TCP):
196
+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
197
+ else:
198
+ def _set_nodelay(sock):
199
+ pass
200
+
201
+
202
+ def _check_ssl_socket(sock):
203
+ if ssl is not None and isinstance(sock, ssl.SSLSocket):
204
+ raise TypeError("Socket cannot be of type SSLSocket")
205
+
206
+
207
+ class _SendfileFallbackProtocol(protocols.Protocol):
208
+ def __init__(self, transp):
209
+ if not isinstance(transp, transports._FlowControlMixin):
210
+ raise TypeError("transport should be _FlowControlMixin instance")
211
+ self._transport = transp
212
+ self._proto = transp.get_protocol()
213
+ self._should_resume_reading = transp.is_reading()
214
+ self._should_resume_writing = transp._protocol_paused
215
+ transp.pause_reading()
216
+ transp.set_protocol(self)
217
+ if self._should_resume_writing:
218
+ self._write_ready_fut = self._transport._loop.create_future()
219
+ else:
220
+ self._write_ready_fut = None
221
+
222
+ async def drain(self):
223
+ if self._transport.is_closing():
224
+ raise ConnectionError("Connection closed by peer")
225
+ fut = self._write_ready_fut
226
+ if fut is None:
227
+ return
228
+ await fut
229
+
230
+ def connection_made(self, transport):
231
+ raise RuntimeError("Invalid state: "
232
+ "connection should have been established already.")
233
+
234
+ def connection_lost(self, exc):
235
+ if self._write_ready_fut is not None:
236
+ # Never happens if peer disconnects after sending the whole content
237
+ # Thus disconnection is always an exception from user perspective
238
+ if exc is None:
239
+ self._write_ready_fut.set_exception(
240
+ ConnectionError("Connection is closed by peer"))
241
+ else:
242
+ self._write_ready_fut.set_exception(exc)
243
+ self._proto.connection_lost(exc)
244
+
245
+ def pause_writing(self):
246
+ if self._write_ready_fut is not None:
247
+ return
248
+ self._write_ready_fut = self._transport._loop.create_future()
249
+
250
+ def resume_writing(self):
251
+ if self._write_ready_fut is None:
252
+ return
253
+ self._write_ready_fut.set_result(False)
254
+ self._write_ready_fut = None
255
+
256
+ def data_received(self, data):
257
+ raise RuntimeError("Invalid state: reading should be paused")
258
+
259
+ def eof_received(self):
260
+ raise RuntimeError("Invalid state: reading should be paused")
261
+
262
+ async def restore(self):
263
+ self._transport.set_protocol(self._proto)
264
+ if self._should_resume_reading:
265
+ self._transport.resume_reading()
266
+ if self._write_ready_fut is not None:
267
+ # Cancel the future.
268
+ # Basically it has no effect because protocol is switched back,
269
+ # no code should wait for it anymore.
270
+ self._write_ready_fut.cancel()
271
+ if self._should_resume_writing:
272
+ self._proto.resume_writing()
273
+
274
+
275
+ class Server(events.AbstractServer):
276
+
277
+ def __init__(self, loop, sockets, protocol_factory, ssl_context, backlog,
278
+ ssl_handshake_timeout, ssl_shutdown_timeout=None):
279
+ self._loop = loop
280
+ self._sockets = sockets
281
+ self._active_count = 0
282
+ self._waiters = []
283
+ self._protocol_factory = protocol_factory
284
+ self._backlog = backlog
285
+ self._ssl_context = ssl_context
286
+ self._ssl_handshake_timeout = ssl_handshake_timeout
287
+ self._ssl_shutdown_timeout = ssl_shutdown_timeout
288
+ self._serving = False
289
+ self._serving_forever_fut = None
290
+
291
+ def __repr__(self):
292
+ return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
293
+
294
+ def _attach(self):
295
+ assert self._sockets is not None
296
+ self._active_count += 1
297
+
298
+ def _detach(self):
299
+ assert self._active_count > 0
300
+ self._active_count -= 1
301
+ if self._active_count == 0 and self._sockets is None:
302
+ self._wakeup()
303
+
304
+ def _wakeup(self):
305
+ waiters = self._waiters
306
+ self._waiters = None
307
+ for waiter in waiters:
308
+ if not waiter.done():
309
+ waiter.set_result(waiter)
310
+
311
+ def _start_serving(self):
312
+ if self._serving:
313
+ return
314
+ self._serving = True
315
+ for sock in self._sockets:
316
+ sock.listen(self._backlog)
317
+ self._loop._start_serving(
318
+ self._protocol_factory, sock, self._ssl_context,
319
+ self, self._backlog, self._ssl_handshake_timeout,
320
+ self._ssl_shutdown_timeout)
321
+
322
+ def get_loop(self):
323
+ return self._loop
324
+
325
+ def is_serving(self):
326
+ return self._serving
327
+
328
+ @property
329
+ def sockets(self):
330
+ if self._sockets is None:
331
+ return ()
332
+ return tuple(trsock.TransportSocket(s) for s in self._sockets)
333
+
334
+ def close(self):
335
+ sockets = self._sockets
336
+ if sockets is None:
337
+ return
338
+ self._sockets = None
339
+
340
+ for sock in sockets:
341
+ self._loop._stop_serving(sock)
342
+
343
+ self._serving = False
344
+
345
+ if (self._serving_forever_fut is not None and
346
+ not self._serving_forever_fut.done()):
347
+ self._serving_forever_fut.cancel()
348
+ self._serving_forever_fut = None
349
+
350
+ if self._active_count == 0:
351
+ self._wakeup()
352
+
353
+ async def start_serving(self):
354
+ self._start_serving()
355
+ # Skip one loop iteration so that all 'loop.add_reader'
356
+ # go through.
357
+ await tasks.sleep(0)
358
+
359
+ async def serve_forever(self):
360
+ if self._serving_forever_fut is not None:
361
+ raise RuntimeError(
362
+ f'server {self!r} is already being awaited on serve_forever()')
363
+ if self._sockets is None:
364
+ raise RuntimeError(f'server {self!r} is closed')
365
+
366
+ self._start_serving()
367
+ self._serving_forever_fut = self._loop.create_future()
368
+
369
+ try:
370
+ await self._serving_forever_fut
371
+ except exceptions.CancelledError:
372
+ try:
373
+ self.close()
374
+ await self.wait_closed()
375
+ finally:
376
+ raise
377
+ finally:
378
+ self._serving_forever_fut = None
379
+
380
+ async def wait_closed(self):
381
+ if self._sockets is None or self._waiters is None:
382
+ return
383
+ waiter = self._loop.create_future()
384
+ self._waiters.append(waiter)
385
+ await waiter
386
+
387
+
388
+ class BaseEventLoop(events.AbstractEventLoop):
389
+
390
+ def __init__(self):
391
+ self._timer_cancelled_count = 0
392
+ self._closed = False
393
+ self._stopping = False
394
+ self._ready = collections.deque()
395
+ self._scheduled = []
396
+ self._default_executor = None
397
+ self._internal_fds = 0
398
+ # Identifier of the thread running the event loop, or None if the
399
+ # event loop is not running
400
+ self._thread_id = None
401
+ self._clock_resolution = time.get_clock_info('monotonic').resolution
402
+ self._exception_handler = None
403
+ self.set_debug(coroutines._is_debug_mode())
404
+ # In debug mode, if the execution of a callback or a step of a task
405
+ # exceed this duration in seconds, the slow callback/task is logged.
406
+ self.slow_callback_duration = 0.1
407
+ self._current_handle = None
408
+ self._task_factory = None
409
+ self._coroutine_origin_tracking_enabled = False
410
+ self._coroutine_origin_tracking_saved_depth = None
411
+
412
+ # A weak set of all asynchronous generators that are
413
+ # being iterated by the loop.
414
+ self._asyncgens = weakref.WeakSet()
415
+ # Set to True when `loop.shutdown_asyncgens` is called.
416
+ self._asyncgens_shutdown_called = False
417
+ # Set to True when `loop.shutdown_default_executor` is called.
418
+ self._executor_shutdown_called = False
419
+
420
+ def __repr__(self):
421
+ return (
422
+ f'<{self.__class__.__name__} running={self.is_running()} '
423
+ f'closed={self.is_closed()} debug={self.get_debug()}>'
424
+ )
425
+
426
+ def create_future(self):
427
+ """Create a Future object attached to the loop."""
428
+ return futures.Future(loop=self)
429
+
430
+ def create_task(self, coro, *, name=None, context=None):
431
+ """Schedule a coroutine object.
432
+
433
+ Return a task object.
434
+ """
435
+ self._check_closed()
436
+ if self._task_factory is None:
437
+ task = tasks.Task(coro, loop=self, name=name, context=context)
438
+ if task._source_traceback:
439
+ del task._source_traceback[-1]
440
+ else:
441
+ if context is None:
442
+ # Use legacy API if context is not needed
443
+ task = self._task_factory(self, coro)
444
+ else:
445
+ task = self._task_factory(self, coro, context=context)
446
+
447
+ tasks._set_task_name(task, name)
448
+
449
+ return task
450
+
451
+ def set_task_factory(self, factory):
452
+ """Set a task factory that will be used by loop.create_task().
453
+
454
+ If factory is None the default task factory will be set.
455
+
456
+ If factory is a callable, it should have a signature matching
457
+ '(loop, coro)', where 'loop' will be a reference to the active
458
+ event loop, 'coro' will be a coroutine object. The callable
459
+ must return a Future.
460
+ """
461
+ if factory is not None and not callable(factory):
462
+ raise TypeError('task factory must be a callable or None')
463
+ self._task_factory = factory
464
+
465
+ def get_task_factory(self):
466
+ """Return a task factory, or None if the default one is in use."""
467
+ return self._task_factory
468
+
469
+ def _make_socket_transport(self, sock, protocol, waiter=None, *,
470
+ extra=None, server=None):
471
+ """Create socket transport."""
472
+ raise NotImplementedError
473
+
474
+ def _make_ssl_transport(
475
+ self, rawsock, protocol, sslcontext, waiter=None,
476
+ *, server_side=False, server_hostname=None,
477
+ extra=None, server=None,
478
+ ssl_handshake_timeout=None,
479
+ ssl_shutdown_timeout=None,
480
+ call_connection_made=True):
481
+ """Create SSL transport."""
482
+ raise NotImplementedError
483
+
484
+ def _make_datagram_transport(self, sock, protocol,
485
+ address=None, waiter=None, extra=None):
486
+ """Create datagram transport."""
487
+ raise NotImplementedError
488
+
489
+ def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
490
+ extra=None):
491
+ """Create read pipe transport."""
492
+ raise NotImplementedError
493
+
494
+ def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
495
+ extra=None):
496
+ """Create write pipe transport."""
497
+ raise NotImplementedError
498
+
499
+ async def _make_subprocess_transport(self, protocol, args, shell,
500
+ stdin, stdout, stderr, bufsize,
501
+ extra=None, **kwargs):
502
+ """Create subprocess transport."""
503
+ raise NotImplementedError
504
+
505
+ def _write_to_self(self):
506
+ """Write a byte to self-pipe, to wake up the event loop.
507
+
508
+ This may be called from a different thread.
509
+
510
+ The subclass is responsible for implementing the self-pipe.
511
+ """
512
+ raise NotImplementedError
513
+
514
+ def _process_events(self, event_list):
515
+ """Process selector events."""
516
+ raise NotImplementedError
517
+
518
+ def _check_closed(self):
519
+ if self._closed:
520
+ raise RuntimeError('Event loop is closed')
521
+
522
+ def _check_default_executor(self):
523
+ if self._executor_shutdown_called:
524
+ raise RuntimeError('Executor shutdown has been called')
525
+
526
+ def _asyncgen_finalizer_hook(self, agen):
527
+ self._asyncgens.discard(agen)
528
+ if not self.is_closed():
529
+ self.call_soon_threadsafe(self.create_task, agen.aclose())
530
+
531
+ def _asyncgen_firstiter_hook(self, agen):
532
+ if self._asyncgens_shutdown_called:
533
+ warnings.warn(
534
+ f"asynchronous generator {agen!r} was scheduled after "
535
+ f"loop.shutdown_asyncgens() call",
536
+ ResourceWarning, source=self)
537
+
538
+ self._asyncgens.add(agen)
539
+
540
+ async def shutdown_asyncgens(self):
541
+ """Shutdown all active asynchronous generators."""
542
+ self._asyncgens_shutdown_called = True
543
+
544
+ if not len(self._asyncgens):
545
+ # If Python version is <3.6 or we don't have any asynchronous
546
+ # generators alive.
547
+ return
548
+
549
+ closing_agens = list(self._asyncgens)
550
+ self._asyncgens.clear()
551
+
552
+ results = await tasks.gather(
553
+ *[ag.aclose() for ag in closing_agens],
554
+ return_exceptions=True)
555
+
556
+ for result, agen in zip(results, closing_agens):
557
+ if isinstance(result, Exception):
558
+ self.call_exception_handler({
559
+ 'message': f'an error occurred during closing of '
560
+ f'asynchronous generator {agen!r}',
561
+ 'exception': result,
562
+ 'asyncgen': agen
563
+ })
564
+
565
+ async def shutdown_default_executor(self):
566
+ """Schedule the shutdown of the default executor."""
567
+ self._executor_shutdown_called = True
568
+ if self._default_executor is None:
569
+ return
570
+ future = self.create_future()
571
+ thread = threading.Thread(target=self._do_shutdown, args=(future,))
572
+ thread.start()
573
+ try:
574
+ await future
575
+ finally:
576
+ thread.join()
577
+
578
+ def _do_shutdown(self, future):
579
+ try:
580
+ self._default_executor.shutdown(wait=True)
581
+ if not self.is_closed():
582
+ self.call_soon_threadsafe(future.set_result, None)
583
+ except Exception as ex:
584
+ if not self.is_closed():
585
+ self.call_soon_threadsafe(future.set_exception, ex)
586
+
587
+ def _check_running(self):
588
+ if self.is_running():
589
+ raise RuntimeError('This event loop is already running')
590
+ if events._get_running_loop() is not None:
591
+ raise RuntimeError(
592
+ 'Cannot run the event loop while another loop is running')
593
+
594
+ def run_forever(self):
595
+ """Run until stop() is called."""
596
+ self._check_closed()
597
+ self._check_running()
598
+ self._set_coroutine_origin_tracking(self._debug)
599
+
600
+ old_agen_hooks = sys.get_asyncgen_hooks()
601
+ try:
602
+ self._thread_id = threading.get_ident()
603
+ sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
604
+ finalizer=self._asyncgen_finalizer_hook)
605
+
606
+ events._set_running_loop(self)
607
+ while True:
608
+ self._run_once()
609
+ if self._stopping:
610
+ break
611
+ finally:
612
+ self._stopping = False
613
+ self._thread_id = None
614
+ events._set_running_loop(None)
615
+ self._set_coroutine_origin_tracking(False)
616
+ sys.set_asyncgen_hooks(*old_agen_hooks)
617
+
618
+ def run_until_complete(self, future):
619
+ """Run until the Future is done.
620
+
621
+ If the argument is a coroutine, it is wrapped in a Task.
622
+
623
+ WARNING: It would be disastrous to call run_until_complete()
624
+ with the same coroutine twice -- it would wrap it in two
625
+ different Tasks and that can't be good.
626
+
627
+ Return the Future's result, or raise its exception.
628
+ """
629
+ self._check_closed()
630
+ self._check_running()
631
+
632
+ new_task = not futures.isfuture(future)
633
+ future = tasks.ensure_future(future, loop=self)
634
+ if new_task:
635
+ # An exception is raised if the future didn't complete, so there
636
+ # is no need to log the "destroy pending task" message
637
+ future._log_destroy_pending = False
638
+
639
+ future.add_done_callback(_run_until_complete_cb)
640
+ try:
641
+ self.run_forever()
642
+ except:
643
+ if new_task and future.done() and not future.cancelled():
644
+ # The coroutine raised a BaseException. Consume the exception
645
+ # to not log a warning, the caller doesn't have access to the
646
+ # local task.
647
+ future.exception()
648
+ raise
649
+ finally:
650
+ future.remove_done_callback(_run_until_complete_cb)
651
+ if not future.done():
652
+ raise RuntimeError('Event loop stopped before Future completed.')
653
+
654
+ return future.result()
655
+
656
+ def stop(self):
657
+ """Stop running the event loop.
658
+
659
+ Every callback already scheduled will still run. This simply informs
660
+ run_forever to stop looping after a complete iteration.
661
+ """
662
+ self._stopping = True
663
+
664
+ def close(self):
665
+ """Close the event loop.
666
+
667
+ This clears the queues and shuts down the executor,
668
+ but does not wait for the executor to finish.
669
+
670
+ The event loop must not be running.
671
+ """
672
+ if self.is_running():
673
+ raise RuntimeError("Cannot close a running event loop")
674
+ if self._closed:
675
+ return
676
+ if self._debug:
677
+ logger.debug("Close %r", self)
678
+ self._closed = True
679
+ self._ready.clear()
680
+ self._scheduled.clear()
681
+ self._executor_shutdown_called = True
682
+ executor = self._default_executor
683
+ if executor is not None:
684
+ self._default_executor = None
685
+ executor.shutdown(wait=False)
686
+
687
+ def is_closed(self):
688
+ """Returns True if the event loop was closed."""
689
+ return self._closed
690
+
691
+ def __del__(self, _warn=warnings.warn):
692
+ if not self.is_closed():
693
+ _warn(f"unclosed event loop {self!r}", ResourceWarning, source=self)
694
+ if not self.is_running():
695
+ self.close()
696
+
697
+ def is_running(self):
698
+ """Returns True if the event loop is running."""
699
+ return (self._thread_id is not None)
700
+
701
+ def time(self):
702
+ """Return the time according to the event loop's clock.
703
+
704
+ This is a float expressed in seconds since an epoch, but the
705
+ epoch, precision, accuracy and drift are unspecified and may
706
+ differ per event loop.
707
+ """
708
+ return time.monotonic()
709
+
710
+ def call_later(self, delay, callback, *args, context=None):
711
+ """Arrange for a callback to be called at a given time.
712
+
713
+ Return a Handle: an opaque object with a cancel() method that
714
+ can be used to cancel the call.
715
+
716
+ The delay can be an int or float, expressed in seconds. It is
717
+ always relative to the current time.
718
+
719
+ Each callback will be called exactly once. If two callbacks
720
+ are scheduled for exactly the same time, it is undefined which
721
+ will be called first.
722
+
723
+ Any positional arguments after the callback will be passed to
724
+ the callback when it is called.
725
+ """
726
+ if delay is None:
727
+ raise TypeError('delay must not be None')
728
+ timer = self.call_at(self.time() + delay, callback, *args,
729
+ context=context)
730
+ if timer._source_traceback:
731
+ del timer._source_traceback[-1]
732
+ return timer
733
+
734
+ def call_at(self, when, callback, *args, context=None):
735
+ """Like call_later(), but uses an absolute time.
736
+
737
+ Absolute time corresponds to the event loop's time() method.
738
+ """
739
+ if when is None:
740
+ raise TypeError("when cannot be None")
741
+ self._check_closed()
742
+ if self._debug:
743
+ self._check_thread()
744
+ self._check_callback(callback, 'call_at')
745
+ timer = events.TimerHandle(when, callback, args, self, context)
746
+ if timer._source_traceback:
747
+ del timer._source_traceback[-1]
748
+ heapq.heappush(self._scheduled, timer)
749
+ timer._scheduled = True
750
+ return timer
751
+
752
+ def call_soon(self, callback, *args, context=None):
753
+ """Arrange for a callback to be called as soon as possible.
754
+
755
+ This operates as a FIFO queue: callbacks are called in the
756
+ order in which they are registered. Each callback will be
757
+ called exactly once.
758
+
759
+ Any positional arguments after the callback will be passed to
760
+ the callback when it is called.
761
+ """
762
+ self._check_closed()
763
+ if self._debug:
764
+ self._check_thread()
765
+ self._check_callback(callback, 'call_soon')
766
+ handle = self._call_soon(callback, args, context)
767
+ if handle._source_traceback:
768
+ del handle._source_traceback[-1]
769
+ return handle
770
+
771
+ def _check_callback(self, callback, method):
772
+ if (coroutines.iscoroutine(callback) or
773
+ coroutines.iscoroutinefunction(callback)):
774
+ raise TypeError(
775
+ f"coroutines cannot be used with {method}()")
776
+ if not callable(callback):
777
+ raise TypeError(
778
+ f'a callable object was expected by {method}(), '
779
+ f'got {callback!r}')
780
+
781
+ def _call_soon(self, callback, args, context):
782
+ handle = events.Handle(callback, args, self, context)
783
+ if handle._source_traceback:
784
+ del handle._source_traceback[-1]
785
+ self._ready.append(handle)
786
+ return handle
787
+
788
+ def _check_thread(self):
789
+ """Check that the current thread is the thread running the event loop.
790
+
791
+ Non-thread-safe methods of this class make this assumption and will
792
+ likely behave incorrectly when the assumption is violated.
793
+
794
+ Should only be called when (self._debug == True). The caller is
795
+ responsible for checking this condition for performance reasons.
796
+ """
797
+ if self._thread_id is None:
798
+ return
799
+ thread_id = threading.get_ident()
800
+ if thread_id != self._thread_id:
801
+ raise RuntimeError(
802
+ "Non-thread-safe operation invoked on an event loop other "
803
+ "than the current one")
804
+
805
+ def call_soon_threadsafe(self, callback, *args, context=None):
806
+ """Like call_soon(), but thread-safe."""
807
+ self._check_closed()
808
+ if self._debug:
809
+ self._check_callback(callback, 'call_soon_threadsafe')
810
+ handle = self._call_soon(callback, args, context)
811
+ if handle._source_traceback:
812
+ del handle._source_traceback[-1]
813
+ self._write_to_self()
814
+ return handle
815
+
816
+ def run_in_executor(self, executor, func, *args):
817
+ self._check_closed()
818
+ if self._debug:
819
+ self._check_callback(func, 'run_in_executor')
820
+ if executor is None:
821
+ executor = self._default_executor
822
+ # Only check when the default executor is being used
823
+ self._check_default_executor()
824
+ if executor is None:
825
+ executor = concurrent.futures.ThreadPoolExecutor(
826
+ thread_name_prefix='asyncio'
827
+ )
828
+ self._default_executor = executor
829
+ return futures.wrap_future(
830
+ executor.submit(func, *args), loop=self)
831
+
832
+ def set_default_executor(self, executor):
833
+ if not isinstance(executor, concurrent.futures.ThreadPoolExecutor):
834
+ raise TypeError('executor must be ThreadPoolExecutor instance')
835
+ self._default_executor = executor
836
+
837
+ def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
838
+ msg = [f"{host}:{port!r}"]
839
+ if family:
840
+ msg.append(f'family={family!r}')
841
+ if type:
842
+ msg.append(f'type={type!r}')
843
+ if proto:
844
+ msg.append(f'proto={proto!r}')
845
+ if flags:
846
+ msg.append(f'flags={flags!r}')
847
+ msg = ', '.join(msg)
848
+ logger.debug('Get address info %s', msg)
849
+
850
+ t0 = self.time()
851
+ addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
852
+ dt = self.time() - t0
853
+
854
+ msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
855
+ if dt >= self.slow_callback_duration:
856
+ logger.info(msg)
857
+ else:
858
+ logger.debug(msg)
859
+ return addrinfo
860
+
861
+ async def getaddrinfo(self, host, port, *,
862
+ family=0, type=0, proto=0, flags=0):
863
+ if self._debug:
864
+ getaddr_func = self._getaddrinfo_debug
865
+ else:
866
+ getaddr_func = socket.getaddrinfo
867
+
868
+ return await self.run_in_executor(
869
+ None, getaddr_func, host, port, family, type, proto, flags)
870
+
871
+ async def getnameinfo(self, sockaddr, flags=0):
872
+ return await self.run_in_executor(
873
+ None, socket.getnameinfo, sockaddr, flags)
874
+
875
+ async def sock_sendfile(self, sock, file, offset=0, count=None,
876
+ *, fallback=True):
877
+ if self._debug and sock.gettimeout() != 0:
878
+ raise ValueError("the socket must be non-blocking")
879
+ _check_ssl_socket(sock)
880
+ self._check_sendfile_params(sock, file, offset, count)
881
+ try:
882
+ return await self._sock_sendfile_native(sock, file,
883
+ offset, count)
884
+ except exceptions.SendfileNotAvailableError as exc:
885
+ if not fallback:
886
+ raise
887
+ return await self._sock_sendfile_fallback(sock, file,
888
+ offset, count)
889
+
890
+ async def _sock_sendfile_native(self, sock, file, offset, count):
891
+ # NB: sendfile syscall is not supported for SSL sockets and
892
+ # non-mmap files even if sendfile is supported by OS
893
+ raise exceptions.SendfileNotAvailableError(
894
+ f"syscall sendfile is not available for socket {sock!r} "
895
+ f"and file {file!r} combination")
896
+
897
+ async def _sock_sendfile_fallback(self, sock, file, offset, count):
898
+ if offset:
899
+ file.seek(offset)
900
+ blocksize = (
901
+ min(count, constants.SENDFILE_FALLBACK_READBUFFER_SIZE)
902
+ if count else constants.SENDFILE_FALLBACK_READBUFFER_SIZE
903
+ )
904
+ buf = bytearray(blocksize)
905
+ total_sent = 0
906
+ try:
907
+ while True:
908
+ if count:
909
+ blocksize = min(count - total_sent, blocksize)
910
+ if blocksize <= 0:
911
+ break
912
+ view = memoryview(buf)[:blocksize]
913
+ read = await self.run_in_executor(None, file.readinto, view)
914
+ if not read:
915
+ break # EOF
916
+ await self.sock_sendall(sock, view[:read])
917
+ total_sent += read
918
+ return total_sent
919
+ finally:
920
+ if total_sent > 0 and hasattr(file, 'seek'):
921
+ file.seek(offset + total_sent)
922
+
923
+ def _check_sendfile_params(self, sock, file, offset, count):
924
+ if 'b' not in getattr(file, 'mode', 'b'):
925
+ raise ValueError("file should be opened in binary mode")
926
+ if not sock.type == socket.SOCK_STREAM:
927
+ raise ValueError("only SOCK_STREAM type sockets are supported")
928
+ if count is not None:
929
+ if not isinstance(count, int):
930
+ raise TypeError(
931
+ "count must be a positive integer (got {!r})".format(count))
932
+ if count <= 0:
933
+ raise ValueError(
934
+ "count must be a positive integer (got {!r})".format(count))
935
+ if not isinstance(offset, int):
936
+ raise TypeError(
937
+ "offset must be a non-negative integer (got {!r})".format(
938
+ offset))
939
+ if offset < 0:
940
+ raise ValueError(
941
+ "offset must be a non-negative integer (got {!r})".format(
942
+ offset))
943
+
944
+ async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None):
945
+ """Create, bind and connect one socket."""
946
+ my_exceptions = []
947
+ exceptions.append(my_exceptions)
948
+ family, type_, proto, _, address = addr_info
949
+ sock = None
950
+ try:
951
+ sock = socket.socket(family=family, type=type_, proto=proto)
952
+ sock.setblocking(False)
953
+ if local_addr_infos is not None:
954
+ for lfamily, _, _, _, laddr in local_addr_infos:
955
+ # skip local addresses of different family
956
+ if lfamily != family:
957
+ continue
958
+ try:
959
+ sock.bind(laddr)
960
+ break
961
+ except OSError as exc:
962
+ msg = (
963
+ f'error while attempting to bind on '
964
+ f'address {laddr!r}: '
965
+ f'{exc.strerror.lower()}'
966
+ )
967
+ exc = OSError(exc.errno, msg)
968
+ my_exceptions.append(exc)
969
+ else: # all bind attempts failed
970
+ if my_exceptions:
971
+ raise my_exceptions.pop()
972
+ else:
973
+ raise OSError(f"no matching local address with {family=} found")
974
+ await self.sock_connect(sock, address)
975
+ return sock
976
+ except OSError as exc:
977
+ my_exceptions.append(exc)
978
+ if sock is not None:
979
+ sock.close()
980
+ raise
981
+ except:
982
+ if sock is not None:
983
+ sock.close()
984
+ raise
985
+ finally:
986
+ exceptions = my_exceptions = None
987
+
988
+ async def create_connection(
989
+ self, protocol_factory, host=None, port=None,
990
+ *, ssl=None, family=0,
991
+ proto=0, flags=0, sock=None,
992
+ local_addr=None, server_hostname=None,
993
+ ssl_handshake_timeout=None,
994
+ ssl_shutdown_timeout=None,
995
+ happy_eyeballs_delay=None, interleave=None):
996
+ """Connect to a TCP server.
997
+
998
+ Create a streaming transport connection to a given internet host and
999
+ port: socket family AF_INET or socket.AF_INET6 depending on host (or
1000
+ family if specified), socket type SOCK_STREAM. protocol_factory must be
1001
+ a callable returning a protocol instance.
1002
+
1003
+ This method is a coroutine which will try to establish the connection
1004
+ in the background. When successful, the coroutine returns a
1005
+ (transport, protocol) pair.
1006
+ """
1007
+ if server_hostname is not None and not ssl:
1008
+ raise ValueError('server_hostname is only meaningful with ssl')
1009
+
1010
+ if server_hostname is None and ssl:
1011
+ # Use host as default for server_hostname. It is an error
1012
+ # if host is empty or not set, e.g. when an
1013
+ # already-connected socket was passed or when only a port
1014
+ # is given. To avoid this error, you can pass
1015
+ # server_hostname='' -- this will bypass the hostname
1016
+ # check. (This also means that if host is a numeric
1017
+ # IP/IPv6 address, we will attempt to verify that exact
1018
+ # address; this will probably fail, but it is possible to
1019
+ # create a certificate for a specific IP address, so we
1020
+ # don't judge it here.)
1021
+ if not host:
1022
+ raise ValueError('You must set server_hostname '
1023
+ 'when using ssl without a host')
1024
+ server_hostname = host
1025
+
1026
+ if ssl_handshake_timeout is not None and not ssl:
1027
+ raise ValueError(
1028
+ 'ssl_handshake_timeout is only meaningful with ssl')
1029
+
1030
+ if ssl_shutdown_timeout is not None and not ssl:
1031
+ raise ValueError(
1032
+ 'ssl_shutdown_timeout is only meaningful with ssl')
1033
+
1034
+ if sock is not None:
1035
+ _check_ssl_socket(sock)
1036
+
1037
+ if happy_eyeballs_delay is not None and interleave is None:
1038
+ # If using happy eyeballs, default to interleave addresses by family
1039
+ interleave = 1
1040
+
1041
+ if host is not None or port is not None:
1042
+ if sock is not None:
1043
+ raise ValueError(
1044
+ 'host/port and sock can not be specified at the same time')
1045
+
1046
+ infos = await self._ensure_resolved(
1047
+ (host, port), family=family,
1048
+ type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
1049
+ if not infos:
1050
+ raise OSError('getaddrinfo() returned empty list')
1051
+
1052
+ if local_addr is not None:
1053
+ laddr_infos = await self._ensure_resolved(
1054
+ local_addr, family=family,
1055
+ type=socket.SOCK_STREAM, proto=proto,
1056
+ flags=flags, loop=self)
1057
+ if not laddr_infos:
1058
+ raise OSError('getaddrinfo() returned empty list')
1059
+ else:
1060
+ laddr_infos = None
1061
+
1062
+ if interleave:
1063
+ infos = _interleave_addrinfos(infos, interleave)
1064
+
1065
+ exceptions = []
1066
+ if happy_eyeballs_delay is None:
1067
+ # not using happy eyeballs
1068
+ for addrinfo in infos:
1069
+ try:
1070
+ sock = await self._connect_sock(
1071
+ exceptions, addrinfo, laddr_infos)
1072
+ break
1073
+ except OSError:
1074
+ continue
1075
+ else: # using happy eyeballs
1076
+ sock, _, _ = await staggered.staggered_race(
1077
+ (functools.partial(self._connect_sock,
1078
+ exceptions, addrinfo, laddr_infos)
1079
+ for addrinfo in infos),
1080
+ happy_eyeballs_delay, loop=self)
1081
+
1082
+ if sock is None:
1083
+ exceptions = [exc for sub in exceptions for exc in sub]
1084
+ try:
1085
+ if len(exceptions) == 1:
1086
+ raise exceptions[0]
1087
+ else:
1088
+ # If they all have the same str(), raise one.
1089
+ model = str(exceptions[0])
1090
+ if all(str(exc) == model for exc in exceptions):
1091
+ raise exceptions[0]
1092
+ # Raise a combined exception so the user can see all
1093
+ # the various error messages.
1094
+ raise OSError('Multiple exceptions: {}'.format(
1095
+ ', '.join(str(exc) for exc in exceptions)))
1096
+ finally:
1097
+ exceptions = None
1098
+
1099
+ else:
1100
+ if sock is None:
1101
+ raise ValueError(
1102
+ 'host and port was not specified and no sock specified')
1103
+ if sock.type != socket.SOCK_STREAM:
1104
+ # We allow AF_INET, AF_INET6, AF_UNIX as long as they
1105
+ # are SOCK_STREAM.
1106
+ # We support passing AF_UNIX sockets even though we have
1107
+ # a dedicated API for that: create_unix_connection.
1108
+ # Disallowing AF_UNIX in this method, breaks backwards
1109
+ # compatibility.
1110
+ raise ValueError(
1111
+ f'A Stream Socket was expected, got {sock!r}')
1112
+
1113
+ transport, protocol = await self._create_connection_transport(
1114
+ sock, protocol_factory, ssl, server_hostname,
1115
+ ssl_handshake_timeout=ssl_handshake_timeout,
1116
+ ssl_shutdown_timeout=ssl_shutdown_timeout)
1117
+ if self._debug:
1118
+ # Get the socket from the transport because SSL transport closes
1119
+ # the old socket and creates a new SSL socket
1120
+ sock = transport.get_extra_info('socket')
1121
+ logger.debug("%r connected to %s:%r: (%r, %r)",
1122
+ sock, host, port, transport, protocol)
1123
+ return transport, protocol
1124
+
1125
+ async def _create_connection_transport(
1126
+ self, sock, protocol_factory, ssl,
1127
+ server_hostname, server_side=False,
1128
+ ssl_handshake_timeout=None,
1129
+ ssl_shutdown_timeout=None):
1130
+
1131
+ sock.setblocking(False)
1132
+
1133
+ protocol = protocol_factory()
1134
+ waiter = self.create_future()
1135
+ if ssl:
1136
+ sslcontext = None if isinstance(ssl, bool) else ssl
1137
+ transport = self._make_ssl_transport(
1138
+ sock, protocol, sslcontext, waiter,
1139
+ server_side=server_side, server_hostname=server_hostname,
1140
+ ssl_handshake_timeout=ssl_handshake_timeout,
1141
+ ssl_shutdown_timeout=ssl_shutdown_timeout)
1142
+ else:
1143
+ transport = self._make_socket_transport(sock, protocol, waiter)
1144
+
1145
+ try:
1146
+ await waiter
1147
+ except:
1148
+ transport.close()
1149
+ raise
1150
+
1151
+ return transport, protocol
1152
+
1153
+ async def sendfile(self, transport, file, offset=0, count=None,
1154
+ *, fallback=True):
1155
+ """Send a file to transport.
1156
+
1157
+ Return the total number of bytes which were sent.
1158
+
1159
+ The method uses high-performance os.sendfile if available.
1160
+
1161
+ file must be a regular file object opened in binary mode.
1162
+
1163
+ offset tells from where to start reading the file. If specified,
1164
+ count is the total number of bytes to transmit as opposed to
1165
+ sending the file until EOF is reached. File position is updated on
1166
+ return or also in case of error in which case file.tell()
1167
+ can be used to figure out the number of bytes
1168
+ which were sent.
1169
+
1170
+ fallback set to True makes asyncio to manually read and send
1171
+ the file when the platform does not support the sendfile syscall
1172
+ (e.g. Windows or SSL socket on Unix).
1173
+
1174
+ Raise SendfileNotAvailableError if the system does not support
1175
+ sendfile syscall and fallback is False.
1176
+ """
1177
+ if transport.is_closing():
1178
+ raise RuntimeError("Transport is closing")
1179
+ mode = getattr(transport, '_sendfile_compatible',
1180
+ constants._SendfileMode.UNSUPPORTED)
1181
+ if mode is constants._SendfileMode.UNSUPPORTED:
1182
+ raise RuntimeError(
1183
+ f"sendfile is not supported for transport {transport!r}")
1184
+ if mode is constants._SendfileMode.TRY_NATIVE:
1185
+ try:
1186
+ return await self._sendfile_native(transport, file,
1187
+ offset, count)
1188
+ except exceptions.SendfileNotAvailableError as exc:
1189
+ if not fallback:
1190
+ raise
1191
+
1192
+ if not fallback:
1193
+ raise RuntimeError(
1194
+ f"fallback is disabled and native sendfile is not "
1195
+ f"supported for transport {transport!r}")
1196
+
1197
+ return await self._sendfile_fallback(transport, file,
1198
+ offset, count)
1199
+
1200
+ async def _sendfile_native(self, transp, file, offset, count):
1201
+ raise exceptions.SendfileNotAvailableError(
1202
+ "sendfile syscall is not supported")
1203
+
1204
+ async def _sendfile_fallback(self, transp, file, offset, count):
1205
+ if offset:
1206
+ file.seek(offset)
1207
+ blocksize = min(count, 16384) if count else 16384
1208
+ buf = bytearray(blocksize)
1209
+ total_sent = 0
1210
+ proto = _SendfileFallbackProtocol(transp)
1211
+ try:
1212
+ while True:
1213
+ if count:
1214
+ blocksize = min(count - total_sent, blocksize)
1215
+ if blocksize <= 0:
1216
+ return total_sent
1217
+ view = memoryview(buf)[:blocksize]
1218
+ read = await self.run_in_executor(None, file.readinto, view)
1219
+ if not read:
1220
+ return total_sent # EOF
1221
+ await proto.drain()
1222
+ transp.write(view[:read])
1223
+ total_sent += read
1224
+ finally:
1225
+ if total_sent > 0 and hasattr(file, 'seek'):
1226
+ file.seek(offset + total_sent)
1227
+ await proto.restore()
1228
+
1229
+ async def start_tls(self, transport, protocol, sslcontext, *,
1230
+ server_side=False,
1231
+ server_hostname=None,
1232
+ ssl_handshake_timeout=None,
1233
+ ssl_shutdown_timeout=None):
1234
+ """Upgrade transport to TLS.
1235
+
1236
+ Return a new transport that *protocol* should start using
1237
+ immediately.
1238
+ """
1239
+ if ssl is None:
1240
+ raise RuntimeError('Python ssl module is not available')
1241
+
1242
+ if not isinstance(sslcontext, ssl.SSLContext):
1243
+ raise TypeError(
1244
+ f'sslcontext is expected to be an instance of ssl.SSLContext, '
1245
+ f'got {sslcontext!r}')
1246
+
1247
+ if not getattr(transport, '_start_tls_compatible', False):
1248
+ raise TypeError(
1249
+ f'transport {transport!r} is not supported by start_tls()')
1250
+
1251
+ waiter = self.create_future()
1252
+ ssl_protocol = sslproto.SSLProtocol(
1253
+ self, protocol, sslcontext, waiter,
1254
+ server_side, server_hostname,
1255
+ ssl_handshake_timeout=ssl_handshake_timeout,
1256
+ ssl_shutdown_timeout=ssl_shutdown_timeout,
1257
+ call_connection_made=False)
1258
+
1259
+ # Pause early so that "ssl_protocol.data_received()" doesn't
1260
+ # have a chance to get called before "ssl_protocol.connection_made()".
1261
+ transport.pause_reading()
1262
+
1263
+ transport.set_protocol(ssl_protocol)
1264
+ conmade_cb = self.call_soon(ssl_protocol.connection_made, transport)
1265
+ resume_cb = self.call_soon(transport.resume_reading)
1266
+
1267
+ try:
1268
+ await waiter
1269
+ except BaseException:
1270
+ transport.close()
1271
+ conmade_cb.cancel()
1272
+ resume_cb.cancel()
1273
+ raise
1274
+
1275
+ return ssl_protocol._app_transport
1276
+
1277
+ async def create_datagram_endpoint(self, protocol_factory,
1278
+ local_addr=None, remote_addr=None, *,
1279
+ family=0, proto=0, flags=0,
1280
+ reuse_port=None,
1281
+ allow_broadcast=None, sock=None):
1282
+ """Create datagram connection."""
1283
+ if sock is not None:
1284
+ if sock.type == socket.SOCK_STREAM:
1285
+ raise ValueError(
1286
+ f'A datagram socket was expected, got {sock!r}')
1287
+ if (local_addr or remote_addr or
1288
+ family or proto or flags or
1289
+ reuse_port or allow_broadcast):
1290
+ # show the problematic kwargs in exception msg
1291
+ opts = dict(local_addr=local_addr, remote_addr=remote_addr,
1292
+ family=family, proto=proto, flags=flags,
1293
+ reuse_port=reuse_port,
1294
+ allow_broadcast=allow_broadcast)
1295
+ problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
1296
+ raise ValueError(
1297
+ f'socket modifier keyword arguments can not be used '
1298
+ f'when sock is specified. ({problems})')
1299
+ sock.setblocking(False)
1300
+ r_addr = None
1301
+ else:
1302
+ if not (local_addr or remote_addr):
1303
+ if family == 0:
1304
+ raise ValueError('unexpected address family')
1305
+ addr_pairs_info = (((family, proto), (None, None)),)
1306
+ elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
1307
+ for addr in (local_addr, remote_addr):
1308
+ if addr is not None and not isinstance(addr, str):
1309
+ raise TypeError('string is expected')
1310
+
1311
+ if local_addr and local_addr[0] not in (0, '\x00'):
1312
+ try:
1313
+ if stat.S_ISSOCK(os.stat(local_addr).st_mode):
1314
+ os.remove(local_addr)
1315
+ except FileNotFoundError:
1316
+ pass
1317
+ except OSError as err:
1318
+ # Directory may have permissions only to create socket.
1319
+ logger.error('Unable to check or remove stale UNIX '
1320
+ 'socket %r: %r',
1321
+ local_addr, err)
1322
+
1323
+ addr_pairs_info = (((family, proto),
1324
+ (local_addr, remote_addr)), )
1325
+ else:
1326
+ # join address by (family, protocol)
1327
+ addr_infos = {} # Using order preserving dict
1328
+ for idx, addr in ((0, local_addr), (1, remote_addr)):
1329
+ if addr is not None:
1330
+ if not (isinstance(addr, tuple) and len(addr) == 2):
1331
+ raise TypeError('2-tuple is expected')
1332
+
1333
+ infos = await self._ensure_resolved(
1334
+ addr, family=family, type=socket.SOCK_DGRAM,
1335
+ proto=proto, flags=flags, loop=self)
1336
+ if not infos:
1337
+ raise OSError('getaddrinfo() returned empty list')
1338
+
1339
+ for fam, _, pro, _, address in infos:
1340
+ key = (fam, pro)
1341
+ if key not in addr_infos:
1342
+ addr_infos[key] = [None, None]
1343
+ addr_infos[key][idx] = address
1344
+
1345
+ # each addr has to have info for each (family, proto) pair
1346
+ addr_pairs_info = [
1347
+ (key, addr_pair) for key, addr_pair in addr_infos.items()
1348
+ if not ((local_addr and addr_pair[0] is None) or
1349
+ (remote_addr and addr_pair[1] is None))]
1350
+
1351
+ if not addr_pairs_info:
1352
+ raise ValueError('can not get address information')
1353
+
1354
+ exceptions = []
1355
+
1356
+ for ((family, proto),
1357
+ (local_address, remote_address)) in addr_pairs_info:
1358
+ sock = None
1359
+ r_addr = None
1360
+ try:
1361
+ sock = socket.socket(
1362
+ family=family, type=socket.SOCK_DGRAM, proto=proto)
1363
+ if reuse_port:
1364
+ _set_reuseport(sock)
1365
+ if allow_broadcast:
1366
+ sock.setsockopt(
1367
+ socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
1368
+ sock.setblocking(False)
1369
+
1370
+ if local_addr:
1371
+ sock.bind(local_address)
1372
+ if remote_addr:
1373
+ if not allow_broadcast:
1374
+ await self.sock_connect(sock, remote_address)
1375
+ r_addr = remote_address
1376
+ except OSError as exc:
1377
+ if sock is not None:
1378
+ sock.close()
1379
+ exceptions.append(exc)
1380
+ except:
1381
+ if sock is not None:
1382
+ sock.close()
1383
+ raise
1384
+ else:
1385
+ break
1386
+ else:
1387
+ raise exceptions[0]
1388
+
1389
+ protocol = protocol_factory()
1390
+ waiter = self.create_future()
1391
+ transport = self._make_datagram_transport(
1392
+ sock, protocol, r_addr, waiter)
1393
+ if self._debug:
1394
+ if local_addr:
1395
+ logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
1396
+ "created: (%r, %r)",
1397
+ local_addr, remote_addr, transport, protocol)
1398
+ else:
1399
+ logger.debug("Datagram endpoint remote_addr=%r created: "
1400
+ "(%r, %r)",
1401
+ remote_addr, transport, protocol)
1402
+
1403
+ try:
1404
+ await waiter
1405
+ except:
1406
+ transport.close()
1407
+ raise
1408
+
1409
+ return transport, protocol
1410
+
1411
+ async def _ensure_resolved(self, address, *,
1412
+ family=0, type=socket.SOCK_STREAM,
1413
+ proto=0, flags=0, loop):
1414
+ host, port = address[:2]
1415
+ info = _ipaddr_info(host, port, family, type, proto, *address[2:])
1416
+ if info is not None:
1417
+ # "host" is already a resolved IP.
1418
+ return [info]
1419
+ else:
1420
+ return await loop.getaddrinfo(host, port, family=family, type=type,
1421
+ proto=proto, flags=flags)
1422
+
1423
+ async def _create_server_getaddrinfo(self, host, port, family, flags):
1424
+ infos = await self._ensure_resolved((host, port), family=family,
1425
+ type=socket.SOCK_STREAM,
1426
+ flags=flags, loop=self)
1427
+ if not infos:
1428
+ raise OSError(f'getaddrinfo({host!r}) returned empty list')
1429
+ return infos
1430
+
1431
+ async def create_server(
1432
+ self, protocol_factory, host=None, port=None,
1433
+ *,
1434
+ family=socket.AF_UNSPEC,
1435
+ flags=socket.AI_PASSIVE,
1436
+ sock=None,
1437
+ backlog=100,
1438
+ ssl=None,
1439
+ reuse_address=None,
1440
+ reuse_port=None,
1441
+ ssl_handshake_timeout=None,
1442
+ ssl_shutdown_timeout=None,
1443
+ start_serving=True):
1444
+ """Create a TCP server.
1445
+
1446
+ The host parameter can be a string, in that case the TCP server is
1447
+ bound to host and port.
1448
+
1449
+ The host parameter can also be a sequence of strings and in that case
1450
+ the TCP server is bound to all hosts of the sequence. If a host
1451
+ appears multiple times (possibly indirectly e.g. when hostnames
1452
+ resolve to the same IP address), the server is only bound once to that
1453
+ host.
1454
+
1455
+ Return a Server object which can be used to stop the service.
1456
+
1457
+ This method is a coroutine.
1458
+ """
1459
+ if isinstance(ssl, bool):
1460
+ raise TypeError('ssl argument must be an SSLContext or None')
1461
+
1462
+ if ssl_handshake_timeout is not None and ssl is None:
1463
+ raise ValueError(
1464
+ 'ssl_handshake_timeout is only meaningful with ssl')
1465
+
1466
+ if ssl_shutdown_timeout is not None and ssl is None:
1467
+ raise ValueError(
1468
+ 'ssl_shutdown_timeout is only meaningful with ssl')
1469
+
1470
+ if sock is not None:
1471
+ _check_ssl_socket(sock)
1472
+
1473
+ if host is not None or port is not None:
1474
+ if sock is not None:
1475
+ raise ValueError(
1476
+ 'host/port and sock can not be specified at the same time')
1477
+
1478
+ if reuse_address is None:
1479
+ reuse_address = os.name == "posix" and sys.platform != "cygwin"
1480
+ sockets = []
1481
+ if host == '':
1482
+ hosts = [None]
1483
+ elif (isinstance(host, str) or
1484
+ not isinstance(host, collections.abc.Iterable)):
1485
+ hosts = [host]
1486
+ else:
1487
+ hosts = host
1488
+
1489
+ fs = [self._create_server_getaddrinfo(host, port, family=family,
1490
+ flags=flags)
1491
+ for host in hosts]
1492
+ infos = await tasks.gather(*fs)
1493
+ infos = set(itertools.chain.from_iterable(infos))
1494
+
1495
+ completed = False
1496
+ try:
1497
+ for res in infos:
1498
+ af, socktype, proto, canonname, sa = res
1499
+ try:
1500
+ sock = socket.socket(af, socktype, proto)
1501
+ except socket.error:
1502
+ # Assume it's a bad family/type/protocol combination.
1503
+ if self._debug:
1504
+ logger.warning('create_server() failed to create '
1505
+ 'socket.socket(%r, %r, %r)',
1506
+ af, socktype, proto, exc_info=True)
1507
+ continue
1508
+ sockets.append(sock)
1509
+ if reuse_address:
1510
+ sock.setsockopt(
1511
+ socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1512
+ if reuse_port:
1513
+ _set_reuseport(sock)
1514
+ # Disable IPv4/IPv6 dual stack support (enabled by
1515
+ # default on Linux) which makes a single socket
1516
+ # listen on both address families.
1517
+ if (_HAS_IPv6 and
1518
+ af == socket.AF_INET6 and
1519
+ hasattr(socket, 'IPPROTO_IPV6')):
1520
+ sock.setsockopt(socket.IPPROTO_IPV6,
1521
+ socket.IPV6_V6ONLY,
1522
+ True)
1523
+ try:
1524
+ sock.bind(sa)
1525
+ except OSError as err:
1526
+ msg = ('error while attempting '
1527
+ 'to bind on address %r: %s'
1528
+ % (sa, err.strerror.lower()))
1529
+ if err.errno == errno.EADDRNOTAVAIL:
1530
+ # Assume the family is not enabled (bpo-30945)
1531
+ sockets.pop()
1532
+ sock.close()
1533
+ if self._debug:
1534
+ logger.warning(msg)
1535
+ continue
1536
+ raise OSError(err.errno, msg) from None
1537
+
1538
+ if not sockets:
1539
+ raise OSError('could not bind on any address out of %r'
1540
+ % ([info[4] for info in infos],))
1541
+
1542
+ completed = True
1543
+ finally:
1544
+ if not completed:
1545
+ for sock in sockets:
1546
+ sock.close()
1547
+ else:
1548
+ if sock is None:
1549
+ raise ValueError('Neither host/port nor sock were specified')
1550
+ if sock.type != socket.SOCK_STREAM:
1551
+ raise ValueError(f'A Stream Socket was expected, got {sock!r}')
1552
+ sockets = [sock]
1553
+
1554
+ for sock in sockets:
1555
+ sock.setblocking(False)
1556
+
1557
+ server = Server(self, sockets, protocol_factory,
1558
+ ssl, backlog, ssl_handshake_timeout,
1559
+ ssl_shutdown_timeout)
1560
+ if start_serving:
1561
+ server._start_serving()
1562
+ # Skip one loop iteration so that all 'loop.add_reader'
1563
+ # go through.
1564
+ await tasks.sleep(0)
1565
+
1566
+ if self._debug:
1567
+ logger.info("%r is serving", server)
1568
+ return server
1569
+
1570
+ async def connect_accepted_socket(
1571
+ self, protocol_factory, sock,
1572
+ *, ssl=None,
1573
+ ssl_handshake_timeout=None,
1574
+ ssl_shutdown_timeout=None):
1575
+ if sock.type != socket.SOCK_STREAM:
1576
+ raise ValueError(f'A Stream Socket was expected, got {sock!r}')
1577
+
1578
+ if ssl_handshake_timeout is not None and not ssl:
1579
+ raise ValueError(
1580
+ 'ssl_handshake_timeout is only meaningful with ssl')
1581
+
1582
+ if ssl_shutdown_timeout is not None and not ssl:
1583
+ raise ValueError(
1584
+ 'ssl_shutdown_timeout is only meaningful with ssl')
1585
+
1586
+ if sock is not None:
1587
+ _check_ssl_socket(sock)
1588
+
1589
+ transport, protocol = await self._create_connection_transport(
1590
+ sock, protocol_factory, ssl, '', server_side=True,
1591
+ ssl_handshake_timeout=ssl_handshake_timeout,
1592
+ ssl_shutdown_timeout=ssl_shutdown_timeout)
1593
+ if self._debug:
1594
+ # Get the socket from the transport because SSL transport closes
1595
+ # the old socket and creates a new SSL socket
1596
+ sock = transport.get_extra_info('socket')
1597
+ logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1598
+ return transport, protocol
1599
+
1600
+ async def connect_read_pipe(self, protocol_factory, pipe):
1601
+ protocol = protocol_factory()
1602
+ waiter = self.create_future()
1603
+ transport = self._make_read_pipe_transport(pipe, protocol, waiter)
1604
+
1605
+ try:
1606
+ await waiter
1607
+ except:
1608
+ transport.close()
1609
+ raise
1610
+
1611
+ if self._debug:
1612
+ logger.debug('Read pipe %r connected: (%r, %r)',
1613
+ pipe.fileno(), transport, protocol)
1614
+ return transport, protocol
1615
+
1616
+ async def connect_write_pipe(self, protocol_factory, pipe):
1617
+ protocol = protocol_factory()
1618
+ waiter = self.create_future()
1619
+ transport = self._make_write_pipe_transport(pipe, protocol, waiter)
1620
+
1621
+ try:
1622
+ await waiter
1623
+ except:
1624
+ transport.close()
1625
+ raise
1626
+
1627
+ if self._debug:
1628
+ logger.debug('Write pipe %r connected: (%r, %r)',
1629
+ pipe.fileno(), transport, protocol)
1630
+ return transport, protocol
1631
+
1632
+ def _log_subprocess(self, msg, stdin, stdout, stderr):
1633
+ info = [msg]
1634
+ if stdin is not None:
1635
+ info.append(f'stdin={_format_pipe(stdin)}')
1636
+ if stdout is not None and stderr == subprocess.STDOUT:
1637
+ info.append(f'stdout=stderr={_format_pipe(stdout)}')
1638
+ else:
1639
+ if stdout is not None:
1640
+ info.append(f'stdout={_format_pipe(stdout)}')
1641
+ if stderr is not None:
1642
+ info.append(f'stderr={_format_pipe(stderr)}')
1643
+ logger.debug(' '.join(info))
1644
+
1645
+ async def subprocess_shell(self, protocol_factory, cmd, *,
1646
+ stdin=subprocess.PIPE,
1647
+ stdout=subprocess.PIPE,
1648
+ stderr=subprocess.PIPE,
1649
+ universal_newlines=False,
1650
+ shell=True, bufsize=0,
1651
+ encoding=None, errors=None, text=None,
1652
+ **kwargs):
1653
+ if not isinstance(cmd, (bytes, str)):
1654
+ raise ValueError("cmd must be a string")
1655
+ if universal_newlines:
1656
+ raise ValueError("universal_newlines must be False")
1657
+ if not shell:
1658
+ raise ValueError("shell must be True")
1659
+ if bufsize != 0:
1660
+ raise ValueError("bufsize must be 0")
1661
+ if text:
1662
+ raise ValueError("text must be False")
1663
+ if encoding is not None:
1664
+ raise ValueError("encoding must be None")
1665
+ if errors is not None:
1666
+ raise ValueError("errors must be None")
1667
+
1668
+ protocol = protocol_factory()
1669
+ debug_log = None
1670
+ if self._debug:
1671
+ # don't log parameters: they may contain sensitive information
1672
+ # (password) and may be too long
1673
+ debug_log = 'run shell command %r' % cmd
1674
+ self._log_subprocess(debug_log, stdin, stdout, stderr)
1675
+ transport = await self._make_subprocess_transport(
1676
+ protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
1677
+ if self._debug and debug_log is not None:
1678
+ logger.info('%s: %r', debug_log, transport)
1679
+ return transport, protocol
1680
+
1681
+ async def subprocess_exec(self, protocol_factory, program, *args,
1682
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1683
+ stderr=subprocess.PIPE, universal_newlines=False,
1684
+ shell=False, bufsize=0,
1685
+ encoding=None, errors=None, text=None,
1686
+ **kwargs):
1687
+ if universal_newlines:
1688
+ raise ValueError("universal_newlines must be False")
1689
+ if shell:
1690
+ raise ValueError("shell must be False")
1691
+ if bufsize != 0:
1692
+ raise ValueError("bufsize must be 0")
1693
+ if text:
1694
+ raise ValueError("text must be False")
1695
+ if encoding is not None:
1696
+ raise ValueError("encoding must be None")
1697
+ if errors is not None:
1698
+ raise ValueError("errors must be None")
1699
+
1700
+ popen_args = (program,) + args
1701
+ protocol = protocol_factory()
1702
+ debug_log = None
1703
+ if self._debug:
1704
+ # don't log parameters: they may contain sensitive information
1705
+ # (password) and may be too long
1706
+ debug_log = f'execute program {program!r}'
1707
+ self._log_subprocess(debug_log, stdin, stdout, stderr)
1708
+ transport = await self._make_subprocess_transport(
1709
+ protocol, popen_args, False, stdin, stdout, stderr,
1710
+ bufsize, **kwargs)
1711
+ if self._debug and debug_log is not None:
1712
+ logger.info('%s: %r', debug_log, transport)
1713
+ return transport, protocol
1714
+
1715
+ def get_exception_handler(self):
1716
+ """Return an exception handler, or None if the default one is in use.
1717
+ """
1718
+ return self._exception_handler
1719
+
1720
+ def set_exception_handler(self, handler):
1721
+ """Set handler as the new event loop exception handler.
1722
+
1723
+ If handler is None, the default exception handler will
1724
+ be set.
1725
+
1726
+ If handler is a callable object, it should have a
1727
+ signature matching '(loop, context)', where 'loop'
1728
+ will be a reference to the active event loop, 'context'
1729
+ will be a dict object (see `call_exception_handler()`
1730
+ documentation for details about context).
1731
+ """
1732
+ if handler is not None and not callable(handler):
1733
+ raise TypeError(f'A callable object or None is expected, '
1734
+ f'got {handler!r}')
1735
+ self._exception_handler = handler
1736
+
1737
+ def default_exception_handler(self, context):
1738
+ """Default exception handler.
1739
+
1740
+ This is called when an exception occurs and no exception
1741
+ handler is set, and can be called by a custom exception
1742
+ handler that wants to defer to the default behavior.
1743
+
1744
+ This default handler logs the error message and other
1745
+ context-dependent information. In debug mode, a truncated
1746
+ stack trace is also appended showing where the given object
1747
+ (e.g. a handle or future or task) was created, if any.
1748
+
1749
+ The context parameter has the same meaning as in
1750
+ `call_exception_handler()`.
1751
+ """
1752
+ message = context.get('message')
1753
+ if not message:
1754
+ message = 'Unhandled exception in event loop'
1755
+
1756
+ exception = context.get('exception')
1757
+ if exception is not None:
1758
+ exc_info = (type(exception), exception, exception.__traceback__)
1759
+ else:
1760
+ exc_info = False
1761
+
1762
+ if ('source_traceback' not in context and
1763
+ self._current_handle is not None and
1764
+ self._current_handle._source_traceback):
1765
+ context['handle_traceback'] = \
1766
+ self._current_handle._source_traceback
1767
+
1768
+ log_lines = [message]
1769
+ for key in sorted(context):
1770
+ if key in {'message', 'exception'}:
1771
+ continue
1772
+ value = context[key]
1773
+ if key == 'source_traceback':
1774
+ tb = ''.join(traceback.format_list(value))
1775
+ value = 'Object created at (most recent call last):\n'
1776
+ value += tb.rstrip()
1777
+ elif key == 'handle_traceback':
1778
+ tb = ''.join(traceback.format_list(value))
1779
+ value = 'Handle created at (most recent call last):\n'
1780
+ value += tb.rstrip()
1781
+ else:
1782
+ value = repr(value)
1783
+ log_lines.append(f'{key}: {value}')
1784
+
1785
+ logger.error('\n'.join(log_lines), exc_info=exc_info)
1786
+
1787
+ def call_exception_handler(self, context):
1788
+ """Call the current event loop's exception handler.
1789
+
1790
+ The context argument is a dict containing the following keys:
1791
+
1792
+ - 'message': Error message;
1793
+ - 'exception' (optional): Exception object;
1794
+ - 'future' (optional): Future instance;
1795
+ - 'task' (optional): Task instance;
1796
+ - 'handle' (optional): Handle instance;
1797
+ - 'protocol' (optional): Protocol instance;
1798
+ - 'transport' (optional): Transport instance;
1799
+ - 'socket' (optional): Socket instance;
1800
+ - 'asyncgen' (optional): Asynchronous generator that caused
1801
+ the exception.
1802
+
1803
+ New keys maybe introduced in the future.
1804
+
1805
+ Note: do not overload this method in an event loop subclass.
1806
+ For custom exception handling, use the
1807
+ `set_exception_handler()` method.
1808
+ """
1809
+ if self._exception_handler is None:
1810
+ try:
1811
+ self.default_exception_handler(context)
1812
+ except (SystemExit, KeyboardInterrupt):
1813
+ raise
1814
+ except BaseException:
1815
+ # Second protection layer for unexpected errors
1816
+ # in the default implementation, as well as for subclassed
1817
+ # event loops with overloaded "default_exception_handler".
1818
+ logger.error('Exception in default exception handler',
1819
+ exc_info=True)
1820
+ else:
1821
+ try:
1822
+ self._exception_handler(self, context)
1823
+ except (SystemExit, KeyboardInterrupt):
1824
+ raise
1825
+ except BaseException as exc:
1826
+ # Exception in the user set custom exception handler.
1827
+ try:
1828
+ # Let's try default handler.
1829
+ self.default_exception_handler({
1830
+ 'message': 'Unhandled error in exception handler',
1831
+ 'exception': exc,
1832
+ 'context': context,
1833
+ })
1834
+ except (SystemExit, KeyboardInterrupt):
1835
+ raise
1836
+ except BaseException:
1837
+ # Guard 'default_exception_handler' in case it is
1838
+ # overloaded.
1839
+ logger.error('Exception in default exception handler '
1840
+ 'while handling an unexpected error '
1841
+ 'in custom exception handler',
1842
+ exc_info=True)
1843
+
1844
+ def _add_callback(self, handle):
1845
+ """Add a Handle to _ready."""
1846
+ if not handle._cancelled:
1847
+ self._ready.append(handle)
1848
+
1849
+ def _add_callback_signalsafe(self, handle):
1850
+ """Like _add_callback() but called from a signal handler."""
1851
+ self._add_callback(handle)
1852
+ self._write_to_self()
1853
+
1854
+ def _timer_handle_cancelled(self, handle):
1855
+ """Notification that a TimerHandle has been cancelled."""
1856
+ if handle._scheduled:
1857
+ self._timer_cancelled_count += 1
1858
+
1859
+ def _run_once(self):
1860
+ """Run one full iteration of the event loop.
1861
+
1862
+ This calls all currently ready callbacks, polls for I/O,
1863
+ schedules the resulting callbacks, and finally schedules
1864
+ 'call_later' callbacks.
1865
+ """
1866
+
1867
+ sched_count = len(self._scheduled)
1868
+ if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1869
+ self._timer_cancelled_count / sched_count >
1870
+ _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
1871
+ # Remove delayed calls that were cancelled if their number
1872
+ # is too high
1873
+ new_scheduled = []
1874
+ for handle in self._scheduled:
1875
+ if handle._cancelled:
1876
+ handle._scheduled = False
1877
+ else:
1878
+ new_scheduled.append(handle)
1879
+
1880
+ heapq.heapify(new_scheduled)
1881
+ self._scheduled = new_scheduled
1882
+ self._timer_cancelled_count = 0
1883
+ else:
1884
+ # Remove delayed calls that were cancelled from head of queue.
1885
+ while self._scheduled and self._scheduled[0]._cancelled:
1886
+ self._timer_cancelled_count -= 1
1887
+ handle = heapq.heappop(self._scheduled)
1888
+ handle._scheduled = False
1889
+
1890
+ timeout = None
1891
+ if self._ready or self._stopping:
1892
+ timeout = 0
1893
+ elif self._scheduled:
1894
+ # Compute the desired timeout.
1895
+ when = self._scheduled[0]._when
1896
+ timeout = min(max(0, when - self.time()), MAXIMUM_SELECT_TIMEOUT)
1897
+
1898
+ event_list = self._selector.select(timeout)
1899
+ self._process_events(event_list)
1900
+ # Needed to break cycles when an exception occurs.
1901
+ event_list = None
1902
+
1903
+ # Handle 'later' callbacks that are ready.
1904
+ end_time = self.time() + self._clock_resolution
1905
+ while self._scheduled:
1906
+ handle = self._scheduled[0]
1907
+ if handle._when >= end_time:
1908
+ break
1909
+ handle = heapq.heappop(self._scheduled)
1910
+ handle._scheduled = False
1911
+ self._ready.append(handle)
1912
+
1913
+ # This is the only place where callbacks are actually *called*.
1914
+ # All other places just add them to ready.
1915
+ # Note: We run all currently scheduled callbacks, but not any
1916
+ # callbacks scheduled by callbacks run this time around --
1917
+ # they will be run the next time (after another I/O poll).
1918
+ # Use an idiom that is thread-safe without using locks.
1919
+ ntodo = len(self._ready)
1920
+ for i in range(ntodo):
1921
+ handle = self._ready.popleft()
1922
+ if handle._cancelled:
1923
+ continue
1924
+ if self._debug:
1925
+ try:
1926
+ self._current_handle = handle
1927
+ t0 = self.time()
1928
+ handle._run()
1929
+ dt = self.time() - t0
1930
+ if dt >= self.slow_callback_duration:
1931
+ logger.warning('Executing %s took %.3f seconds',
1932
+ _format_handle(handle), dt)
1933
+ finally:
1934
+ self._current_handle = None
1935
+ else:
1936
+ handle._run()
1937
+ handle = None # Needed to break cycles when an exception occurs.
1938
+
1939
+ def _set_coroutine_origin_tracking(self, enabled):
1940
+ if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
1941
+ return
1942
+
1943
+ if enabled:
1944
+ self._coroutine_origin_tracking_saved_depth = (
1945
+ sys.get_coroutine_origin_tracking_depth())
1946
+ sys.set_coroutine_origin_tracking_depth(
1947
+ constants.DEBUG_STACK_DEPTH)
1948
+ else:
1949
+ sys.set_coroutine_origin_tracking_depth(
1950
+ self._coroutine_origin_tracking_saved_depth)
1951
+
1952
+ self._coroutine_origin_tracking_enabled = enabled
1953
+
1954
+ def get_debug(self):
1955
+ return self._debug
1956
+
1957
+ def set_debug(self, enabled):
1958
+ self._debug = enabled
1959
+
1960
+ if self.is_running():
1961
+ self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/base_futures.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ()
2
+
3
+ import reprlib
4
+ from _thread import get_ident
5
+
6
+ from . import format_helpers
7
+
8
+ # States for Future.
9
+ _PENDING = 'PENDING'
10
+ _CANCELLED = 'CANCELLED'
11
+ _FINISHED = 'FINISHED'
12
+
13
+
14
+ def isfuture(obj):
15
+ """Check for a Future.
16
+
17
+ This returns True when obj is a Future instance or is advertising
18
+ itself as duck-type compatible by setting _asyncio_future_blocking.
19
+ See comment in Future for more details.
20
+ """
21
+ return (hasattr(obj.__class__, '_asyncio_future_blocking') and
22
+ obj._asyncio_future_blocking is not None)
23
+
24
+
25
+ def _format_callbacks(cb):
26
+ """helper function for Future.__repr__"""
27
+ size = len(cb)
28
+ if not size:
29
+ cb = ''
30
+
31
+ def format_cb(callback):
32
+ return format_helpers._format_callback_source(callback, ())
33
+
34
+ if size == 1:
35
+ cb = format_cb(cb[0][0])
36
+ elif size == 2:
37
+ cb = '{}, {}'.format(format_cb(cb[0][0]), format_cb(cb[1][0]))
38
+ elif size > 2:
39
+ cb = '{}, <{} more>, {}'.format(format_cb(cb[0][0]),
40
+ size - 2,
41
+ format_cb(cb[-1][0]))
42
+ return f'cb=[{cb}]'
43
+
44
+
45
+ def _future_repr_info(future):
46
+ # (Future) -> str
47
+ """helper function for Future.__repr__"""
48
+ info = [future._state.lower()]
49
+ if future._state == _FINISHED:
50
+ if future._exception is not None:
51
+ info.append(f'exception={future._exception!r}')
52
+ else:
53
+ # use reprlib to limit the length of the output, especially
54
+ # for very long strings
55
+ result = reprlib.repr(future._result)
56
+ info.append(f'result={result}')
57
+ if future._callbacks:
58
+ info.append(_format_callbacks(future._callbacks))
59
+ if future._source_traceback:
60
+ frame = future._source_traceback[-1]
61
+ info.append(f'created at {frame[0]}:{frame[1]}')
62
+ return info
63
+
64
+
65
+ @reprlib.recursive_repr()
66
+ def _future_repr(future):
67
+ info = ' '.join(_future_repr_info(future))
68
+ return f'<{future.__class__.__name__} {info}>'
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/base_subprocess.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import subprocess
3
+ import warnings
4
+
5
+ from . import protocols
6
+ from . import transports
7
+ from .log import logger
8
+
9
+
10
+ class BaseSubprocessTransport(transports.SubprocessTransport):
11
+
12
+ def __init__(self, loop, protocol, args, shell,
13
+ stdin, stdout, stderr, bufsize,
14
+ waiter=None, extra=None, **kwargs):
15
+ super().__init__(extra)
16
+ self._closed = False
17
+ self._protocol = protocol
18
+ self._loop = loop
19
+ self._proc = None
20
+ self._pid = None
21
+ self._returncode = None
22
+ self._exit_waiters = []
23
+ self._pending_calls = collections.deque()
24
+ self._pipes = {}
25
+ self._finished = False
26
+
27
+ if stdin == subprocess.PIPE:
28
+ self._pipes[0] = None
29
+ if stdout == subprocess.PIPE:
30
+ self._pipes[1] = None
31
+ if stderr == subprocess.PIPE:
32
+ self._pipes[2] = None
33
+
34
+ # Create the child process: set the _proc attribute
35
+ try:
36
+ self._start(args=args, shell=shell, stdin=stdin, stdout=stdout,
37
+ stderr=stderr, bufsize=bufsize, **kwargs)
38
+ except:
39
+ self.close()
40
+ raise
41
+
42
+ self._pid = self._proc.pid
43
+ self._extra['subprocess'] = self._proc
44
+
45
+ if self._loop.get_debug():
46
+ if isinstance(args, (bytes, str)):
47
+ program = args
48
+ else:
49
+ program = args[0]
50
+ logger.debug('process %r created: pid %s',
51
+ program, self._pid)
52
+
53
+ self._loop.create_task(self._connect_pipes(waiter))
54
+
55
+ def __repr__(self):
56
+ info = [self.__class__.__name__]
57
+ if self._closed:
58
+ info.append('closed')
59
+ if self._pid is not None:
60
+ info.append(f'pid={self._pid}')
61
+ if self._returncode is not None:
62
+ info.append(f'returncode={self._returncode}')
63
+ elif self._pid is not None:
64
+ info.append('running')
65
+ else:
66
+ info.append('not started')
67
+
68
+ stdin = self._pipes.get(0)
69
+ if stdin is not None:
70
+ info.append(f'stdin={stdin.pipe}')
71
+
72
+ stdout = self._pipes.get(1)
73
+ stderr = self._pipes.get(2)
74
+ if stdout is not None and stderr is stdout:
75
+ info.append(f'stdout=stderr={stdout.pipe}')
76
+ else:
77
+ if stdout is not None:
78
+ info.append(f'stdout={stdout.pipe}')
79
+ if stderr is not None:
80
+ info.append(f'stderr={stderr.pipe}')
81
+
82
+ return '<{}>'.format(' '.join(info))
83
+
84
+ def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
85
+ raise NotImplementedError
86
+
87
+ def set_protocol(self, protocol):
88
+ self._protocol = protocol
89
+
90
+ def get_protocol(self):
91
+ return self._protocol
92
+
93
+ def is_closing(self):
94
+ return self._closed
95
+
96
+ def close(self):
97
+ if self._closed:
98
+ return
99
+ self._closed = True
100
+
101
+ for proto in self._pipes.values():
102
+ if proto is None:
103
+ continue
104
+ proto.pipe.close()
105
+
106
+ if (self._proc is not None and
107
+ # has the child process finished?
108
+ self._returncode is None and
109
+ # the child process has finished, but the
110
+ # transport hasn't been notified yet?
111
+ self._proc.poll() is None):
112
+
113
+ if self._loop.get_debug():
114
+ logger.warning('Close running child process: kill %r', self)
115
+
116
+ try:
117
+ self._proc.kill()
118
+ except ProcessLookupError:
119
+ pass
120
+
121
+ # Don't clear the _proc reference yet: _post_init() may still run
122
+
123
+ def __del__(self, _warn=warnings.warn):
124
+ if not self._closed:
125
+ _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
126
+ self.close()
127
+
128
+ def get_pid(self):
129
+ return self._pid
130
+
131
+ def get_returncode(self):
132
+ return self._returncode
133
+
134
+ def get_pipe_transport(self, fd):
135
+ if fd in self._pipes:
136
+ return self._pipes[fd].pipe
137
+ else:
138
+ return None
139
+
140
+ def _check_proc(self):
141
+ if self._proc is None:
142
+ raise ProcessLookupError()
143
+
144
+ def send_signal(self, signal):
145
+ self._check_proc()
146
+ self._proc.send_signal(signal)
147
+
148
+ def terminate(self):
149
+ self._check_proc()
150
+ self._proc.terminate()
151
+
152
+ def kill(self):
153
+ self._check_proc()
154
+ self._proc.kill()
155
+
156
+ async def _connect_pipes(self, waiter):
157
+ try:
158
+ proc = self._proc
159
+ loop = self._loop
160
+
161
+ if proc.stdin is not None:
162
+ _, pipe = await loop.connect_write_pipe(
163
+ lambda: WriteSubprocessPipeProto(self, 0),
164
+ proc.stdin)
165
+ self._pipes[0] = pipe
166
+
167
+ if proc.stdout is not None:
168
+ _, pipe = await loop.connect_read_pipe(
169
+ lambda: ReadSubprocessPipeProto(self, 1),
170
+ proc.stdout)
171
+ self._pipes[1] = pipe
172
+
173
+ if proc.stderr is not None:
174
+ _, pipe = await loop.connect_read_pipe(
175
+ lambda: ReadSubprocessPipeProto(self, 2),
176
+ proc.stderr)
177
+ self._pipes[2] = pipe
178
+
179
+ assert self._pending_calls is not None
180
+
181
+ loop.call_soon(self._protocol.connection_made, self)
182
+ for callback, data in self._pending_calls:
183
+ loop.call_soon(callback, *data)
184
+ self._pending_calls = None
185
+ except (SystemExit, KeyboardInterrupt):
186
+ raise
187
+ except BaseException as exc:
188
+ if waiter is not None and not waiter.cancelled():
189
+ waiter.set_exception(exc)
190
+ else:
191
+ if waiter is not None and not waiter.cancelled():
192
+ waiter.set_result(None)
193
+
194
+ def _call(self, cb, *data):
195
+ if self._pending_calls is not None:
196
+ self._pending_calls.append((cb, data))
197
+ else:
198
+ self._loop.call_soon(cb, *data)
199
+
200
+ def _pipe_connection_lost(self, fd, exc):
201
+ self._call(self._protocol.pipe_connection_lost, fd, exc)
202
+ self._try_finish()
203
+
204
+ def _pipe_data_received(self, fd, data):
205
+ self._call(self._protocol.pipe_data_received, fd, data)
206
+
207
+ def _process_exited(self, returncode):
208
+ assert returncode is not None, returncode
209
+ assert self._returncode is None, self._returncode
210
+ if self._loop.get_debug():
211
+ logger.info('%r exited with return code %r', self, returncode)
212
+ self._returncode = returncode
213
+ if self._proc.returncode is None:
214
+ # asyncio uses a child watcher: copy the status into the Popen
215
+ # object. On Python 3.6, it is required to avoid a ResourceWarning.
216
+ self._proc.returncode = returncode
217
+ self._call(self._protocol.process_exited)
218
+
219
+ self._try_finish()
220
+
221
+ async def _wait(self):
222
+ """Wait until the process exit and return the process return code.
223
+
224
+ This method is a coroutine."""
225
+ if self._returncode is not None:
226
+ return self._returncode
227
+
228
+ waiter = self._loop.create_future()
229
+ self._exit_waiters.append(waiter)
230
+ return await waiter
231
+
232
+ def _try_finish(self):
233
+ assert not self._finished
234
+ if self._returncode is None:
235
+ return
236
+ if all(p is not None and p.disconnected
237
+ for p in self._pipes.values()):
238
+ self._finished = True
239
+ self._call(self._call_connection_lost, None)
240
+
241
+ def _call_connection_lost(self, exc):
242
+ try:
243
+ self._protocol.connection_lost(exc)
244
+ finally:
245
+ # wake up futures waiting for wait()
246
+ for waiter in self._exit_waiters:
247
+ if not waiter.cancelled():
248
+ waiter.set_result(self._returncode)
249
+ self._exit_waiters = None
250
+ self._loop = None
251
+ self._proc = None
252
+ self._protocol = None
253
+
254
+
255
+ class WriteSubprocessPipeProto(protocols.BaseProtocol):
256
+
257
+ def __init__(self, proc, fd):
258
+ self.proc = proc
259
+ self.fd = fd
260
+ self.pipe = None
261
+ self.disconnected = False
262
+
263
+ def connection_made(self, transport):
264
+ self.pipe = transport
265
+
266
+ def __repr__(self):
267
+ return f'<{self.__class__.__name__} fd={self.fd} pipe={self.pipe!r}>'
268
+
269
+ def connection_lost(self, exc):
270
+ self.disconnected = True
271
+ self.proc._pipe_connection_lost(self.fd, exc)
272
+ self.proc = None
273
+
274
+ def pause_writing(self):
275
+ self.proc._protocol.pause_writing()
276
+
277
+ def resume_writing(self):
278
+ self.proc._protocol.resume_writing()
279
+
280
+
281
+ class ReadSubprocessPipeProto(WriteSubprocessPipeProto,
282
+ protocols.Protocol):
283
+
284
+ def data_received(self, data):
285
+ self.proc._pipe_data_received(self.fd, data)
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/base_tasks.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import linecache
2
+ import reprlib
3
+ import traceback
4
+
5
+ from . import base_futures
6
+ from . import coroutines
7
+
8
+
9
+ def _task_repr_info(task):
10
+ info = base_futures._future_repr_info(task)
11
+
12
+ if task.cancelling() and not task.done():
13
+ # replace status
14
+ info[0] = 'cancelling'
15
+
16
+ info.insert(1, 'name=%r' % task.get_name())
17
+
18
+ coro = coroutines._format_coroutine(task._coro)
19
+ info.insert(2, f'coro=<{coro}>')
20
+
21
+ if task._fut_waiter is not None:
22
+ info.insert(3, f'wait_for={task._fut_waiter!r}')
23
+ return info
24
+
25
+
26
+ @reprlib.recursive_repr()
27
+ def _task_repr(task):
28
+ info = ' '.join(_task_repr_info(task))
29
+ return f'<{task.__class__.__name__} {info}>'
30
+
31
+
32
+ def _task_get_stack(task, limit):
33
+ frames = []
34
+ if hasattr(task._coro, 'cr_frame'):
35
+ # case 1: 'async def' coroutines
36
+ f = task._coro.cr_frame
37
+ elif hasattr(task._coro, 'gi_frame'):
38
+ # case 2: legacy coroutines
39
+ f = task._coro.gi_frame
40
+ elif hasattr(task._coro, 'ag_frame'):
41
+ # case 3: async generators
42
+ f = task._coro.ag_frame
43
+ else:
44
+ # case 4: unknown objects
45
+ f = None
46
+ if f is not None:
47
+ while f is not None:
48
+ if limit is not None:
49
+ if limit <= 0:
50
+ break
51
+ limit -= 1
52
+ frames.append(f)
53
+ f = f.f_back
54
+ frames.reverse()
55
+ elif task._exception is not None:
56
+ tb = task._exception.__traceback__
57
+ while tb is not None:
58
+ if limit is not None:
59
+ if limit <= 0:
60
+ break
61
+ limit -= 1
62
+ frames.append(tb.tb_frame)
63
+ tb = tb.tb_next
64
+ return frames
65
+
66
+
67
+ def _task_print_stack(task, limit, file):
68
+ extracted_list = []
69
+ checked = set()
70
+ for f in task.get_stack(limit=limit):
71
+ lineno = f.f_lineno
72
+ co = f.f_code
73
+ filename = co.co_filename
74
+ name = co.co_name
75
+ if filename not in checked:
76
+ checked.add(filename)
77
+ linecache.checkcache(filename)
78
+ line = linecache.getline(filename, lineno, f.f_globals)
79
+ extracted_list.append((filename, lineno, name, line))
80
+
81
+ exc = task._exception
82
+ if not extracted_list:
83
+ print(f'No stack for {task!r}', file=file)
84
+ elif exc is not None:
85
+ print(f'Traceback for {task!r} (most recent call last):', file=file)
86
+ else:
87
+ print(f'Stack for {task!r} (most recent call last):', file=file)
88
+
89
+ traceback.print_list(extracted_list, file=file)
90
+ if exc is not None:
91
+ for line in traceback.format_exception_only(exc.__class__, exc):
92
+ print(line, file=file, end='')
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/constants.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contains code from https://github.com/MagicStack/uvloop/tree/v0.16.0
2
+ # SPDX-License-Identifier: PSF-2.0 AND (MIT OR Apache-2.0)
3
+ # SPDX-FileCopyrightText: Copyright (c) 2015-2021 MagicStack Inc. http://magic.io
4
+
5
+ import enum
6
+
7
+ # After the connection is lost, log warnings after this many write()s.
8
+ LOG_THRESHOLD_FOR_CONNLOST_WRITES = 5
9
+
10
+ # Seconds to wait before retrying accept().
11
+ ACCEPT_RETRY_DELAY = 1
12
+
13
+ # Number of stack entries to capture in debug mode.
14
+ # The larger the number, the slower the operation in debug mode
15
+ # (see extract_stack() in format_helpers.py).
16
+ DEBUG_STACK_DEPTH = 10
17
+
18
+ # Number of seconds to wait for SSL handshake to complete
19
+ # The default timeout matches that of Nginx.
20
+ SSL_HANDSHAKE_TIMEOUT = 60.0
21
+
22
+ # Number of seconds to wait for SSL shutdown to complete
23
+ # The default timeout mimics lingering_time
24
+ SSL_SHUTDOWN_TIMEOUT = 30.0
25
+
26
+ # Used in sendfile fallback code. We use fallback for platforms
27
+ # that don't support sendfile, or for TLS connections.
28
+ SENDFILE_FALLBACK_READBUFFER_SIZE = 1024 * 256
29
+
30
+ FLOW_CONTROL_HIGH_WATER_SSL_READ = 256 # KiB
31
+ FLOW_CONTROL_HIGH_WATER_SSL_WRITE = 512 # KiB
32
+
33
+ # The enum should be here to break circular dependencies between
34
+ # base_events and sslproto
35
+ class _SendfileMode(enum.Enum):
36
+ UNSUPPORTED = enum.auto()
37
+ TRY_NATIVE = enum.auto()
38
+ FALLBACK = enum.auto()
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/coroutines.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = 'iscoroutinefunction', 'iscoroutine'
2
+
3
+ import collections.abc
4
+ import inspect
5
+ import os
6
+ import sys
7
+ import traceback
8
+ import types
9
+
10
+
11
+ def _is_debug_mode():
12
+ # See: https://docs.python.org/3/library/asyncio-dev.html#asyncio-debug-mode.
13
+ return sys.flags.dev_mode or (not sys.flags.ignore_environment and
14
+ bool(os.environ.get('PYTHONASYNCIODEBUG')))
15
+
16
+
17
+ # A marker for iscoroutinefunction.
18
+ _is_coroutine = object()
19
+
20
+
21
+ def iscoroutinefunction(func):
22
+ """Return True if func is a decorated coroutine function."""
23
+ return (inspect.iscoroutinefunction(func) or
24
+ getattr(func, '_is_coroutine', None) is _is_coroutine)
25
+
26
+
27
+ # Prioritize native coroutine check to speed-up
28
+ # asyncio.iscoroutine.
29
+ _COROUTINE_TYPES = (types.CoroutineType, types.GeneratorType,
30
+ collections.abc.Coroutine)
31
+ _iscoroutine_typecache = set()
32
+
33
+
34
+ def iscoroutine(obj):
35
+ """Return True if obj is a coroutine object."""
36
+ if type(obj) in _iscoroutine_typecache:
37
+ return True
38
+
39
+ if isinstance(obj, _COROUTINE_TYPES):
40
+ # Just in case we don't want to cache more than 100
41
+ # positive types. That shouldn't ever happen, unless
42
+ # someone stressing the system on purpose.
43
+ if len(_iscoroutine_typecache) < 100:
44
+ _iscoroutine_typecache.add(type(obj))
45
+ return True
46
+ else:
47
+ return False
48
+
49
+
50
+ def _format_coroutine(coro):
51
+ assert iscoroutine(coro)
52
+
53
+ def get_name(coro):
54
+ # Coroutines compiled with Cython sometimes don't have
55
+ # proper __qualname__ or __name__. While that is a bug
56
+ # in Cython, asyncio shouldn't crash with an AttributeError
57
+ # in its __repr__ functions.
58
+ if hasattr(coro, '__qualname__') and coro.__qualname__:
59
+ coro_name = coro.__qualname__
60
+ elif hasattr(coro, '__name__') and coro.__name__:
61
+ coro_name = coro.__name__
62
+ else:
63
+ # Stop masking Cython bugs, expose them in a friendly way.
64
+ coro_name = f'<{type(coro).__name__} without __name__>'
65
+ return f'{coro_name}()'
66
+
67
+ def is_running(coro):
68
+ try:
69
+ return coro.cr_running
70
+ except AttributeError:
71
+ try:
72
+ return coro.gi_running
73
+ except AttributeError:
74
+ return False
75
+
76
+ coro_code = None
77
+ if hasattr(coro, 'cr_code') and coro.cr_code:
78
+ coro_code = coro.cr_code
79
+ elif hasattr(coro, 'gi_code') and coro.gi_code:
80
+ coro_code = coro.gi_code
81
+
82
+ coro_name = get_name(coro)
83
+
84
+ if not coro_code:
85
+ # Built-in types might not have __qualname__ or __name__.
86
+ if is_running(coro):
87
+ return f'{coro_name} running'
88
+ else:
89
+ return coro_name
90
+
91
+ coro_frame = None
92
+ if hasattr(coro, 'gi_frame') and coro.gi_frame:
93
+ coro_frame = coro.gi_frame
94
+ elif hasattr(coro, 'cr_frame') and coro.cr_frame:
95
+ coro_frame = coro.cr_frame
96
+
97
+ # If Cython's coroutine has a fake code object without proper
98
+ # co_filename -- expose that.
99
+ filename = coro_code.co_filename or '<empty co_filename>'
100
+
101
+ lineno = 0
102
+
103
+ if coro_frame is not None:
104
+ lineno = coro_frame.f_lineno
105
+ coro_repr = f'{coro_name} running at {filename}:{lineno}'
106
+
107
+ else:
108
+ lineno = coro_code.co_firstlineno
109
+ coro_repr = f'{coro_name} done, defined at {filename}:{lineno}'
110
+
111
+ return coro_repr
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/events.py ADDED
@@ -0,0 +1,846 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Event loop and event loop policy."""
2
+
3
+ # Contains code from https://github.com/MagicStack/uvloop/tree/v0.16.0
4
+ # SPDX-License-Identifier: PSF-2.0 AND (MIT OR Apache-2.0)
5
+ # SPDX-FileCopyrightText: Copyright (c) 2015-2021 MagicStack Inc. http://magic.io
6
+
7
+ __all__ = (
8
+ 'AbstractEventLoopPolicy',
9
+ 'AbstractEventLoop', 'AbstractServer',
10
+ 'Handle', 'TimerHandle',
11
+ 'get_event_loop_policy', 'set_event_loop_policy',
12
+ 'get_event_loop', 'set_event_loop', 'new_event_loop',
13
+ 'get_child_watcher', 'set_child_watcher',
14
+ '_set_running_loop', 'get_running_loop',
15
+ '_get_running_loop',
16
+ )
17
+
18
+ import contextvars
19
+ import os
20
+ import socket
21
+ import subprocess
22
+ import sys
23
+ import threading
24
+
25
+ from . import format_helpers
26
+
27
+
28
+ class Handle:
29
+ """Object returned by callback registration methods."""
30
+
31
+ __slots__ = ('_callback', '_args', '_cancelled', '_loop',
32
+ '_source_traceback', '_repr', '__weakref__',
33
+ '_context')
34
+
35
+ def __init__(self, callback, args, loop, context=None):
36
+ if context is None:
37
+ context = contextvars.copy_context()
38
+ self._context = context
39
+ self._loop = loop
40
+ self._callback = callback
41
+ self._args = args
42
+ self._cancelled = False
43
+ self._repr = None
44
+ if self._loop.get_debug():
45
+ self._source_traceback = format_helpers.extract_stack(
46
+ sys._getframe(1))
47
+ else:
48
+ self._source_traceback = None
49
+
50
+ def _repr_info(self):
51
+ info = [self.__class__.__name__]
52
+ if self._cancelled:
53
+ info.append('cancelled')
54
+ if self._callback is not None:
55
+ info.append(format_helpers._format_callback_source(
56
+ self._callback, self._args))
57
+ if self._source_traceback:
58
+ frame = self._source_traceback[-1]
59
+ info.append(f'created at {frame[0]}:{frame[1]}')
60
+ return info
61
+
62
+ def __repr__(self):
63
+ if self._repr is not None:
64
+ return self._repr
65
+ info = self._repr_info()
66
+ return '<{}>'.format(' '.join(info))
67
+
68
+ def cancel(self):
69
+ if not self._cancelled:
70
+ self._cancelled = True
71
+ if self._loop.get_debug():
72
+ # Keep a representation in debug mode to keep callback and
73
+ # parameters. For example, to log the warning
74
+ # "Executing <Handle...> took 2.5 second"
75
+ self._repr = repr(self)
76
+ self._callback = None
77
+ self._args = None
78
+
79
+ def cancelled(self):
80
+ return self._cancelled
81
+
82
+ def _run(self):
83
+ try:
84
+ self._context.run(self._callback, *self._args)
85
+ except (SystemExit, KeyboardInterrupt):
86
+ raise
87
+ except BaseException as exc:
88
+ cb = format_helpers._format_callback_source(
89
+ self._callback, self._args)
90
+ msg = f'Exception in callback {cb}'
91
+ context = {
92
+ 'message': msg,
93
+ 'exception': exc,
94
+ 'handle': self,
95
+ }
96
+ if self._source_traceback:
97
+ context['source_traceback'] = self._source_traceback
98
+ self._loop.call_exception_handler(context)
99
+ self = None # Needed to break cycles when an exception occurs.
100
+
101
+
102
+ class TimerHandle(Handle):
103
+ """Object returned by timed callback registration methods."""
104
+
105
+ __slots__ = ['_scheduled', '_when']
106
+
107
+ def __init__(self, when, callback, args, loop, context=None):
108
+ super().__init__(callback, args, loop, context)
109
+ if self._source_traceback:
110
+ del self._source_traceback[-1]
111
+ self._when = when
112
+ self._scheduled = False
113
+
114
+ def _repr_info(self):
115
+ info = super()._repr_info()
116
+ pos = 2 if self._cancelled else 1
117
+ info.insert(pos, f'when={self._when}')
118
+ return info
119
+
120
+ def __hash__(self):
121
+ return hash(self._when)
122
+
123
+ def __lt__(self, other):
124
+ if isinstance(other, TimerHandle):
125
+ return self._when < other._when
126
+ return NotImplemented
127
+
128
+ def __le__(self, other):
129
+ if isinstance(other, TimerHandle):
130
+ return self._when < other._when or self.__eq__(other)
131
+ return NotImplemented
132
+
133
+ def __gt__(self, other):
134
+ if isinstance(other, TimerHandle):
135
+ return self._when > other._when
136
+ return NotImplemented
137
+
138
+ def __ge__(self, other):
139
+ if isinstance(other, TimerHandle):
140
+ return self._when > other._when or self.__eq__(other)
141
+ return NotImplemented
142
+
143
+ def __eq__(self, other):
144
+ if isinstance(other, TimerHandle):
145
+ return (self._when == other._when and
146
+ self._callback == other._callback and
147
+ self._args == other._args and
148
+ self._cancelled == other._cancelled)
149
+ return NotImplemented
150
+
151
+ def cancel(self):
152
+ if not self._cancelled:
153
+ self._loop._timer_handle_cancelled(self)
154
+ super().cancel()
155
+
156
+ def when(self):
157
+ """Return a scheduled callback time.
158
+
159
+ The time is an absolute timestamp, using the same time
160
+ reference as loop.time().
161
+ """
162
+ return self._when
163
+
164
+
165
+ class AbstractServer:
166
+ """Abstract server returned by create_server()."""
167
+
168
+ def close(self):
169
+ """Stop serving. This leaves existing connections open."""
170
+ raise NotImplementedError
171
+
172
+ def get_loop(self):
173
+ """Get the event loop the Server object is attached to."""
174
+ raise NotImplementedError
175
+
176
+ def is_serving(self):
177
+ """Return True if the server is accepting connections."""
178
+ raise NotImplementedError
179
+
180
+ async def start_serving(self):
181
+ """Start accepting connections.
182
+
183
+ This method is idempotent, so it can be called when
184
+ the server is already being serving.
185
+ """
186
+ raise NotImplementedError
187
+
188
+ async def serve_forever(self):
189
+ """Start accepting connections until the coroutine is cancelled.
190
+
191
+ The server is closed when the coroutine is cancelled.
192
+ """
193
+ raise NotImplementedError
194
+
195
+ async def wait_closed(self):
196
+ """Coroutine to wait until service is closed."""
197
+ raise NotImplementedError
198
+
199
+ async def __aenter__(self):
200
+ return self
201
+
202
+ async def __aexit__(self, *exc):
203
+ self.close()
204
+ await self.wait_closed()
205
+
206
+
207
+ class AbstractEventLoop:
208
+ """Abstract event loop."""
209
+
210
+ # Running and stopping the event loop.
211
+
212
+ def run_forever(self):
213
+ """Run the event loop until stop() is called."""
214
+ raise NotImplementedError
215
+
216
+ def run_until_complete(self, future):
217
+ """Run the event loop until a Future is done.
218
+
219
+ Return the Future's result, or raise its exception.
220
+ """
221
+ raise NotImplementedError
222
+
223
+ def stop(self):
224
+ """Stop the event loop as soon as reasonable.
225
+
226
+ Exactly how soon that is may depend on the implementation, but
227
+ no more I/O callbacks should be scheduled.
228
+ """
229
+ raise NotImplementedError
230
+
231
+ def is_running(self):
232
+ """Return whether the event loop is currently running."""
233
+ raise NotImplementedError
234
+
235
+ def is_closed(self):
236
+ """Returns True if the event loop was closed."""
237
+ raise NotImplementedError
238
+
239
+ def close(self):
240
+ """Close the loop.
241
+
242
+ The loop should not be running.
243
+
244
+ This is idempotent and irreversible.
245
+
246
+ No other methods should be called after this one.
247
+ """
248
+ raise NotImplementedError
249
+
250
+ async def shutdown_asyncgens(self):
251
+ """Shutdown all active asynchronous generators."""
252
+ raise NotImplementedError
253
+
254
+ async def shutdown_default_executor(self):
255
+ """Schedule the shutdown of the default executor."""
256
+ raise NotImplementedError
257
+
258
+ # Methods scheduling callbacks. All these return Handles.
259
+
260
+ def _timer_handle_cancelled(self, handle):
261
+ """Notification that a TimerHandle has been cancelled."""
262
+ raise NotImplementedError
263
+
264
+ def call_soon(self, callback, *args, context=None):
265
+ return self.call_later(0, callback, *args, context=context)
266
+
267
+ def call_later(self, delay, callback, *args, context=None):
268
+ raise NotImplementedError
269
+
270
+ def call_at(self, when, callback, *args, context=None):
271
+ raise NotImplementedError
272
+
273
+ def time(self):
274
+ raise NotImplementedError
275
+
276
+ def create_future(self):
277
+ raise NotImplementedError
278
+
279
+ # Method scheduling a coroutine object: create a task.
280
+
281
+ def create_task(self, coro, *, name=None, context=None):
282
+ raise NotImplementedError
283
+
284
+ # Methods for interacting with threads.
285
+
286
+ def call_soon_threadsafe(self, callback, *args, context=None):
287
+ raise NotImplementedError
288
+
289
+ def run_in_executor(self, executor, func, *args):
290
+ raise NotImplementedError
291
+
292
+ def set_default_executor(self, executor):
293
+ raise NotImplementedError
294
+
295
+ # Network I/O methods returning Futures.
296
+
297
+ async def getaddrinfo(self, host, port, *,
298
+ family=0, type=0, proto=0, flags=0):
299
+ raise NotImplementedError
300
+
301
+ async def getnameinfo(self, sockaddr, flags=0):
302
+ raise NotImplementedError
303
+
304
+ async def create_connection(
305
+ self, protocol_factory, host=None, port=None,
306
+ *, ssl=None, family=0, proto=0,
307
+ flags=0, sock=None, local_addr=None,
308
+ server_hostname=None,
309
+ ssl_handshake_timeout=None,
310
+ ssl_shutdown_timeout=None,
311
+ happy_eyeballs_delay=None, interleave=None):
312
+ raise NotImplementedError
313
+
314
+ async def create_server(
315
+ self, protocol_factory, host=None, port=None,
316
+ *, family=socket.AF_UNSPEC,
317
+ flags=socket.AI_PASSIVE, sock=None, backlog=100,
318
+ ssl=None, reuse_address=None, reuse_port=None,
319
+ ssl_handshake_timeout=None,
320
+ ssl_shutdown_timeout=None,
321
+ start_serving=True):
322
+ """A coroutine which creates a TCP server bound to host and port.
323
+
324
+ The return value is a Server object which can be used to stop
325
+ the service.
326
+
327
+ If host is an empty string or None all interfaces are assumed
328
+ and a list of multiple sockets will be returned (most likely
329
+ one for IPv4 and another one for IPv6). The host parameter can also be
330
+ a sequence (e.g. list) of hosts to bind to.
331
+
332
+ family can be set to either AF_INET or AF_INET6 to force the
333
+ socket to use IPv4 or IPv6. If not set it will be determined
334
+ from host (defaults to AF_UNSPEC).
335
+
336
+ flags is a bitmask for getaddrinfo().
337
+
338
+ sock can optionally be specified in order to use a preexisting
339
+ socket object.
340
+
341
+ backlog is the maximum number of queued connections passed to
342
+ listen() (defaults to 100).
343
+
344
+ ssl can be set to an SSLContext to enable SSL over the
345
+ accepted connections.
346
+
347
+ reuse_address tells the kernel to reuse a local socket in
348
+ TIME_WAIT state, without waiting for its natural timeout to
349
+ expire. If not specified will automatically be set to True on
350
+ UNIX.
351
+
352
+ reuse_port tells the kernel to allow this endpoint to be bound to
353
+ the same port as other existing endpoints are bound to, so long as
354
+ they all set this flag when being created. This option is not
355
+ supported on Windows.
356
+
357
+ ssl_handshake_timeout is the time in seconds that an SSL server
358
+ will wait for completion of the SSL handshake before aborting the
359
+ connection. Default is 60s.
360
+
361
+ ssl_shutdown_timeout is the time in seconds that an SSL server
362
+ will wait for completion of the SSL shutdown procedure
363
+ before aborting the connection. Default is 30s.
364
+
365
+ start_serving set to True (default) causes the created server
366
+ to start accepting connections immediately. When set to False,
367
+ the user should await Server.start_serving() or Server.serve_forever()
368
+ to make the server to start accepting connections.
369
+ """
370
+ raise NotImplementedError
371
+
372
+ async def sendfile(self, transport, file, offset=0, count=None,
373
+ *, fallback=True):
374
+ """Send a file through a transport.
375
+
376
+ Return an amount of sent bytes.
377
+ """
378
+ raise NotImplementedError
379
+
380
+ async def start_tls(self, transport, protocol, sslcontext, *,
381
+ server_side=False,
382
+ server_hostname=None,
383
+ ssl_handshake_timeout=None,
384
+ ssl_shutdown_timeout=None):
385
+ """Upgrade a transport to TLS.
386
+
387
+ Return a new transport that *protocol* should start using
388
+ immediately.
389
+ """
390
+ raise NotImplementedError
391
+
392
+ async def create_unix_connection(
393
+ self, protocol_factory, path=None, *,
394
+ ssl=None, sock=None,
395
+ server_hostname=None,
396
+ ssl_handshake_timeout=None,
397
+ ssl_shutdown_timeout=None):
398
+ raise NotImplementedError
399
+
400
+ async def create_unix_server(
401
+ self, protocol_factory, path=None, *,
402
+ sock=None, backlog=100, ssl=None,
403
+ ssl_handshake_timeout=None,
404
+ ssl_shutdown_timeout=None,
405
+ start_serving=True):
406
+ """A coroutine which creates a UNIX Domain Socket server.
407
+
408
+ The return value is a Server object, which can be used to stop
409
+ the service.
410
+
411
+ path is a str, representing a file system path to bind the
412
+ server socket to.
413
+
414
+ sock can optionally be specified in order to use a preexisting
415
+ socket object.
416
+
417
+ backlog is the maximum number of queued connections passed to
418
+ listen() (defaults to 100).
419
+
420
+ ssl can be set to an SSLContext to enable SSL over the
421
+ accepted connections.
422
+
423
+ ssl_handshake_timeout is the time in seconds that an SSL server
424
+ will wait for the SSL handshake to complete (defaults to 60s).
425
+
426
+ ssl_shutdown_timeout is the time in seconds that an SSL server
427
+ will wait for the SSL shutdown to finish (defaults to 30s).
428
+
429
+ start_serving set to True (default) causes the created server
430
+ to start accepting connections immediately. When set to False,
431
+ the user should await Server.start_serving() or Server.serve_forever()
432
+ to make the server to start accepting connections.
433
+ """
434
+ raise NotImplementedError
435
+
436
+ async def connect_accepted_socket(
437
+ self, protocol_factory, sock,
438
+ *, ssl=None,
439
+ ssl_handshake_timeout=None,
440
+ ssl_shutdown_timeout=None):
441
+ """Handle an accepted connection.
442
+
443
+ This is used by servers that accept connections outside of
444
+ asyncio, but use asyncio to handle connections.
445
+
446
+ This method is a coroutine. When completed, the coroutine
447
+ returns a (transport, protocol) pair.
448
+ """
449
+ raise NotImplementedError
450
+
451
+ async def create_datagram_endpoint(self, protocol_factory,
452
+ local_addr=None, remote_addr=None, *,
453
+ family=0, proto=0, flags=0,
454
+ reuse_address=None, reuse_port=None,
455
+ allow_broadcast=None, sock=None):
456
+ """A coroutine which creates a datagram endpoint.
457
+
458
+ This method will try to establish the endpoint in the background.
459
+ When successful, the coroutine returns a (transport, protocol) pair.
460
+
461
+ protocol_factory must be a callable returning a protocol instance.
462
+
463
+ socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
464
+ host (or family if specified), socket type SOCK_DGRAM.
465
+
466
+ reuse_address tells the kernel to reuse a local socket in
467
+ TIME_WAIT state, without waiting for its natural timeout to
468
+ expire. If not specified it will automatically be set to True on
469
+ UNIX.
470
+
471
+ reuse_port tells the kernel to allow this endpoint to be bound to
472
+ the same port as other existing endpoints are bound to, so long as
473
+ they all set this flag when being created. This option is not
474
+ supported on Windows and some UNIX's. If the
475
+ :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
476
+ capability is unsupported.
477
+
478
+ allow_broadcast tells the kernel to allow this endpoint to send
479
+ messages to the broadcast address.
480
+
481
+ sock can optionally be specified in order to use a preexisting
482
+ socket object.
483
+ """
484
+ raise NotImplementedError
485
+
486
+ # Pipes and subprocesses.
487
+
488
+ async def connect_read_pipe(self, protocol_factory, pipe):
489
+ """Register read pipe in event loop. Set the pipe to non-blocking mode.
490
+
491
+ protocol_factory should instantiate object with Protocol interface.
492
+ pipe is a file-like object.
493
+ Return pair (transport, protocol), where transport supports the
494
+ ReadTransport interface."""
495
+ # The reason to accept file-like object instead of just file descriptor
496
+ # is: we need to own pipe and close it at transport finishing
497
+ # Can got complicated errors if pass f.fileno(),
498
+ # close fd in pipe transport then close f and vice versa.
499
+ raise NotImplementedError
500
+
501
+ async def connect_write_pipe(self, protocol_factory, pipe):
502
+ """Register write pipe in event loop.
503
+
504
+ protocol_factory should instantiate object with BaseProtocol interface.
505
+ Pipe is file-like object already switched to nonblocking.
506
+ Return pair (transport, protocol), where transport support
507
+ WriteTransport interface."""
508
+ # The reason to accept file-like object instead of just file descriptor
509
+ # is: we need to own pipe and close it at transport finishing
510
+ # Can got complicated errors if pass f.fileno(),
511
+ # close fd in pipe transport then close f and vice versa.
512
+ raise NotImplementedError
513
+
514
+ async def subprocess_shell(self, protocol_factory, cmd, *,
515
+ stdin=subprocess.PIPE,
516
+ stdout=subprocess.PIPE,
517
+ stderr=subprocess.PIPE,
518
+ **kwargs):
519
+ raise NotImplementedError
520
+
521
+ async def subprocess_exec(self, protocol_factory, *args,
522
+ stdin=subprocess.PIPE,
523
+ stdout=subprocess.PIPE,
524
+ stderr=subprocess.PIPE,
525
+ **kwargs):
526
+ raise NotImplementedError
527
+
528
+ # Ready-based callback registration methods.
529
+ # The add_*() methods return None.
530
+ # The remove_*() methods return True if something was removed,
531
+ # False if there was nothing to delete.
532
+
533
+ def add_reader(self, fd, callback, *args):
534
+ raise NotImplementedError
535
+
536
+ def remove_reader(self, fd):
537
+ raise NotImplementedError
538
+
539
+ def add_writer(self, fd, callback, *args):
540
+ raise NotImplementedError
541
+
542
+ def remove_writer(self, fd):
543
+ raise NotImplementedError
544
+
545
+ # Completion based I/O methods returning Futures.
546
+
547
+ async def sock_recv(self, sock, nbytes):
548
+ raise NotImplementedError
549
+
550
+ async def sock_recv_into(self, sock, buf):
551
+ raise NotImplementedError
552
+
553
+ async def sock_recvfrom(self, sock, bufsize):
554
+ raise NotImplementedError
555
+
556
+ async def sock_recvfrom_into(self, sock, buf, nbytes=0):
557
+ raise NotImplementedError
558
+
559
+ async def sock_sendall(self, sock, data):
560
+ raise NotImplementedError
561
+
562
+ async def sock_sendto(self, sock, data, address):
563
+ raise NotImplementedError
564
+
565
+ async def sock_connect(self, sock, address):
566
+ raise NotImplementedError
567
+
568
+ async def sock_accept(self, sock):
569
+ raise NotImplementedError
570
+
571
+ async def sock_sendfile(self, sock, file, offset=0, count=None,
572
+ *, fallback=None):
573
+ raise NotImplementedError
574
+
575
+ # Signal handling.
576
+
577
+ def add_signal_handler(self, sig, callback, *args):
578
+ raise NotImplementedError
579
+
580
+ def remove_signal_handler(self, sig):
581
+ raise NotImplementedError
582
+
583
+ # Task factory.
584
+
585
+ def set_task_factory(self, factory):
586
+ raise NotImplementedError
587
+
588
+ def get_task_factory(self):
589
+ raise NotImplementedError
590
+
591
+ # Error handlers.
592
+
593
+ def get_exception_handler(self):
594
+ raise NotImplementedError
595
+
596
+ def set_exception_handler(self, handler):
597
+ raise NotImplementedError
598
+
599
+ def default_exception_handler(self, context):
600
+ raise NotImplementedError
601
+
602
+ def call_exception_handler(self, context):
603
+ raise NotImplementedError
604
+
605
+ # Debug flag management.
606
+
607
+ def get_debug(self):
608
+ raise NotImplementedError
609
+
610
+ def set_debug(self, enabled):
611
+ raise NotImplementedError
612
+
613
+
614
+ class AbstractEventLoopPolicy:
615
+ """Abstract policy for accessing the event loop."""
616
+
617
+ def get_event_loop(self):
618
+ """Get the event loop for the current context.
619
+
620
+ Returns an event loop object implementing the AbstractEventLoop interface,
621
+ or raises an exception in case no event loop has been set for the
622
+ current context and the current policy does not specify to create one.
623
+
624
+ It should never return None."""
625
+ raise NotImplementedError
626
+
627
+ def set_event_loop(self, loop):
628
+ """Set the event loop for the current context to loop."""
629
+ raise NotImplementedError
630
+
631
+ def new_event_loop(self):
632
+ """Create and return a new event loop object according to this
633
+ policy's rules. If there's need to set this loop as the event loop for
634
+ the current context, set_event_loop must be called explicitly."""
635
+ raise NotImplementedError
636
+
637
+ # Child processes handling (Unix only).
638
+
639
+ def get_child_watcher(self):
640
+ "Get the watcher for child processes."
641
+ raise NotImplementedError
642
+
643
+ def set_child_watcher(self, watcher):
644
+ """Set the watcher for child processes."""
645
+ raise NotImplementedError
646
+
647
+
648
+ class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
649
+ """Default policy implementation for accessing the event loop.
650
+
651
+ In this policy, each thread has its own event loop. However, we
652
+ only automatically create an event loop by default for the main
653
+ thread; other threads by default have no event loop.
654
+
655
+ Other policies may have different rules (e.g. a single global
656
+ event loop, or automatically creating an event loop per thread, or
657
+ using some other notion of context to which an event loop is
658
+ associated).
659
+ """
660
+
661
+ _loop_factory = None
662
+
663
+ class _Local(threading.local):
664
+ _loop = None
665
+ _set_called = False
666
+
667
+ def __init__(self):
668
+ self._local = self._Local()
669
+
670
+ def get_event_loop(self):
671
+ """Get the event loop for the current context.
672
+
673
+ Returns an instance of EventLoop or raises an exception.
674
+ """
675
+ if (self._local._loop is None and
676
+ not self._local._set_called and
677
+ threading.current_thread() is threading.main_thread()):
678
+ self.set_event_loop(self.new_event_loop())
679
+
680
+ if self._local._loop is None:
681
+ raise RuntimeError('There is no current event loop in thread %r.'
682
+ % threading.current_thread().name)
683
+
684
+ return self._local._loop
685
+
686
+ def set_event_loop(self, loop):
687
+ """Set the event loop."""
688
+ self._local._set_called = True
689
+ if loop is not None and not isinstance(loop, AbstractEventLoop):
690
+ raise TypeError(f"loop must be an instance of AbstractEventLoop or None, not '{type(loop).__name__}'")
691
+ self._local._loop = loop
692
+
693
+ def new_event_loop(self):
694
+ """Create a new event loop.
695
+
696
+ You must call set_event_loop() to make this the current event
697
+ loop.
698
+ """
699
+ return self._loop_factory()
700
+
701
+
702
+ # Event loop policy. The policy itself is always global, even if the
703
+ # policy's rules say that there is an event loop per thread (or other
704
+ # notion of context). The default policy is installed by the first
705
+ # call to get_event_loop_policy().
706
+ _event_loop_policy = None
707
+
708
+ # Lock for protecting the on-the-fly creation of the event loop policy.
709
+ _lock = threading.Lock()
710
+
711
+
712
+ # A TLS for the running event loop, used by _get_running_loop.
713
+ class _RunningLoop(threading.local):
714
+ loop_pid = (None, None)
715
+
716
+
717
+ _running_loop = _RunningLoop()
718
+
719
+
720
+ def get_running_loop():
721
+ """Return the running event loop. Raise a RuntimeError if there is none.
722
+
723
+ This function is thread-specific.
724
+ """
725
+ # NOTE: this function is implemented in C (see _asynciomodule.c)
726
+ loop = _get_running_loop()
727
+ if loop is None:
728
+ raise RuntimeError('no running event loop')
729
+ return loop
730
+
731
+
732
+ def _get_running_loop():
733
+ """Return the running event loop or None.
734
+
735
+ This is a low-level function intended to be used by event loops.
736
+ This function is thread-specific.
737
+ """
738
+ # NOTE: this function is implemented in C (see _asynciomodule.c)
739
+ running_loop, pid = _running_loop.loop_pid
740
+ if running_loop is not None and pid == os.getpid():
741
+ return running_loop
742
+
743
+
744
+ def _set_running_loop(loop):
745
+ """Set the running event loop.
746
+
747
+ This is a low-level function intended to be used by event loops.
748
+ This function is thread-specific.
749
+ """
750
+ # NOTE: this function is implemented in C (see _asynciomodule.c)
751
+ _running_loop.loop_pid = (loop, os.getpid())
752
+
753
+
754
+ def _init_event_loop_policy():
755
+ global _event_loop_policy
756
+ with _lock:
757
+ if _event_loop_policy is None: # pragma: no branch
758
+ from . import DefaultEventLoopPolicy
759
+ _event_loop_policy = DefaultEventLoopPolicy()
760
+
761
+
762
+ def get_event_loop_policy():
763
+ """Get the current event loop policy."""
764
+ if _event_loop_policy is None:
765
+ _init_event_loop_policy()
766
+ return _event_loop_policy
767
+
768
+
769
+ def set_event_loop_policy(policy):
770
+ """Set the current event loop policy.
771
+
772
+ If policy is None, the default policy is restored."""
773
+ global _event_loop_policy
774
+ if policy is not None and not isinstance(policy, AbstractEventLoopPolicy):
775
+ raise TypeError(f"policy must be an instance of AbstractEventLoopPolicy or None, not '{type(policy).__name__}'")
776
+ _event_loop_policy = policy
777
+
778
+
779
+ def get_event_loop():
780
+ """Return an asyncio event loop.
781
+
782
+ When called from a coroutine or a callback (e.g. scheduled with call_soon
783
+ or similar API), this function will always return the running event loop.
784
+
785
+ If there is no running event loop set, the function will return
786
+ the result of `get_event_loop_policy().get_event_loop()` call.
787
+ """
788
+ # NOTE: this function is implemented in C (see _asynciomodule.c)
789
+ return _py__get_event_loop()
790
+
791
+
792
+ def _get_event_loop(stacklevel=3):
793
+ # This internal method is going away in Python 3.12, left here only for
794
+ # backwards compatibility with 3.10.0 - 3.10.8 and 3.11.0.
795
+ # Similarly, this method's C equivalent in _asyncio is going away as well.
796
+ # See GH-99949 for more details.
797
+ current_loop = _get_running_loop()
798
+ if current_loop is not None:
799
+ return current_loop
800
+ return get_event_loop_policy().get_event_loop()
801
+
802
+
803
+ def set_event_loop(loop):
804
+ """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
805
+ get_event_loop_policy().set_event_loop(loop)
806
+
807
+
808
+ def new_event_loop():
809
+ """Equivalent to calling get_event_loop_policy().new_event_loop()."""
810
+ return get_event_loop_policy().new_event_loop()
811
+
812
+
813
+ def get_child_watcher():
814
+ """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
815
+ return get_event_loop_policy().get_child_watcher()
816
+
817
+
818
+ def set_child_watcher(watcher):
819
+ """Equivalent to calling
820
+ get_event_loop_policy().set_child_watcher(watcher)."""
821
+ return get_event_loop_policy().set_child_watcher(watcher)
822
+
823
+
824
+ # Alias pure-Python implementations for testing purposes.
825
+ _py__get_running_loop = _get_running_loop
826
+ _py__set_running_loop = _set_running_loop
827
+ _py_get_running_loop = get_running_loop
828
+ _py_get_event_loop = get_event_loop
829
+ _py__get_event_loop = _get_event_loop
830
+
831
+
832
+ try:
833
+ # get_event_loop() is one of the most frequently called
834
+ # functions in asyncio. Pure Python implementation is
835
+ # about 4 times slower than C-accelerated.
836
+ from _asyncio import (_get_running_loop, _set_running_loop,
837
+ get_running_loop, get_event_loop, _get_event_loop)
838
+ except ImportError:
839
+ pass
840
+ else:
841
+ # Alias C implementations for testing purposes.
842
+ _c__get_running_loop = _get_running_loop
843
+ _c__set_running_loop = _set_running_loop
844
+ _c_get_running_loop = get_running_loop
845
+ _c_get_event_loop = get_event_loop
846
+ _c__get_event_loop = _get_event_loop
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/exceptions.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """asyncio exceptions."""
2
+
3
+
4
+ __all__ = ('BrokenBarrierError',
5
+ 'CancelledError', 'InvalidStateError', 'TimeoutError',
6
+ 'IncompleteReadError', 'LimitOverrunError',
7
+ 'SendfileNotAvailableError')
8
+
9
+
10
+ class CancelledError(BaseException):
11
+ """The Future or Task was cancelled."""
12
+
13
+
14
+ TimeoutError = TimeoutError # make local alias for the standard exception
15
+
16
+
17
+ class InvalidStateError(Exception):
18
+ """The operation is not allowed in this state."""
19
+
20
+
21
+ class SendfileNotAvailableError(RuntimeError):
22
+ """Sendfile syscall is not available.
23
+
24
+ Raised if OS does not support sendfile syscall for given socket or
25
+ file type.
26
+ """
27
+
28
+
29
+ class IncompleteReadError(EOFError):
30
+ """
31
+ Incomplete read error. Attributes:
32
+
33
+ - partial: read bytes string before the end of stream was reached
34
+ - expected: total number of expected bytes (or None if unknown)
35
+ """
36
+ def __init__(self, partial, expected):
37
+ r_expected = 'undefined' if expected is None else repr(expected)
38
+ super().__init__(f'{len(partial)} bytes read on a total of '
39
+ f'{r_expected} expected bytes')
40
+ self.partial = partial
41
+ self.expected = expected
42
+
43
+ def __reduce__(self):
44
+ return type(self), (self.partial, self.expected)
45
+
46
+
47
+ class LimitOverrunError(Exception):
48
+ """Reached the buffer limit while looking for a separator.
49
+
50
+ Attributes:
51
+ - consumed: total number of to be consumed bytes.
52
+ """
53
+ def __init__(self, message, consumed):
54
+ super().__init__(message)
55
+ self.consumed = consumed
56
+
57
+ def __reduce__(self):
58
+ return type(self), (self.args[0], self.consumed)
59
+
60
+
61
+ class BrokenBarrierError(RuntimeError):
62
+ """Barrier is broken by barrier.abort() call."""
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/format_helpers.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import inspect
3
+ import reprlib
4
+ import sys
5
+ import traceback
6
+
7
+ from . import constants
8
+
9
+
10
+ def _get_function_source(func):
11
+ func = inspect.unwrap(func)
12
+ if inspect.isfunction(func):
13
+ code = func.__code__
14
+ return (code.co_filename, code.co_firstlineno)
15
+ if isinstance(func, functools.partial):
16
+ return _get_function_source(func.func)
17
+ if isinstance(func, functools.partialmethod):
18
+ return _get_function_source(func.func)
19
+ return None
20
+
21
+
22
+ def _format_callback_source(func, args):
23
+ func_repr = _format_callback(func, args, None)
24
+ source = _get_function_source(func)
25
+ if source:
26
+ func_repr += f' at {source[0]}:{source[1]}'
27
+ return func_repr
28
+
29
+
30
+ def _format_args_and_kwargs(args, kwargs):
31
+ """Format function arguments and keyword arguments.
32
+
33
+ Special case for a single parameter: ('hello',) is formatted as ('hello').
34
+ """
35
+ # use reprlib to limit the length of the output
36
+ items = []
37
+ if args:
38
+ items.extend(reprlib.repr(arg) for arg in args)
39
+ if kwargs:
40
+ items.extend(f'{k}={reprlib.repr(v)}' for k, v in kwargs.items())
41
+ return '({})'.format(', '.join(items))
42
+
43
+
44
+ def _format_callback(func, args, kwargs, suffix=''):
45
+ if isinstance(func, functools.partial):
46
+ suffix = _format_args_and_kwargs(args, kwargs) + suffix
47
+ return _format_callback(func.func, func.args, func.keywords, suffix)
48
+
49
+ if hasattr(func, '__qualname__') and func.__qualname__:
50
+ func_repr = func.__qualname__
51
+ elif hasattr(func, '__name__') and func.__name__:
52
+ func_repr = func.__name__
53
+ else:
54
+ func_repr = repr(func)
55
+
56
+ func_repr += _format_args_and_kwargs(args, kwargs)
57
+ if suffix:
58
+ func_repr += suffix
59
+ return func_repr
60
+
61
+
62
+ def extract_stack(f=None, limit=None):
63
+ """Replacement for traceback.extract_stack() that only does the
64
+ necessary work for asyncio debug mode.
65
+ """
66
+ if f is None:
67
+ f = sys._getframe().f_back
68
+ if limit is None:
69
+ # Limit the amount of work to a reasonable amount, as extract_stack()
70
+ # can be called for each coroutine and future in debug mode.
71
+ limit = constants.DEBUG_STACK_DEPTH
72
+ stack = traceback.StackSummary.extract(traceback.walk_stack(f),
73
+ limit=limit,
74
+ lookup_lines=False)
75
+ stack.reverse()
76
+ return stack
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/futures.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A Future class similar to the one in PEP 3148."""
2
+
3
+ __all__ = (
4
+ 'Future', 'wrap_future', 'isfuture',
5
+ )
6
+
7
+ import concurrent.futures
8
+ import contextvars
9
+ import logging
10
+ import sys
11
+ from types import GenericAlias
12
+
13
+ from . import base_futures
14
+ from . import events
15
+ from . import exceptions
16
+ from . import format_helpers
17
+
18
+
19
+ isfuture = base_futures.isfuture
20
+
21
+
22
+ _PENDING = base_futures._PENDING
23
+ _CANCELLED = base_futures._CANCELLED
24
+ _FINISHED = base_futures._FINISHED
25
+
26
+
27
+ STACK_DEBUG = logging.DEBUG - 1 # heavy-duty debugging
28
+
29
+
30
+ class Future:
31
+ """This class is *almost* compatible with concurrent.futures.Future.
32
+
33
+ Differences:
34
+
35
+ - This class is not thread-safe.
36
+
37
+ - result() and exception() do not take a timeout argument and
38
+ raise an exception when the future isn't done yet.
39
+
40
+ - Callbacks registered with add_done_callback() are always called
41
+ via the event loop's call_soon().
42
+
43
+ - This class is not compatible with the wait() and as_completed()
44
+ methods in the concurrent.futures package.
45
+
46
+ (In Python 3.4 or later we may be able to unify the implementations.)
47
+ """
48
+
49
+ # Class variables serving as defaults for instance variables.
50
+ _state = _PENDING
51
+ _result = None
52
+ _exception = None
53
+ _loop = None
54
+ _source_traceback = None
55
+ _cancel_message = None
56
+ # A saved CancelledError for later chaining as an exception context.
57
+ _cancelled_exc = None
58
+
59
+ # This field is used for a dual purpose:
60
+ # - Its presence is a marker to declare that a class implements
61
+ # the Future protocol (i.e. is intended to be duck-type compatible).
62
+ # The value must also be not-None, to enable a subclass to declare
63
+ # that it is not compatible by setting this to None.
64
+ # - It is set by __iter__() below so that Task._step() can tell
65
+ # the difference between
66
+ # `await Future()` or`yield from Future()` (correct) vs.
67
+ # `yield Future()` (incorrect).
68
+ _asyncio_future_blocking = False
69
+
70
+ __log_traceback = False
71
+
72
+ def __init__(self, *, loop=None):
73
+ """Initialize the future.
74
+
75
+ The optional event_loop argument allows explicitly setting the event
76
+ loop object used by the future. If it's not provided, the future uses
77
+ the default event loop.
78
+ """
79
+ if loop is None:
80
+ self._loop = events._get_event_loop()
81
+ else:
82
+ self._loop = loop
83
+ self._callbacks = []
84
+ if self._loop.get_debug():
85
+ self._source_traceback = format_helpers.extract_stack(
86
+ sys._getframe(1))
87
+
88
+ def __repr__(self):
89
+ return base_futures._future_repr(self)
90
+
91
+ def __del__(self):
92
+ if not self.__log_traceback:
93
+ # set_exception() was not called, or result() or exception()
94
+ # has consumed the exception
95
+ return
96
+ exc = self._exception
97
+ context = {
98
+ 'message':
99
+ f'{self.__class__.__name__} exception was never retrieved',
100
+ 'exception': exc,
101
+ 'future': self,
102
+ }
103
+ if self._source_traceback:
104
+ context['source_traceback'] = self._source_traceback
105
+ self._loop.call_exception_handler(context)
106
+
107
+ __class_getitem__ = classmethod(GenericAlias)
108
+
109
+ @property
110
+ def _log_traceback(self):
111
+ return self.__log_traceback
112
+
113
+ @_log_traceback.setter
114
+ def _log_traceback(self, val):
115
+ if val:
116
+ raise ValueError('_log_traceback can only be set to False')
117
+ self.__log_traceback = False
118
+
119
+ def get_loop(self):
120
+ """Return the event loop the Future is bound to."""
121
+ loop = self._loop
122
+ if loop is None:
123
+ raise RuntimeError("Future object is not initialized.")
124
+ return loop
125
+
126
+ def _make_cancelled_error(self):
127
+ """Create the CancelledError to raise if the Future is cancelled.
128
+
129
+ This should only be called once when handling a cancellation since
130
+ it erases the saved context exception value.
131
+ """
132
+ if self._cancelled_exc is not None:
133
+ exc = self._cancelled_exc
134
+ self._cancelled_exc = None
135
+ return exc
136
+
137
+ if self._cancel_message is None:
138
+ exc = exceptions.CancelledError()
139
+ else:
140
+ exc = exceptions.CancelledError(self._cancel_message)
141
+ exc.__context__ = self._cancelled_exc
142
+ # Remove the reference since we don't need this anymore.
143
+ self._cancelled_exc = None
144
+ return exc
145
+
146
+ def cancel(self, msg=None):
147
+ """Cancel the future and schedule callbacks.
148
+
149
+ If the future is already done or cancelled, return False. Otherwise,
150
+ change the future's state to cancelled, schedule the callbacks and
151
+ return True.
152
+ """
153
+ self.__log_traceback = False
154
+ if self._state != _PENDING:
155
+ return False
156
+ self._state = _CANCELLED
157
+ self._cancel_message = msg
158
+ self.__schedule_callbacks()
159
+ return True
160
+
161
+ def __schedule_callbacks(self):
162
+ """Internal: Ask the event loop to call all callbacks.
163
+
164
+ The callbacks are scheduled to be called as soon as possible. Also
165
+ clears the callback list.
166
+ """
167
+ callbacks = self._callbacks[:]
168
+ if not callbacks:
169
+ return
170
+
171
+ self._callbacks[:] = []
172
+ for callback, ctx in callbacks:
173
+ self._loop.call_soon(callback, self, context=ctx)
174
+
175
+ def cancelled(self):
176
+ """Return True if the future was cancelled."""
177
+ return self._state == _CANCELLED
178
+
179
+ # Don't implement running(); see http://bugs.python.org/issue18699
180
+
181
+ def done(self):
182
+ """Return True if the future is done.
183
+
184
+ Done means either that a result / exception are available, or that the
185
+ future was cancelled.
186
+ """
187
+ return self._state != _PENDING
188
+
189
+ def result(self):
190
+ """Return the result this future represents.
191
+
192
+ If the future has been cancelled, raises CancelledError. If the
193
+ future's result isn't yet available, raises InvalidStateError. If
194
+ the future is done and has an exception set, this exception is raised.
195
+ """
196
+ if self._state == _CANCELLED:
197
+ exc = self._make_cancelled_error()
198
+ raise exc
199
+ if self._state != _FINISHED:
200
+ raise exceptions.InvalidStateError('Result is not ready.')
201
+ self.__log_traceback = False
202
+ if self._exception is not None:
203
+ raise self._exception.with_traceback(self._exception_tb)
204
+ return self._result
205
+
206
+ def exception(self):
207
+ """Return the exception that was set on this future.
208
+
209
+ The exception (or None if no exception was set) is returned only if
210
+ the future is done. If the future has been cancelled, raises
211
+ CancelledError. If the future isn't done yet, raises
212
+ InvalidStateError.
213
+ """
214
+ if self._state == _CANCELLED:
215
+ exc = self._make_cancelled_error()
216
+ raise exc
217
+ if self._state != _FINISHED:
218
+ raise exceptions.InvalidStateError('Exception is not set.')
219
+ self.__log_traceback = False
220
+ return self._exception
221
+
222
+ def add_done_callback(self, fn, *, context=None):
223
+ """Add a callback to be run when the future becomes done.
224
+
225
+ The callback is called with a single argument - the future object. If
226
+ the future is already done when this is called, the callback is
227
+ scheduled with call_soon.
228
+ """
229
+ if self._state != _PENDING:
230
+ self._loop.call_soon(fn, self, context=context)
231
+ else:
232
+ if context is None:
233
+ context = contextvars.copy_context()
234
+ self._callbacks.append((fn, context))
235
+
236
+ # New method not in PEP 3148.
237
+
238
+ def remove_done_callback(self, fn):
239
+ """Remove all instances of a callback from the "call when done" list.
240
+
241
+ Returns the number of callbacks removed.
242
+ """
243
+ filtered_callbacks = [(f, ctx)
244
+ for (f, ctx) in self._callbacks
245
+ if f != fn]
246
+ removed_count = len(self._callbacks) - len(filtered_callbacks)
247
+ if removed_count:
248
+ self._callbacks[:] = filtered_callbacks
249
+ return removed_count
250
+
251
+ # So-called internal methods (note: no set_running_or_notify_cancel()).
252
+
253
+ def set_result(self, result):
254
+ """Mark the future done and set its result.
255
+
256
+ If the future is already done when this method is called, raises
257
+ InvalidStateError.
258
+ """
259
+ if self._state != _PENDING:
260
+ raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
261
+ self._result = result
262
+ self._state = _FINISHED
263
+ self.__schedule_callbacks()
264
+
265
+ def set_exception(self, exception):
266
+ """Mark the future done and set an exception.
267
+
268
+ If the future is already done when this method is called, raises
269
+ InvalidStateError.
270
+ """
271
+ if self._state != _PENDING:
272
+ raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
273
+ if isinstance(exception, type):
274
+ exception = exception()
275
+ if type(exception) is StopIteration:
276
+ raise TypeError("StopIteration interacts badly with generators "
277
+ "and cannot be raised into a Future")
278
+ self._exception = exception
279
+ self._exception_tb = exception.__traceback__
280
+ self._state = _FINISHED
281
+ self.__schedule_callbacks()
282
+ self.__log_traceback = True
283
+
284
+ def __await__(self):
285
+ if not self.done():
286
+ self._asyncio_future_blocking = True
287
+ yield self # This tells Task to wait for completion.
288
+ if not self.done():
289
+ raise RuntimeError("await wasn't used with future")
290
+ return self.result() # May raise too.
291
+
292
+ __iter__ = __await__ # make compatible with 'yield from'.
293
+
294
+
295
+ # Needed for testing purposes.
296
+ _PyFuture = Future
297
+
298
+
299
+ def _get_loop(fut):
300
+ # Tries to call Future.get_loop() if it's available.
301
+ # Otherwise fallbacks to using the old '_loop' property.
302
+ try:
303
+ get_loop = fut.get_loop
304
+ except AttributeError:
305
+ pass
306
+ else:
307
+ return get_loop()
308
+ return fut._loop
309
+
310
+
311
+ def _set_result_unless_cancelled(fut, result):
312
+ """Helper setting the result only if the future was not cancelled."""
313
+ if fut.cancelled():
314
+ return
315
+ fut.set_result(result)
316
+
317
+
318
+ def _convert_future_exc(exc):
319
+ exc_class = type(exc)
320
+ if exc_class is concurrent.futures.CancelledError:
321
+ return exceptions.CancelledError(*exc.args)
322
+ elif exc_class is concurrent.futures.TimeoutError:
323
+ return exceptions.TimeoutError(*exc.args)
324
+ elif exc_class is concurrent.futures.InvalidStateError:
325
+ return exceptions.InvalidStateError(*exc.args)
326
+ else:
327
+ return exc
328
+
329
+
330
+ def _set_concurrent_future_state(concurrent, source):
331
+ """Copy state from a future to a concurrent.futures.Future."""
332
+ assert source.done()
333
+ if source.cancelled():
334
+ concurrent.cancel()
335
+ if not concurrent.set_running_or_notify_cancel():
336
+ return
337
+ exception = source.exception()
338
+ if exception is not None:
339
+ concurrent.set_exception(_convert_future_exc(exception))
340
+ else:
341
+ result = source.result()
342
+ concurrent.set_result(result)
343
+
344
+
345
+ def _copy_future_state(source, dest):
346
+ """Internal helper to copy state from another Future.
347
+
348
+ The other Future may be a concurrent.futures.Future.
349
+ """
350
+ assert source.done()
351
+ if dest.cancelled():
352
+ return
353
+ assert not dest.done()
354
+ if source.cancelled():
355
+ dest.cancel()
356
+ else:
357
+ exception = source.exception()
358
+ if exception is not None:
359
+ dest.set_exception(_convert_future_exc(exception))
360
+ else:
361
+ result = source.result()
362
+ dest.set_result(result)
363
+
364
+
365
+ def _chain_future(source, destination):
366
+ """Chain two futures so that when one completes, so does the other.
367
+
368
+ The result (or exception) of source will be copied to destination.
369
+ If destination is cancelled, source gets cancelled too.
370
+ Compatible with both asyncio.Future and concurrent.futures.Future.
371
+ """
372
+ if not isfuture(source) and not isinstance(source,
373
+ concurrent.futures.Future):
374
+ raise TypeError('A future is required for source argument')
375
+ if not isfuture(destination) and not isinstance(destination,
376
+ concurrent.futures.Future):
377
+ raise TypeError('A future is required for destination argument')
378
+ source_loop = _get_loop(source) if isfuture(source) else None
379
+ dest_loop = _get_loop(destination) if isfuture(destination) else None
380
+
381
+ def _set_state(future, other):
382
+ if isfuture(future):
383
+ _copy_future_state(other, future)
384
+ else:
385
+ _set_concurrent_future_state(future, other)
386
+
387
+ def _call_check_cancel(destination):
388
+ if destination.cancelled():
389
+ if source_loop is None or source_loop is dest_loop:
390
+ source.cancel()
391
+ else:
392
+ source_loop.call_soon_threadsafe(source.cancel)
393
+
394
+ def _call_set_state(source):
395
+ if (destination.cancelled() and
396
+ dest_loop is not None and dest_loop.is_closed()):
397
+ return
398
+ if dest_loop is None or dest_loop is source_loop:
399
+ _set_state(destination, source)
400
+ else:
401
+ if dest_loop.is_closed():
402
+ return
403
+ dest_loop.call_soon_threadsafe(_set_state, destination, source)
404
+
405
+ destination.add_done_callback(_call_check_cancel)
406
+ source.add_done_callback(_call_set_state)
407
+
408
+
409
+ def wrap_future(future, *, loop=None):
410
+ """Wrap concurrent.futures.Future object."""
411
+ if isfuture(future):
412
+ return future
413
+ assert isinstance(future, concurrent.futures.Future), \
414
+ f'concurrent.futures.Future is expected, got {future!r}'
415
+ if loop is None:
416
+ loop = events._get_event_loop()
417
+ new_future = loop.create_future()
418
+ _chain_future(future, new_future)
419
+ return new_future
420
+
421
+
422
+ try:
423
+ import _asyncio
424
+ except ImportError:
425
+ pass
426
+ else:
427
+ # _CFuture is needed for tests.
428
+ Future = _CFuture = _asyncio.Future
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/locks.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Synchronization primitives."""
2
+
3
+ __all__ = ('Lock', 'Event', 'Condition', 'Semaphore',
4
+ 'BoundedSemaphore', 'Barrier')
5
+
6
+ import collections
7
+ import enum
8
+
9
+ from . import exceptions
10
+ from . import mixins
11
+ from . import tasks
12
+
13
+ class _ContextManagerMixin:
14
+ async def __aenter__(self):
15
+ await self.acquire()
16
+ # We have no use for the "as ..." clause in the with
17
+ # statement for locks.
18
+ return None
19
+
20
+ async def __aexit__(self, exc_type, exc, tb):
21
+ self.release()
22
+
23
+
24
+ class Lock(_ContextManagerMixin, mixins._LoopBoundMixin):
25
+ """Primitive lock objects.
26
+
27
+ A primitive lock is a synchronization primitive that is not owned
28
+ by a particular coroutine when locked. A primitive lock is in one
29
+ of two states, 'locked' or 'unlocked'.
30
+
31
+ It is created in the unlocked state. It has two basic methods,
32
+ acquire() and release(). When the state is unlocked, acquire()
33
+ changes the state to locked and returns immediately. When the
34
+ state is locked, acquire() blocks until a call to release() in
35
+ another coroutine changes it to unlocked, then the acquire() call
36
+ resets it to locked and returns. The release() method should only
37
+ be called in the locked state; it changes the state to unlocked
38
+ and returns immediately. If an attempt is made to release an
39
+ unlocked lock, a RuntimeError will be raised.
40
+
41
+ When more than one coroutine is blocked in acquire() waiting for
42
+ the state to turn to unlocked, only one coroutine proceeds when a
43
+ release() call resets the state to unlocked; first coroutine which
44
+ is blocked in acquire() is being processed.
45
+
46
+ acquire() is a coroutine and should be called with 'await'.
47
+
48
+ Locks also support the asynchronous context management protocol.
49
+ 'async with lock' statement should be used.
50
+
51
+ Usage:
52
+
53
+ lock = Lock()
54
+ ...
55
+ await lock.acquire()
56
+ try:
57
+ ...
58
+ finally:
59
+ lock.release()
60
+
61
+ Context manager usage:
62
+
63
+ lock = Lock()
64
+ ...
65
+ async with lock:
66
+ ...
67
+
68
+ Lock objects can be tested for locking state:
69
+
70
+ if not lock.locked():
71
+ await lock.acquire()
72
+ else:
73
+ # lock is acquired
74
+ ...
75
+
76
+ """
77
+
78
+ def __init__(self):
79
+ self._waiters = None
80
+ self._locked = False
81
+
82
+ def __repr__(self):
83
+ res = super().__repr__()
84
+ extra = 'locked' if self._locked else 'unlocked'
85
+ if self._waiters:
86
+ extra = f'{extra}, waiters:{len(self._waiters)}'
87
+ return f'<{res[1:-1]} [{extra}]>'
88
+
89
+ def locked(self):
90
+ """Return True if lock is acquired."""
91
+ return self._locked
92
+
93
+ async def acquire(self):
94
+ """Acquire a lock.
95
+
96
+ This method blocks until the lock is unlocked, then sets it to
97
+ locked and returns True.
98
+ """
99
+ if (not self._locked and (self._waiters is None or
100
+ all(w.cancelled() for w in self._waiters))):
101
+ self._locked = True
102
+ return True
103
+
104
+ if self._waiters is None:
105
+ self._waiters = collections.deque()
106
+ fut = self._get_loop().create_future()
107
+ self._waiters.append(fut)
108
+
109
+ # Finally block should be called before the CancelledError
110
+ # handling as we don't want CancelledError to call
111
+ # _wake_up_first() and attempt to wake up itself.
112
+ try:
113
+ try:
114
+ await fut
115
+ finally:
116
+ self._waiters.remove(fut)
117
+ except exceptions.CancelledError:
118
+ if not self._locked:
119
+ self._wake_up_first()
120
+ raise
121
+
122
+ self._locked = True
123
+ return True
124
+
125
+ def release(self):
126
+ """Release a lock.
127
+
128
+ When the lock is locked, reset it to unlocked, and return.
129
+ If any other coroutines are blocked waiting for the lock to become
130
+ unlocked, allow exactly one of them to proceed.
131
+
132
+ When invoked on an unlocked lock, a RuntimeError is raised.
133
+
134
+ There is no return value.
135
+ """
136
+ if self._locked:
137
+ self._locked = False
138
+ self._wake_up_first()
139
+ else:
140
+ raise RuntimeError('Lock is not acquired.')
141
+
142
+ def _wake_up_first(self):
143
+ """Wake up the first waiter if it isn't done."""
144
+ if not self._waiters:
145
+ return
146
+ try:
147
+ fut = next(iter(self._waiters))
148
+ except StopIteration:
149
+ return
150
+
151
+ # .done() necessarily means that a waiter will wake up later on and
152
+ # either take the lock, or, if it was cancelled and lock wasn't
153
+ # taken already, will hit this again and wake up a new waiter.
154
+ if not fut.done():
155
+ fut.set_result(True)
156
+
157
+
158
+ class Event(mixins._LoopBoundMixin):
159
+ """Asynchronous equivalent to threading.Event.
160
+
161
+ Class implementing event objects. An event manages a flag that can be set
162
+ to true with the set() method and reset to false with the clear() method.
163
+ The wait() method blocks until the flag is true. The flag is initially
164
+ false.
165
+ """
166
+
167
+ def __init__(self):
168
+ self._waiters = collections.deque()
169
+ self._value = False
170
+
171
+ def __repr__(self):
172
+ res = super().__repr__()
173
+ extra = 'set' if self._value else 'unset'
174
+ if self._waiters:
175
+ extra = f'{extra}, waiters:{len(self._waiters)}'
176
+ return f'<{res[1:-1]} [{extra}]>'
177
+
178
+ def is_set(self):
179
+ """Return True if and only if the internal flag is true."""
180
+ return self._value
181
+
182
+ def set(self):
183
+ """Set the internal flag to true. All coroutines waiting for it to
184
+ become true are awakened. Coroutine that call wait() once the flag is
185
+ true will not block at all.
186
+ """
187
+ if not self._value:
188
+ self._value = True
189
+
190
+ for fut in self._waiters:
191
+ if not fut.done():
192
+ fut.set_result(True)
193
+
194
+ def clear(self):
195
+ """Reset the internal flag to false. Subsequently, coroutines calling
196
+ wait() will block until set() is called to set the internal flag
197
+ to true again."""
198
+ self._value = False
199
+
200
+ async def wait(self):
201
+ """Block until the internal flag is true.
202
+
203
+ If the internal flag is true on entry, return True
204
+ immediately. Otherwise, block until another coroutine calls
205
+ set() to set the flag to true, then return True.
206
+ """
207
+ if self._value:
208
+ return True
209
+
210
+ fut = self._get_loop().create_future()
211
+ self._waiters.append(fut)
212
+ try:
213
+ await fut
214
+ return True
215
+ finally:
216
+ self._waiters.remove(fut)
217
+
218
+
219
+ class Condition(_ContextManagerMixin, mixins._LoopBoundMixin):
220
+ """Asynchronous equivalent to threading.Condition.
221
+
222
+ This class implements condition variable objects. A condition variable
223
+ allows one or more coroutines to wait until they are notified by another
224
+ coroutine.
225
+
226
+ A new Lock object is created and used as the underlying lock.
227
+ """
228
+
229
+ def __init__(self, lock=None):
230
+ if lock is None:
231
+ lock = Lock()
232
+
233
+ self._lock = lock
234
+ # Export the lock's locked(), acquire() and release() methods.
235
+ self.locked = lock.locked
236
+ self.acquire = lock.acquire
237
+ self.release = lock.release
238
+
239
+ self._waiters = collections.deque()
240
+
241
+ def __repr__(self):
242
+ res = super().__repr__()
243
+ extra = 'locked' if self.locked() else 'unlocked'
244
+ if self._waiters:
245
+ extra = f'{extra}, waiters:{len(self._waiters)}'
246
+ return f'<{res[1:-1]} [{extra}]>'
247
+
248
+ async def wait(self):
249
+ """Wait until notified.
250
+
251
+ If the calling coroutine has not acquired the lock when this
252
+ method is called, a RuntimeError is raised.
253
+
254
+ This method releases the underlying lock, and then blocks
255
+ until it is awakened by a notify() or notify_all() call for
256
+ the same condition variable in another coroutine. Once
257
+ awakened, it re-acquires the lock and returns True.
258
+ """
259
+ if not self.locked():
260
+ raise RuntimeError('cannot wait on un-acquired lock')
261
+
262
+ self.release()
263
+ try:
264
+ fut = self._get_loop().create_future()
265
+ self._waiters.append(fut)
266
+ try:
267
+ await fut
268
+ return True
269
+ finally:
270
+ self._waiters.remove(fut)
271
+
272
+ finally:
273
+ # Must reacquire lock even if wait is cancelled
274
+ cancelled = False
275
+ while True:
276
+ try:
277
+ await self.acquire()
278
+ break
279
+ except exceptions.CancelledError:
280
+ cancelled = True
281
+
282
+ if cancelled:
283
+ raise exceptions.CancelledError
284
+
285
+ async def wait_for(self, predicate):
286
+ """Wait until a predicate becomes true.
287
+
288
+ The predicate should be a callable which result will be
289
+ interpreted as a boolean value. The final predicate value is
290
+ the return value.
291
+ """
292
+ result = predicate()
293
+ while not result:
294
+ await self.wait()
295
+ result = predicate()
296
+ return result
297
+
298
+ def notify(self, n=1):
299
+ """By default, wake up one coroutine waiting on this condition, if any.
300
+ If the calling coroutine has not acquired the lock when this method
301
+ is called, a RuntimeError is raised.
302
+
303
+ This method wakes up at most n of the coroutines waiting for the
304
+ condition variable; it is a no-op if no coroutines are waiting.
305
+
306
+ Note: an awakened coroutine does not actually return from its
307
+ wait() call until it can reacquire the lock. Since notify() does
308
+ not release the lock, its caller should.
309
+ """
310
+ if not self.locked():
311
+ raise RuntimeError('cannot notify on un-acquired lock')
312
+
313
+ idx = 0
314
+ for fut in self._waiters:
315
+ if idx >= n:
316
+ break
317
+
318
+ if not fut.done():
319
+ idx += 1
320
+ fut.set_result(False)
321
+
322
+ def notify_all(self):
323
+ """Wake up all threads waiting on this condition. This method acts
324
+ like notify(), but wakes up all waiting threads instead of one. If the
325
+ calling thread has not acquired the lock when this method is called,
326
+ a RuntimeError is raised.
327
+ """
328
+ self.notify(len(self._waiters))
329
+
330
+
331
+ class Semaphore(_ContextManagerMixin, mixins._LoopBoundMixin):
332
+ """A Semaphore implementation.
333
+
334
+ A semaphore manages an internal counter which is decremented by each
335
+ acquire() call and incremented by each release() call. The counter
336
+ can never go below zero; when acquire() finds that it is zero, it blocks,
337
+ waiting until some other thread calls release().
338
+
339
+ Semaphores also support the context management protocol.
340
+
341
+ The optional argument gives the initial value for the internal
342
+ counter; it defaults to 1. If the value given is less than 0,
343
+ ValueError is raised.
344
+ """
345
+
346
+ def __init__(self, value=1):
347
+ if value < 0:
348
+ raise ValueError("Semaphore initial value must be >= 0")
349
+ self._waiters = None
350
+ self._value = value
351
+
352
+ def __repr__(self):
353
+ res = super().__repr__()
354
+ extra = 'locked' if self.locked() else f'unlocked, value:{self._value}'
355
+ if self._waiters:
356
+ extra = f'{extra}, waiters:{len(self._waiters)}'
357
+ return f'<{res[1:-1]} [{extra}]>'
358
+
359
+ def locked(self):
360
+ """Returns True if semaphore cannot be acquired immediately."""
361
+ return self._value == 0 or (
362
+ any(not w.cancelled() for w in (self._waiters or ())))
363
+
364
+ async def acquire(self):
365
+ """Acquire a semaphore.
366
+
367
+ If the internal counter is larger than zero on entry,
368
+ decrement it by one and return True immediately. If it is
369
+ zero on entry, block, waiting until some other coroutine has
370
+ called release() to make it larger than 0, and then return
371
+ True.
372
+ """
373
+ if not self.locked():
374
+ self._value -= 1
375
+ return True
376
+
377
+ if self._waiters is None:
378
+ self._waiters = collections.deque()
379
+ fut = self._get_loop().create_future()
380
+ self._waiters.append(fut)
381
+
382
+ # Finally block should be called before the CancelledError
383
+ # handling as we don't want CancelledError to call
384
+ # _wake_up_first() and attempt to wake up itself.
385
+ try:
386
+ try:
387
+ await fut
388
+ finally:
389
+ self._waiters.remove(fut)
390
+ except exceptions.CancelledError:
391
+ if not fut.cancelled():
392
+ self._value += 1
393
+ self._wake_up_next()
394
+ raise
395
+
396
+ if self._value > 0:
397
+ self._wake_up_next()
398
+ return True
399
+
400
+ def release(self):
401
+ """Release a semaphore, incrementing the internal counter by one.
402
+
403
+ When it was zero on entry and another coroutine is waiting for it to
404
+ become larger than zero again, wake up that coroutine.
405
+ """
406
+ self._value += 1
407
+ self._wake_up_next()
408
+
409
+ def _wake_up_next(self):
410
+ """Wake up the first waiter that isn't done."""
411
+ if not self._waiters:
412
+ return
413
+
414
+ for fut in self._waiters:
415
+ if not fut.done():
416
+ self._value -= 1
417
+ fut.set_result(True)
418
+ return
419
+
420
+
421
+ class BoundedSemaphore(Semaphore):
422
+ """A bounded semaphore implementation.
423
+
424
+ This raises ValueError in release() if it would increase the value
425
+ above the initial value.
426
+ """
427
+
428
+ def __init__(self, value=1):
429
+ self._bound_value = value
430
+ super().__init__(value)
431
+
432
+ def release(self):
433
+ if self._value >= self._bound_value:
434
+ raise ValueError('BoundedSemaphore released too many times')
435
+ super().release()
436
+
437
+
438
+
439
+ class _BarrierState(enum.Enum):
440
+ FILLING = 'filling'
441
+ DRAINING = 'draining'
442
+ RESETTING = 'resetting'
443
+ BROKEN = 'broken'
444
+
445
+
446
+ class Barrier(mixins._LoopBoundMixin):
447
+ """Asyncio equivalent to threading.Barrier
448
+
449
+ Implements a Barrier primitive.
450
+ Useful for synchronizing a fixed number of tasks at known synchronization
451
+ points. Tasks block on 'wait()' and are simultaneously awoken once they
452
+ have all made their call.
453
+ """
454
+
455
+ def __init__(self, parties):
456
+ """Create a barrier, initialised to 'parties' tasks."""
457
+ if parties < 1:
458
+ raise ValueError('parties must be > 0')
459
+
460
+ self._cond = Condition() # notify all tasks when state changes
461
+
462
+ self._parties = parties
463
+ self._state = _BarrierState.FILLING
464
+ self._count = 0 # count tasks in Barrier
465
+
466
+ def __repr__(self):
467
+ res = super().__repr__()
468
+ extra = f'{self._state.value}'
469
+ if not self.broken:
470
+ extra += f', waiters:{self.n_waiting}/{self.parties}'
471
+ return f'<{res[1:-1]} [{extra}]>'
472
+
473
+ async def __aenter__(self):
474
+ # wait for the barrier reaches the parties number
475
+ # when start draining release and return index of waited task
476
+ return await self.wait()
477
+
478
+ async def __aexit__(self, *args):
479
+ pass
480
+
481
+ async def wait(self):
482
+ """Wait for the barrier.
483
+
484
+ When the specified number of tasks have started waiting, they are all
485
+ simultaneously awoken.
486
+ Returns an unique and individual index number from 0 to 'parties-1'.
487
+ """
488
+ async with self._cond:
489
+ await self._block() # Block while the barrier drains or resets.
490
+ try:
491
+ index = self._count
492
+ self._count += 1
493
+ if index + 1 == self._parties:
494
+ # We release the barrier
495
+ await self._release()
496
+ else:
497
+ await self._wait()
498
+ return index
499
+ finally:
500
+ self._count -= 1
501
+ # Wake up any tasks waiting for barrier to drain.
502
+ self._exit()
503
+
504
+ async def _block(self):
505
+ # Block until the barrier is ready for us,
506
+ # or raise an exception if it is broken.
507
+ #
508
+ # It is draining or resetting, wait until done
509
+ # unless a CancelledError occurs
510
+ await self._cond.wait_for(
511
+ lambda: self._state not in (
512
+ _BarrierState.DRAINING, _BarrierState.RESETTING
513
+ )
514
+ )
515
+
516
+ # see if the barrier is in a broken state
517
+ if self._state is _BarrierState.BROKEN:
518
+ raise exceptions.BrokenBarrierError("Barrier aborted")
519
+
520
+ async def _release(self):
521
+ # Release the tasks waiting in the barrier.
522
+
523
+ # Enter draining state.
524
+ # Next waiting tasks will be blocked until the end of draining.
525
+ self._state = _BarrierState.DRAINING
526
+ self._cond.notify_all()
527
+
528
+ async def _wait(self):
529
+ # Wait in the barrier until we are released. Raise an exception
530
+ # if the barrier is reset or broken.
531
+
532
+ # wait for end of filling
533
+ # unless a CancelledError occurs
534
+ await self._cond.wait_for(lambda: self._state is not _BarrierState.FILLING)
535
+
536
+ if self._state in (_BarrierState.BROKEN, _BarrierState.RESETTING):
537
+ raise exceptions.BrokenBarrierError("Abort or reset of barrier")
538
+
539
+ def _exit(self):
540
+ # If we are the last tasks to exit the barrier, signal any tasks
541
+ # waiting for the barrier to drain.
542
+ if self._count == 0:
543
+ if self._state in (_BarrierState.RESETTING, _BarrierState.DRAINING):
544
+ self._state = _BarrierState.FILLING
545
+ self._cond.notify_all()
546
+
547
+ async def reset(self):
548
+ """Reset the barrier to the initial state.
549
+
550
+ Any tasks currently waiting will get the BrokenBarrier exception
551
+ raised.
552
+ """
553
+ async with self._cond:
554
+ if self._count > 0:
555
+ if self._state is not _BarrierState.RESETTING:
556
+ #reset the barrier, waking up tasks
557
+ self._state = _BarrierState.RESETTING
558
+ else:
559
+ self._state = _BarrierState.FILLING
560
+ self._cond.notify_all()
561
+
562
+ async def abort(self):
563
+ """Place the barrier into a 'broken' state.
564
+
565
+ Useful in case of error. Any currently waiting tasks and tasks
566
+ attempting to 'wait()' will have BrokenBarrierError raised.
567
+ """
568
+ async with self._cond:
569
+ self._state = _BarrierState.BROKEN
570
+ self._cond.notify_all()
571
+
572
+ @property
573
+ def parties(self):
574
+ """Return the number of tasks required to trip the barrier."""
575
+ return self._parties
576
+
577
+ @property
578
+ def n_waiting(self):
579
+ """Return the number of tasks currently waiting at the barrier."""
580
+ if self._state is _BarrierState.FILLING:
581
+ return self._count
582
+ return 0
583
+
584
+ @property
585
+ def broken(self):
586
+ """Return True if the barrier is in a broken state."""
587
+ return self._state is _BarrierState.BROKEN
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/log.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Logging configuration."""
2
+
3
+ import logging
4
+
5
+
6
+ # Name the logger after the package.
7
+ logger = logging.getLogger(__package__)
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/mixins.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Event loop mixins."""
2
+
3
+ import threading
4
+ from . import events
5
+
6
+ _global_lock = threading.Lock()
7
+
8
+
9
+ class _LoopBoundMixin:
10
+ _loop = None
11
+
12
+ def _get_loop(self):
13
+ loop = events._get_running_loop()
14
+
15
+ if self._loop is None:
16
+ with _global_lock:
17
+ if self._loop is None:
18
+ self._loop = loop
19
+ if loop is not self._loop:
20
+ raise RuntimeError(f'{self!r} is bound to a different event loop')
21
+ return loop
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/proactor_events.py ADDED
@@ -0,0 +1,894 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Event loop using a proactor and related classes.
2
+
3
+ A proactor is a "notify-on-completion" multiplexer. Currently a
4
+ proactor is only implemented on Windows with IOCP.
5
+ """
6
+
7
+ __all__ = 'BaseProactorEventLoop',
8
+
9
+ import io
10
+ import os
11
+ import socket
12
+ import warnings
13
+ import signal
14
+ import threading
15
+ import collections
16
+
17
+ from . import base_events
18
+ from . import constants
19
+ from . import futures
20
+ from . import exceptions
21
+ from . import protocols
22
+ from . import sslproto
23
+ from . import transports
24
+ from . import trsock
25
+ from .log import logger
26
+
27
+
28
+ def _set_socket_extra(transport, sock):
29
+ transport._extra['socket'] = trsock.TransportSocket(sock)
30
+
31
+ try:
32
+ transport._extra['sockname'] = sock.getsockname()
33
+ except socket.error:
34
+ if transport._loop.get_debug():
35
+ logger.warning(
36
+ "getsockname() failed on %r", sock, exc_info=True)
37
+
38
+ if 'peername' not in transport._extra:
39
+ try:
40
+ transport._extra['peername'] = sock.getpeername()
41
+ except socket.error:
42
+ # UDP sockets may not have a peer name
43
+ transport._extra['peername'] = None
44
+
45
+
46
+ class _ProactorBasePipeTransport(transports._FlowControlMixin,
47
+ transports.BaseTransport):
48
+ """Base class for pipe and socket transports."""
49
+
50
+ def __init__(self, loop, sock, protocol, waiter=None,
51
+ extra=None, server=None):
52
+ super().__init__(extra, loop)
53
+ self._set_extra(sock)
54
+ self._sock = sock
55
+ self.set_protocol(protocol)
56
+ self._server = server
57
+ self._buffer = None # None or bytearray.
58
+ self._read_fut = None
59
+ self._write_fut = None
60
+ self._pending_write = 0
61
+ self._conn_lost = 0
62
+ self._closing = False # Set when close() called.
63
+ self._called_connection_lost = False
64
+ self._eof_written = False
65
+ if self._server is not None:
66
+ self._server._attach()
67
+ self._loop.call_soon(self._protocol.connection_made, self)
68
+ if waiter is not None:
69
+ # only wake up the waiter when connection_made() has been called
70
+ self._loop.call_soon(futures._set_result_unless_cancelled,
71
+ waiter, None)
72
+
73
+ def __repr__(self):
74
+ info = [self.__class__.__name__]
75
+ if self._sock is None:
76
+ info.append('closed')
77
+ elif self._closing:
78
+ info.append('closing')
79
+ if self._sock is not None:
80
+ info.append(f'fd={self._sock.fileno()}')
81
+ if self._read_fut is not None:
82
+ info.append(f'read={self._read_fut!r}')
83
+ if self._write_fut is not None:
84
+ info.append(f'write={self._write_fut!r}')
85
+ if self._buffer:
86
+ info.append(f'write_bufsize={len(self._buffer)}')
87
+ if self._eof_written:
88
+ info.append('EOF written')
89
+ return '<{}>'.format(' '.join(info))
90
+
91
+ def _set_extra(self, sock):
92
+ self._extra['pipe'] = sock
93
+
94
+ def set_protocol(self, protocol):
95
+ self._protocol = protocol
96
+
97
+ def get_protocol(self):
98
+ return self._protocol
99
+
100
+ def is_closing(self):
101
+ return self._closing
102
+
103
+ def close(self):
104
+ if self._closing:
105
+ return
106
+ self._closing = True
107
+ self._conn_lost += 1
108
+ if not self._buffer and self._write_fut is None:
109
+ self._loop.call_soon(self._call_connection_lost, None)
110
+ if self._read_fut is not None:
111
+ self._read_fut.cancel()
112
+ self._read_fut = None
113
+
114
+ def __del__(self, _warn=warnings.warn):
115
+ if self._sock is not None:
116
+ _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
117
+ self._sock.close()
118
+
119
+ def _fatal_error(self, exc, message='Fatal error on pipe transport'):
120
+ try:
121
+ if isinstance(exc, OSError):
122
+ if self._loop.get_debug():
123
+ logger.debug("%r: %s", self, message, exc_info=True)
124
+ else:
125
+ self._loop.call_exception_handler({
126
+ 'message': message,
127
+ 'exception': exc,
128
+ 'transport': self,
129
+ 'protocol': self._protocol,
130
+ })
131
+ finally:
132
+ self._force_close(exc)
133
+
134
+ def _force_close(self, exc):
135
+ if self._empty_waiter is not None and not self._empty_waiter.done():
136
+ if exc is None:
137
+ self._empty_waiter.set_result(None)
138
+ else:
139
+ self._empty_waiter.set_exception(exc)
140
+ if self._closing and self._called_connection_lost:
141
+ return
142
+ self._closing = True
143
+ self._conn_lost += 1
144
+ if self._write_fut:
145
+ self._write_fut.cancel()
146
+ self._write_fut = None
147
+ if self._read_fut:
148
+ self._read_fut.cancel()
149
+ self._read_fut = None
150
+ self._pending_write = 0
151
+ self._buffer = None
152
+ self._loop.call_soon(self._call_connection_lost, exc)
153
+
154
+ def _call_connection_lost(self, exc):
155
+ if self._called_connection_lost:
156
+ return
157
+ try:
158
+ self._protocol.connection_lost(exc)
159
+ finally:
160
+ # XXX If there is a pending overlapped read on the other
161
+ # end then it may fail with ERROR_NETNAME_DELETED if we
162
+ # just close our end. First calling shutdown() seems to
163
+ # cure it, but maybe using DisconnectEx() would be better.
164
+ if hasattr(self._sock, 'shutdown') and self._sock.fileno() != -1:
165
+ self._sock.shutdown(socket.SHUT_RDWR)
166
+ self._sock.close()
167
+ self._sock = None
168
+ server = self._server
169
+ if server is not None:
170
+ server._detach()
171
+ self._server = None
172
+ self._called_connection_lost = True
173
+
174
+ def get_write_buffer_size(self):
175
+ size = self._pending_write
176
+ if self._buffer is not None:
177
+ size += len(self._buffer)
178
+ return size
179
+
180
+
181
+ class _ProactorReadPipeTransport(_ProactorBasePipeTransport,
182
+ transports.ReadTransport):
183
+ """Transport for read pipes."""
184
+
185
+ def __init__(self, loop, sock, protocol, waiter=None,
186
+ extra=None, server=None, buffer_size=65536):
187
+ self._pending_data_length = -1
188
+ self._paused = True
189
+ super().__init__(loop, sock, protocol, waiter, extra, server)
190
+
191
+ self._data = bytearray(buffer_size)
192
+ self._loop.call_soon(self._loop_reading)
193
+ self._paused = False
194
+
195
+ def is_reading(self):
196
+ return not self._paused and not self._closing
197
+
198
+ def pause_reading(self):
199
+ if self._closing or self._paused:
200
+ return
201
+ self._paused = True
202
+
203
+ # bpo-33694: Don't cancel self._read_fut because cancelling an
204
+ # overlapped WSASend() loss silently data with the current proactor
205
+ # implementation.
206
+ #
207
+ # If CancelIoEx() fails with ERROR_NOT_FOUND, it means that WSASend()
208
+ # completed (even if HasOverlappedIoCompleted() returns 0), but
209
+ # Overlapped.cancel() currently silently ignores the ERROR_NOT_FOUND
210
+ # error. Once the overlapped is ignored, the IOCP loop will ignores the
211
+ # completion I/O event and so not read the result of the overlapped
212
+ # WSARecv().
213
+
214
+ if self._loop.get_debug():
215
+ logger.debug("%r pauses reading", self)
216
+
217
+ def resume_reading(self):
218
+ if self._closing or not self._paused:
219
+ return
220
+
221
+ self._paused = False
222
+ if self._read_fut is None:
223
+ self._loop.call_soon(self._loop_reading, None)
224
+
225
+ length = self._pending_data_length
226
+ self._pending_data_length = -1
227
+ if length > -1:
228
+ # Call the protocol method after calling _loop_reading(),
229
+ # since the protocol can decide to pause reading again.
230
+ self._loop.call_soon(self._data_received, self._data[:length], length)
231
+
232
+ if self._loop.get_debug():
233
+ logger.debug("%r resumes reading", self)
234
+
235
+ def _eof_received(self):
236
+ if self._loop.get_debug():
237
+ logger.debug("%r received EOF", self)
238
+
239
+ try:
240
+ keep_open = self._protocol.eof_received()
241
+ except (SystemExit, KeyboardInterrupt):
242
+ raise
243
+ except BaseException as exc:
244
+ self._fatal_error(
245
+ exc, 'Fatal error: protocol.eof_received() call failed.')
246
+ return
247
+
248
+ if not keep_open:
249
+ self.close()
250
+
251
+ def _data_received(self, data, length):
252
+ if self._paused:
253
+ # Don't call any protocol method while reading is paused.
254
+ # The protocol will be called on resume_reading().
255
+ assert self._pending_data_length == -1
256
+ self._pending_data_length = length
257
+ return
258
+
259
+ if length == 0:
260
+ self._eof_received()
261
+ return
262
+
263
+ if isinstance(self._protocol, protocols.BufferedProtocol):
264
+ try:
265
+ protocols._feed_data_to_buffered_proto(self._protocol, data)
266
+ except (SystemExit, KeyboardInterrupt):
267
+ raise
268
+ except BaseException as exc:
269
+ self._fatal_error(exc,
270
+ 'Fatal error: protocol.buffer_updated() '
271
+ 'call failed.')
272
+ return
273
+ else:
274
+ self._protocol.data_received(data)
275
+
276
+ def _loop_reading(self, fut=None):
277
+ length = -1
278
+ data = None
279
+ try:
280
+ if fut is not None:
281
+ assert self._read_fut is fut or (self._read_fut is None and
282
+ self._closing)
283
+ self._read_fut = None
284
+ if fut.done():
285
+ # deliver data later in "finally" clause
286
+ length = fut.result()
287
+ if length == 0:
288
+ # we got end-of-file so no need to reschedule a new read
289
+ return
290
+
291
+ data = self._data[:length]
292
+ else:
293
+ # the future will be replaced by next proactor.recv call
294
+ fut.cancel()
295
+
296
+ if self._closing:
297
+ # since close() has been called we ignore any read data
298
+ return
299
+
300
+ # bpo-33694: buffer_updated() has currently no fast path because of
301
+ # a data loss issue caused by overlapped WSASend() cancellation.
302
+
303
+ if not self._paused:
304
+ # reschedule a new read
305
+ self._read_fut = self._loop._proactor.recv_into(self._sock, self._data)
306
+ except ConnectionAbortedError as exc:
307
+ if not self._closing:
308
+ self._fatal_error(exc, 'Fatal read error on pipe transport')
309
+ elif self._loop.get_debug():
310
+ logger.debug("Read error on pipe transport while closing",
311
+ exc_info=True)
312
+ except ConnectionResetError as exc:
313
+ self._force_close(exc)
314
+ except OSError as exc:
315
+ self._fatal_error(exc, 'Fatal read error on pipe transport')
316
+ except exceptions.CancelledError:
317
+ if not self._closing:
318
+ raise
319
+ else:
320
+ if not self._paused:
321
+ self._read_fut.add_done_callback(self._loop_reading)
322
+ finally:
323
+ if length > -1:
324
+ self._data_received(data, length)
325
+
326
+
327
+ class _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport,
328
+ transports.WriteTransport):
329
+ """Transport for write pipes."""
330
+
331
+ _start_tls_compatible = True
332
+
333
+ def __init__(self, *args, **kw):
334
+ super().__init__(*args, **kw)
335
+ self._empty_waiter = None
336
+
337
+ def write(self, data):
338
+ if not isinstance(data, (bytes, bytearray, memoryview)):
339
+ raise TypeError(
340
+ f"data argument must be a bytes-like object, "
341
+ f"not {type(data).__name__}")
342
+ if self._eof_written:
343
+ raise RuntimeError('write_eof() already called')
344
+ if self._empty_waiter is not None:
345
+ raise RuntimeError('unable to write; sendfile is in progress')
346
+
347
+ if not data:
348
+ return
349
+
350
+ if self._conn_lost:
351
+ if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
352
+ logger.warning('socket.send() raised exception.')
353
+ self._conn_lost += 1
354
+ return
355
+
356
+ # Observable states:
357
+ # 1. IDLE: _write_fut and _buffer both None
358
+ # 2. WRITING: _write_fut set; _buffer None
359
+ # 3. BACKED UP: _write_fut set; _buffer a bytearray
360
+ # We always copy the data, so the caller can't modify it
361
+ # while we're still waiting for the I/O to happen.
362
+ if self._write_fut is None: # IDLE -> WRITING
363
+ assert self._buffer is None
364
+ # Pass a copy, except if it's already immutable.
365
+ self._loop_writing(data=bytes(data))
366
+ elif not self._buffer: # WRITING -> BACKED UP
367
+ # Make a mutable copy which we can extend.
368
+ self._buffer = bytearray(data)
369
+ self._maybe_pause_protocol()
370
+ else: # BACKED UP
371
+ # Append to buffer (also copies).
372
+ self._buffer.extend(data)
373
+ self._maybe_pause_protocol()
374
+
375
+ def _loop_writing(self, f=None, data=None):
376
+ try:
377
+ if f is not None and self._write_fut is None and self._closing:
378
+ # XXX most likely self._force_close() has been called, and
379
+ # it has set self._write_fut to None.
380
+ return
381
+ assert f is self._write_fut
382
+ self._write_fut = None
383
+ self._pending_write = 0
384
+ if f:
385
+ f.result()
386
+ if data is None:
387
+ data = self._buffer
388
+ self._buffer = None
389
+ if not data:
390
+ if self._closing:
391
+ self._loop.call_soon(self._call_connection_lost, None)
392
+ if self._eof_written:
393
+ self._sock.shutdown(socket.SHUT_WR)
394
+ # Now that we've reduced the buffer size, tell the
395
+ # protocol to resume writing if it was paused. Note that
396
+ # we do this last since the callback is called immediately
397
+ # and it may add more data to the buffer (even causing the
398
+ # protocol to be paused again).
399
+ self._maybe_resume_protocol()
400
+ else:
401
+ self._write_fut = self._loop._proactor.send(self._sock, data)
402
+ if not self._write_fut.done():
403
+ assert self._pending_write == 0
404
+ self._pending_write = len(data)
405
+ self._write_fut.add_done_callback(self._loop_writing)
406
+ self._maybe_pause_protocol()
407
+ else:
408
+ self._write_fut.add_done_callback(self._loop_writing)
409
+ if self._empty_waiter is not None and self._write_fut is None:
410
+ self._empty_waiter.set_result(None)
411
+ except ConnectionResetError as exc:
412
+ self._force_close(exc)
413
+ except OSError as exc:
414
+ self._fatal_error(exc, 'Fatal write error on pipe transport')
415
+
416
+ def can_write_eof(self):
417
+ return True
418
+
419
+ def write_eof(self):
420
+ self.close()
421
+
422
+ def abort(self):
423
+ self._force_close(None)
424
+
425
+ def _make_empty_waiter(self):
426
+ if self._empty_waiter is not None:
427
+ raise RuntimeError("Empty waiter is already set")
428
+ self._empty_waiter = self._loop.create_future()
429
+ if self._write_fut is None:
430
+ self._empty_waiter.set_result(None)
431
+ return self._empty_waiter
432
+
433
+ def _reset_empty_waiter(self):
434
+ self._empty_waiter = None
435
+
436
+
437
+ class _ProactorWritePipeTransport(_ProactorBaseWritePipeTransport):
438
+ def __init__(self, *args, **kw):
439
+ super().__init__(*args, **kw)
440
+ self._read_fut = self._loop._proactor.recv(self._sock, 16)
441
+ self._read_fut.add_done_callback(self._pipe_closed)
442
+
443
+ def _pipe_closed(self, fut):
444
+ if fut.cancelled():
445
+ # the transport has been closed
446
+ return
447
+ assert fut.result() == b''
448
+ if self._closing:
449
+ assert self._read_fut is None
450
+ return
451
+ assert fut is self._read_fut, (fut, self._read_fut)
452
+ self._read_fut = None
453
+ if self._write_fut is not None:
454
+ self._force_close(BrokenPipeError())
455
+ else:
456
+ self.close()
457
+
458
+
459
+ class _ProactorDatagramTransport(_ProactorBasePipeTransport,
460
+ transports.DatagramTransport):
461
+ max_size = 256 * 1024
462
+ def __init__(self, loop, sock, protocol, address=None,
463
+ waiter=None, extra=None):
464
+ self._address = address
465
+ self._empty_waiter = None
466
+ self._buffer_size = 0
467
+ # We don't need to call _protocol.connection_made() since our base
468
+ # constructor does it for us.
469
+ super().__init__(loop, sock, protocol, waiter=waiter, extra=extra)
470
+
471
+ # The base constructor sets _buffer = None, so we set it here
472
+ self._buffer = collections.deque()
473
+ self._loop.call_soon(self._loop_reading)
474
+
475
+ def _set_extra(self, sock):
476
+ _set_socket_extra(self, sock)
477
+
478
+ def get_write_buffer_size(self):
479
+ return self._buffer_size
480
+
481
+ def abort(self):
482
+ self._force_close(None)
483
+
484
+ def sendto(self, data, addr=None):
485
+ if not isinstance(data, (bytes, bytearray, memoryview)):
486
+ raise TypeError('data argument must be bytes-like object (%r)',
487
+ type(data))
488
+
489
+ if not data:
490
+ return
491
+
492
+ if self._address is not None and addr not in (None, self._address):
493
+ raise ValueError(
494
+ f'Invalid address: must be None or {self._address}')
495
+
496
+ if self._conn_lost and self._address:
497
+ if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
498
+ logger.warning('socket.sendto() raised exception.')
499
+ self._conn_lost += 1
500
+ return
501
+
502
+ # Ensure that what we buffer is immutable.
503
+ self._buffer.append((bytes(data), addr))
504
+ self._buffer_size += len(data)
505
+
506
+ if self._write_fut is None:
507
+ # No current write operations are active, kick one off
508
+ self._loop_writing()
509
+ # else: A write operation is already kicked off
510
+
511
+ self._maybe_pause_protocol()
512
+
513
+ def _loop_writing(self, fut=None):
514
+ try:
515
+ if self._conn_lost:
516
+ return
517
+
518
+ assert fut is self._write_fut
519
+ self._write_fut = None
520
+ if fut:
521
+ # We are in a _loop_writing() done callback, get the result
522
+ fut.result()
523
+
524
+ if not self._buffer or (self._conn_lost and self._address):
525
+ # The connection has been closed
526
+ if self._closing:
527
+ self._loop.call_soon(self._call_connection_lost, None)
528
+ return
529
+
530
+ data, addr = self._buffer.popleft()
531
+ self._buffer_size -= len(data)
532
+ if self._address is not None:
533
+ self._write_fut = self._loop._proactor.send(self._sock,
534
+ data)
535
+ else:
536
+ self._write_fut = self._loop._proactor.sendto(self._sock,
537
+ data,
538
+ addr=addr)
539
+ except OSError as exc:
540
+ self._protocol.error_received(exc)
541
+ except Exception as exc:
542
+ self._fatal_error(exc, 'Fatal write error on datagram transport')
543
+ else:
544
+ self._write_fut.add_done_callback(self._loop_writing)
545
+ self._maybe_resume_protocol()
546
+
547
+ def _loop_reading(self, fut=None):
548
+ data = None
549
+ try:
550
+ if self._conn_lost:
551
+ return
552
+
553
+ assert self._read_fut is fut or (self._read_fut is None and
554
+ self._closing)
555
+
556
+ self._read_fut = None
557
+ if fut is not None:
558
+ res = fut.result()
559
+
560
+ if self._closing:
561
+ # since close() has been called we ignore any read data
562
+ data = None
563
+ return
564
+
565
+ if self._address is not None:
566
+ data, addr = res, self._address
567
+ else:
568
+ data, addr = res
569
+
570
+ if self._conn_lost:
571
+ return
572
+ if self._address is not None:
573
+ self._read_fut = self._loop._proactor.recv(self._sock,
574
+ self.max_size)
575
+ else:
576
+ self._read_fut = self._loop._proactor.recvfrom(self._sock,
577
+ self.max_size)
578
+ except OSError as exc:
579
+ self._protocol.error_received(exc)
580
+ except exceptions.CancelledError:
581
+ if not self._closing:
582
+ raise
583
+ else:
584
+ if self._read_fut is not None:
585
+ self._read_fut.add_done_callback(self._loop_reading)
586
+ finally:
587
+ if data:
588
+ self._protocol.datagram_received(data, addr)
589
+
590
+
591
+ class _ProactorDuplexPipeTransport(_ProactorReadPipeTransport,
592
+ _ProactorBaseWritePipeTransport,
593
+ transports.Transport):
594
+ """Transport for duplex pipes."""
595
+
596
+ def can_write_eof(self):
597
+ return False
598
+
599
+ def write_eof(self):
600
+ raise NotImplementedError
601
+
602
+
603
+ class _ProactorSocketTransport(_ProactorReadPipeTransport,
604
+ _ProactorBaseWritePipeTransport,
605
+ transports.Transport):
606
+ """Transport for connected sockets."""
607
+
608
+ _sendfile_compatible = constants._SendfileMode.TRY_NATIVE
609
+
610
+ def __init__(self, loop, sock, protocol, waiter=None,
611
+ extra=None, server=None):
612
+ super().__init__(loop, sock, protocol, waiter, extra, server)
613
+ base_events._set_nodelay(sock)
614
+
615
+ def _set_extra(self, sock):
616
+ _set_socket_extra(self, sock)
617
+
618
+ def can_write_eof(self):
619
+ return True
620
+
621
+ def write_eof(self):
622
+ if self._closing or self._eof_written:
623
+ return
624
+ self._eof_written = True
625
+ if self._write_fut is None:
626
+ self._sock.shutdown(socket.SHUT_WR)
627
+
628
+
629
+ class BaseProactorEventLoop(base_events.BaseEventLoop):
630
+
631
+ def __init__(self, proactor):
632
+ super().__init__()
633
+ logger.debug('Using proactor: %s', proactor.__class__.__name__)
634
+ self._proactor = proactor
635
+ self._selector = proactor # convenient alias
636
+ self._self_reading_future = None
637
+ self._accept_futures = {} # socket file descriptor => Future
638
+ proactor.set_loop(self)
639
+ self._make_self_pipe()
640
+ if threading.current_thread() is threading.main_thread():
641
+ # wakeup fd can only be installed to a file descriptor from the main thread
642
+ signal.set_wakeup_fd(self._csock.fileno())
643
+
644
+ def _make_socket_transport(self, sock, protocol, waiter=None,
645
+ extra=None, server=None):
646
+ return _ProactorSocketTransport(self, sock, protocol, waiter,
647
+ extra, server)
648
+
649
+ def _make_ssl_transport(
650
+ self, rawsock, protocol, sslcontext, waiter=None,
651
+ *, server_side=False, server_hostname=None,
652
+ extra=None, server=None,
653
+ ssl_handshake_timeout=None,
654
+ ssl_shutdown_timeout=None):
655
+ ssl_protocol = sslproto.SSLProtocol(
656
+ self, protocol, sslcontext, waiter,
657
+ server_side, server_hostname,
658
+ ssl_handshake_timeout=ssl_handshake_timeout,
659
+ ssl_shutdown_timeout=ssl_shutdown_timeout)
660
+ _ProactorSocketTransport(self, rawsock, ssl_protocol,
661
+ extra=extra, server=server)
662
+ return ssl_protocol._app_transport
663
+
664
+ def _make_datagram_transport(self, sock, protocol,
665
+ address=None, waiter=None, extra=None):
666
+ return _ProactorDatagramTransport(self, sock, protocol, address,
667
+ waiter, extra)
668
+
669
+ def _make_duplex_pipe_transport(self, sock, protocol, waiter=None,
670
+ extra=None):
671
+ return _ProactorDuplexPipeTransport(self,
672
+ sock, protocol, waiter, extra)
673
+
674
+ def _make_read_pipe_transport(self, sock, protocol, waiter=None,
675
+ extra=None):
676
+ return _ProactorReadPipeTransport(self, sock, protocol, waiter, extra)
677
+
678
+ def _make_write_pipe_transport(self, sock, protocol, waiter=None,
679
+ extra=None):
680
+ # We want connection_lost() to be called when other end closes
681
+ return _ProactorWritePipeTransport(self,
682
+ sock, protocol, waiter, extra)
683
+
684
+ def close(self):
685
+ if self.is_running():
686
+ raise RuntimeError("Cannot close a running event loop")
687
+ if self.is_closed():
688
+ return
689
+
690
+ if threading.current_thread() is threading.main_thread():
691
+ signal.set_wakeup_fd(-1)
692
+ # Call these methods before closing the event loop (before calling
693
+ # BaseEventLoop.close), because they can schedule callbacks with
694
+ # call_soon(), which is forbidden when the event loop is closed.
695
+ self._stop_accept_futures()
696
+ self._close_self_pipe()
697
+ self._proactor.close()
698
+ self._proactor = None
699
+ self._selector = None
700
+
701
+ # Close the event loop
702
+ super().close()
703
+
704
+ async def sock_recv(self, sock, n):
705
+ return await self._proactor.recv(sock, n)
706
+
707
+ async def sock_recv_into(self, sock, buf):
708
+ return await self._proactor.recv_into(sock, buf)
709
+
710
+ async def sock_recvfrom(self, sock, bufsize):
711
+ return await self._proactor.recvfrom(sock, bufsize)
712
+
713
+ async def sock_recvfrom_into(self, sock, buf, nbytes=0):
714
+ if not nbytes:
715
+ nbytes = len(buf)
716
+
717
+ return await self._proactor.recvfrom_into(sock, buf, nbytes)
718
+
719
+ async def sock_sendall(self, sock, data):
720
+ return await self._proactor.send(sock, data)
721
+
722
+ async def sock_sendto(self, sock, data, address):
723
+ return await self._proactor.sendto(sock, data, 0, address)
724
+
725
+ async def sock_connect(self, sock, address):
726
+ return await self._proactor.connect(sock, address)
727
+
728
+ async def sock_accept(self, sock):
729
+ return await self._proactor.accept(sock)
730
+
731
+ async def _sock_sendfile_native(self, sock, file, offset, count):
732
+ try:
733
+ fileno = file.fileno()
734
+ except (AttributeError, io.UnsupportedOperation) as err:
735
+ raise exceptions.SendfileNotAvailableError("not a regular file")
736
+ try:
737
+ fsize = os.fstat(fileno).st_size
738
+ except OSError:
739
+ raise exceptions.SendfileNotAvailableError("not a regular file")
740
+ blocksize = count if count else fsize
741
+ if not blocksize:
742
+ return 0 # empty file
743
+
744
+ blocksize = min(blocksize, 0xffff_ffff)
745
+ end_pos = min(offset + count, fsize) if count else fsize
746
+ offset = min(offset, fsize)
747
+ total_sent = 0
748
+ try:
749
+ while True:
750
+ blocksize = min(end_pos - offset, blocksize)
751
+ if blocksize <= 0:
752
+ return total_sent
753
+ await self._proactor.sendfile(sock, file, offset, blocksize)
754
+ offset += blocksize
755
+ total_sent += blocksize
756
+ finally:
757
+ if total_sent > 0:
758
+ file.seek(offset)
759
+
760
+ async def _sendfile_native(self, transp, file, offset, count):
761
+ resume_reading = transp.is_reading()
762
+ transp.pause_reading()
763
+ await transp._make_empty_waiter()
764
+ try:
765
+ return await self.sock_sendfile(transp._sock, file, offset, count,
766
+ fallback=False)
767
+ finally:
768
+ transp._reset_empty_waiter()
769
+ if resume_reading:
770
+ transp.resume_reading()
771
+
772
+ def _close_self_pipe(self):
773
+ if self._self_reading_future is not None:
774
+ self._self_reading_future.cancel()
775
+ self._self_reading_future = None
776
+ self._ssock.close()
777
+ self._ssock = None
778
+ self._csock.close()
779
+ self._csock = None
780
+ self._internal_fds -= 1
781
+
782
+ def _make_self_pipe(self):
783
+ # A self-socket, really. :-)
784
+ self._ssock, self._csock = socket.socketpair()
785
+ self._ssock.setblocking(False)
786
+ self._csock.setblocking(False)
787
+ self._internal_fds += 1
788
+
789
+ def _loop_self_reading(self, f=None):
790
+ try:
791
+ if f is not None:
792
+ f.result() # may raise
793
+ if self._self_reading_future is not f:
794
+ # When we scheduled this Future, we assigned it to
795
+ # _self_reading_future. If it's not there now, something has
796
+ # tried to cancel the loop while this callback was still in the
797
+ # queue (see windows_events.ProactorEventLoop.run_forever). In
798
+ # that case stop here instead of continuing to schedule a new
799
+ # iteration.
800
+ return
801
+ f = self._proactor.recv(self._ssock, 4096)
802
+ except exceptions.CancelledError:
803
+ # _close_self_pipe() has been called, stop waiting for data
804
+ return
805
+ except (SystemExit, KeyboardInterrupt):
806
+ raise
807
+ except BaseException as exc:
808
+ self.call_exception_handler({
809
+ 'message': 'Error on reading from the event loop self pipe',
810
+ 'exception': exc,
811
+ 'loop': self,
812
+ })
813
+ else:
814
+ self._self_reading_future = f
815
+ f.add_done_callback(self._loop_self_reading)
816
+
817
+ def _write_to_self(self):
818
+ # This may be called from a different thread, possibly after
819
+ # _close_self_pipe() has been called or even while it is
820
+ # running. Guard for self._csock being None or closed. When
821
+ # a socket is closed, send() raises OSError (with errno set to
822
+ # EBADF, but let's not rely on the exact error code).
823
+ csock = self._csock
824
+ if csock is None:
825
+ return
826
+
827
+ try:
828
+ csock.send(b'\0')
829
+ except OSError:
830
+ if self._debug:
831
+ logger.debug("Fail to write a null byte into the "
832
+ "self-pipe socket",
833
+ exc_info=True)
834
+
835
+ def _start_serving(self, protocol_factory, sock,
836
+ sslcontext=None, server=None, backlog=100,
837
+ ssl_handshake_timeout=None,
838
+ ssl_shutdown_timeout=None):
839
+
840
+ def loop(f=None):
841
+ try:
842
+ if f is not None:
843
+ conn, addr = f.result()
844
+ if self._debug:
845
+ logger.debug("%r got a new connection from %r: %r",
846
+ server, addr, conn)
847
+ protocol = protocol_factory()
848
+ if sslcontext is not None:
849
+ self._make_ssl_transport(
850
+ conn, protocol, sslcontext, server_side=True,
851
+ extra={'peername': addr}, server=server,
852
+ ssl_handshake_timeout=ssl_handshake_timeout,
853
+ ssl_shutdown_timeout=ssl_shutdown_timeout)
854
+ else:
855
+ self._make_socket_transport(
856
+ conn, protocol,
857
+ extra={'peername': addr}, server=server)
858
+ if self.is_closed():
859
+ return
860
+ f = self._proactor.accept(sock)
861
+ except OSError as exc:
862
+ if sock.fileno() != -1:
863
+ self.call_exception_handler({
864
+ 'message': 'Accept failed on a socket',
865
+ 'exception': exc,
866
+ 'socket': trsock.TransportSocket(sock),
867
+ })
868
+ sock.close()
869
+ elif self._debug:
870
+ logger.debug("Accept failed on socket %r",
871
+ sock, exc_info=True)
872
+ except exceptions.CancelledError:
873
+ sock.close()
874
+ else:
875
+ self._accept_futures[sock.fileno()] = f
876
+ f.add_done_callback(loop)
877
+
878
+ self.call_soon(loop)
879
+
880
+ def _process_events(self, event_list):
881
+ # Events are processed in the IocpProactor._poll() method
882
+ pass
883
+
884
+ def _stop_accept_futures(self):
885
+ for future in self._accept_futures.values():
886
+ future.cancel()
887
+ self._accept_futures.clear()
888
+
889
+ def _stop_serving(self, sock):
890
+ future = self._accept_futures.pop(sock.fileno(), None)
891
+ if future:
892
+ future.cancel()
893
+ self._proactor._stop_serving(sock)
894
+ sock.close()
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/protocols.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Abstract Protocol base classes."""
2
+
3
+ __all__ = (
4
+ 'BaseProtocol', 'Protocol', 'DatagramProtocol',
5
+ 'SubprocessProtocol', 'BufferedProtocol',
6
+ )
7
+
8
+
9
+ class BaseProtocol:
10
+ """Common base class for protocol interfaces.
11
+
12
+ Usually user implements protocols that derived from BaseProtocol
13
+ like Protocol or ProcessProtocol.
14
+
15
+ The only case when BaseProtocol should be implemented directly is
16
+ write-only transport like write pipe
17
+ """
18
+
19
+ __slots__ = ()
20
+
21
+ def connection_made(self, transport):
22
+ """Called when a connection is made.
23
+
24
+ The argument is the transport representing the pipe connection.
25
+ To receive data, wait for data_received() calls.
26
+ When the connection is closed, connection_lost() is called.
27
+ """
28
+
29
+ def connection_lost(self, exc):
30
+ """Called when the connection is lost or closed.
31
+
32
+ The argument is an exception object or None (the latter
33
+ meaning a regular EOF is received or the connection was
34
+ aborted or closed).
35
+ """
36
+
37
+ def pause_writing(self):
38
+ """Called when the transport's buffer goes over the high-water mark.
39
+
40
+ Pause and resume calls are paired -- pause_writing() is called
41
+ once when the buffer goes strictly over the high-water mark
42
+ (even if subsequent writes increases the buffer size even
43
+ more), and eventually resume_writing() is called once when the
44
+ buffer size reaches the low-water mark.
45
+
46
+ Note that if the buffer size equals the high-water mark,
47
+ pause_writing() is not called -- it must go strictly over.
48
+ Conversely, resume_writing() is called when the buffer size is
49
+ equal or lower than the low-water mark. These end conditions
50
+ are important to ensure that things go as expected when either
51
+ mark is zero.
52
+
53
+ NOTE: This is the only Protocol callback that is not called
54
+ through EventLoop.call_soon() -- if it were, it would have no
55
+ effect when it's most needed (when the app keeps writing
56
+ without yielding until pause_writing() is called).
57
+ """
58
+
59
+ def resume_writing(self):
60
+ """Called when the transport's buffer drains below the low-water mark.
61
+
62
+ See pause_writing() for details.
63
+ """
64
+
65
+
66
+ class Protocol(BaseProtocol):
67
+ """Interface for stream protocol.
68
+
69
+ The user should implement this interface. They can inherit from
70
+ this class but don't need to. The implementations here do
71
+ nothing (they don't raise exceptions).
72
+
73
+ When the user wants to requests a transport, they pass a protocol
74
+ factory to a utility function (e.g., EventLoop.create_connection()).
75
+
76
+ When the connection is made successfully, connection_made() is
77
+ called with a suitable transport object. Then data_received()
78
+ will be called 0 or more times with data (bytes) received from the
79
+ transport; finally, connection_lost() will be called exactly once
80
+ with either an exception object or None as an argument.
81
+
82
+ State machine of calls:
83
+
84
+ start -> CM [-> DR*] [-> ER?] -> CL -> end
85
+
86
+ * CM: connection_made()
87
+ * DR: data_received()
88
+ * ER: eof_received()
89
+ * CL: connection_lost()
90
+ """
91
+
92
+ __slots__ = ()
93
+
94
+ def data_received(self, data):
95
+ """Called when some data is received.
96
+
97
+ The argument is a bytes object.
98
+ """
99
+
100
+ def eof_received(self):
101
+ """Called when the other end calls write_eof() or equivalent.
102
+
103
+ If this returns a false value (including None), the transport
104
+ will close itself. If it returns a true value, closing the
105
+ transport is up to the protocol.
106
+ """
107
+
108
+
109
+ class BufferedProtocol(BaseProtocol):
110
+ """Interface for stream protocol with manual buffer control.
111
+
112
+ Event methods, such as `create_server` and `create_connection`,
113
+ accept factories that return protocols that implement this interface.
114
+
115
+ The idea of BufferedProtocol is that it allows to manually allocate
116
+ and control the receive buffer. Event loops can then use the buffer
117
+ provided by the protocol to avoid unnecessary data copies. This
118
+ can result in noticeable performance improvement for protocols that
119
+ receive big amounts of data. Sophisticated protocols can allocate
120
+ the buffer only once at creation time.
121
+
122
+ State machine of calls:
123
+
124
+ start -> CM [-> GB [-> BU?]]* [-> ER?] -> CL -> end
125
+
126
+ * CM: connection_made()
127
+ * GB: get_buffer()
128
+ * BU: buffer_updated()
129
+ * ER: eof_received()
130
+ * CL: connection_lost()
131
+ """
132
+
133
+ __slots__ = ()
134
+
135
+ def get_buffer(self, sizehint):
136
+ """Called to allocate a new receive buffer.
137
+
138
+ *sizehint* is a recommended minimal size for the returned
139
+ buffer. When set to -1, the buffer size can be arbitrary.
140
+
141
+ Must return an object that implements the
142
+ :ref:`buffer protocol <bufferobjects>`.
143
+ It is an error to return a zero-sized buffer.
144
+ """
145
+
146
+ def buffer_updated(self, nbytes):
147
+ """Called when the buffer was updated with the received data.
148
+
149
+ *nbytes* is the total number of bytes that were written to
150
+ the buffer.
151
+ """
152
+
153
+ def eof_received(self):
154
+ """Called when the other end calls write_eof() or equivalent.
155
+
156
+ If this returns a false value (including None), the transport
157
+ will close itself. If it returns a true value, closing the
158
+ transport is up to the protocol.
159
+ """
160
+
161
+
162
+ class DatagramProtocol(BaseProtocol):
163
+ """Interface for datagram protocol."""
164
+
165
+ __slots__ = ()
166
+
167
+ def datagram_received(self, data, addr):
168
+ """Called when some datagram is received."""
169
+
170
+ def error_received(self, exc):
171
+ """Called when a send or receive operation raises an OSError.
172
+
173
+ (Other than BlockingIOError or InterruptedError.)
174
+ """
175
+
176
+
177
+ class SubprocessProtocol(BaseProtocol):
178
+ """Interface for protocol for subprocess calls."""
179
+
180
+ __slots__ = ()
181
+
182
+ def pipe_data_received(self, fd, data):
183
+ """Called when the subprocess writes data into stdout/stderr pipe.
184
+
185
+ fd is int file descriptor.
186
+ data is bytes object.
187
+ """
188
+
189
+ def pipe_connection_lost(self, fd, exc):
190
+ """Called when a file descriptor associated with the child process is
191
+ closed.
192
+
193
+ fd is the int file descriptor that was closed.
194
+ """
195
+
196
+ def process_exited(self):
197
+ """Called when subprocess has exited."""
198
+
199
+
200
+ def _feed_data_to_buffered_proto(proto, data):
201
+ data_len = len(data)
202
+ while data_len:
203
+ buf = proto.get_buffer(data_len)
204
+ buf_len = len(buf)
205
+ if not buf_len:
206
+ raise RuntimeError('get_buffer() returned an empty buffer')
207
+
208
+ if buf_len >= data_len:
209
+ buf[:data_len] = data
210
+ proto.buffer_updated(data_len)
211
+ return
212
+ else:
213
+ buf[:buf_len] = data[:buf_len]
214
+ proto.buffer_updated(buf_len)
215
+ data = data[buf_len:]
216
+ data_len = len(data)
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/queues.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ('Queue', 'PriorityQueue', 'LifoQueue', 'QueueFull', 'QueueEmpty')
2
+
3
+ import collections
4
+ import heapq
5
+ from types import GenericAlias
6
+
7
+ from . import locks
8
+ from . import mixins
9
+
10
+
11
+ class QueueEmpty(Exception):
12
+ """Raised when Queue.get_nowait() is called on an empty Queue."""
13
+ pass
14
+
15
+
16
+ class QueueFull(Exception):
17
+ """Raised when the Queue.put_nowait() method is called on a full Queue."""
18
+ pass
19
+
20
+
21
+ class Queue(mixins._LoopBoundMixin):
22
+ """A queue, useful for coordinating producer and consumer coroutines.
23
+
24
+ If maxsize is less than or equal to zero, the queue size is infinite. If it
25
+ is an integer greater than 0, then "await put()" will block when the
26
+ queue reaches maxsize, until an item is removed by get().
27
+
28
+ Unlike the standard library Queue, you can reliably know this Queue's size
29
+ with qsize(), since your single-threaded asyncio application won't be
30
+ interrupted between calling qsize() and doing an operation on the Queue.
31
+ """
32
+
33
+ def __init__(self, maxsize=0):
34
+ self._maxsize = maxsize
35
+
36
+ # Futures.
37
+ self._getters = collections.deque()
38
+ # Futures.
39
+ self._putters = collections.deque()
40
+ self._unfinished_tasks = 0
41
+ self._finished = locks.Event()
42
+ self._finished.set()
43
+ self._init(maxsize)
44
+
45
+ # These three are overridable in subclasses.
46
+
47
+ def _init(self, maxsize):
48
+ self._queue = collections.deque()
49
+
50
+ def _get(self):
51
+ return self._queue.popleft()
52
+
53
+ def _put(self, item):
54
+ self._queue.append(item)
55
+
56
+ # End of the overridable methods.
57
+
58
+ def _wakeup_next(self, waiters):
59
+ # Wake up the next waiter (if any) that isn't cancelled.
60
+ while waiters:
61
+ waiter = waiters.popleft()
62
+ if not waiter.done():
63
+ waiter.set_result(None)
64
+ break
65
+
66
+ def __repr__(self):
67
+ return f'<{type(self).__name__} at {id(self):#x} {self._format()}>'
68
+
69
+ def __str__(self):
70
+ return f'<{type(self).__name__} {self._format()}>'
71
+
72
+ __class_getitem__ = classmethod(GenericAlias)
73
+
74
+ def _format(self):
75
+ result = f'maxsize={self._maxsize!r}'
76
+ if getattr(self, '_queue', None):
77
+ result += f' _queue={list(self._queue)!r}'
78
+ if self._getters:
79
+ result += f' _getters[{len(self._getters)}]'
80
+ if self._putters:
81
+ result += f' _putters[{len(self._putters)}]'
82
+ if self._unfinished_tasks:
83
+ result += f' tasks={self._unfinished_tasks}'
84
+ return result
85
+
86
+ def qsize(self):
87
+ """Number of items in the queue."""
88
+ return len(self._queue)
89
+
90
+ @property
91
+ def maxsize(self):
92
+ """Number of items allowed in the queue."""
93
+ return self._maxsize
94
+
95
+ def empty(self):
96
+ """Return True if the queue is empty, False otherwise."""
97
+ return not self._queue
98
+
99
+ def full(self):
100
+ """Return True if there are maxsize items in the queue.
101
+
102
+ Note: if the Queue was initialized with maxsize=0 (the default),
103
+ then full() is never True.
104
+ """
105
+ if self._maxsize <= 0:
106
+ return False
107
+ else:
108
+ return self.qsize() >= self._maxsize
109
+
110
+ async def put(self, item):
111
+ """Put an item into the queue.
112
+
113
+ Put an item into the queue. If the queue is full, wait until a free
114
+ slot is available before adding item.
115
+ """
116
+ while self.full():
117
+ putter = self._get_loop().create_future()
118
+ self._putters.append(putter)
119
+ try:
120
+ await putter
121
+ except:
122
+ putter.cancel() # Just in case putter is not done yet.
123
+ try:
124
+ # Clean self._putters from canceled putters.
125
+ self._putters.remove(putter)
126
+ except ValueError:
127
+ # The putter could be removed from self._putters by a
128
+ # previous get_nowait call.
129
+ pass
130
+ if not self.full() and not putter.cancelled():
131
+ # We were woken up by get_nowait(), but can't take
132
+ # the call. Wake up the next in line.
133
+ self._wakeup_next(self._putters)
134
+ raise
135
+ return self.put_nowait(item)
136
+
137
+ def put_nowait(self, item):
138
+ """Put an item into the queue without blocking.
139
+
140
+ If no free slot is immediately available, raise QueueFull.
141
+ """
142
+ if self.full():
143
+ raise QueueFull
144
+ self._put(item)
145
+ self._unfinished_tasks += 1
146
+ self._finished.clear()
147
+ self._wakeup_next(self._getters)
148
+
149
+ async def get(self):
150
+ """Remove and return an item from the queue.
151
+
152
+ If queue is empty, wait until an item is available.
153
+ """
154
+ while self.empty():
155
+ getter = self._get_loop().create_future()
156
+ self._getters.append(getter)
157
+ try:
158
+ await getter
159
+ except:
160
+ getter.cancel() # Just in case getter is not done yet.
161
+ try:
162
+ # Clean self._getters from canceled getters.
163
+ self._getters.remove(getter)
164
+ except ValueError:
165
+ # The getter could be removed from self._getters by a
166
+ # previous put_nowait call.
167
+ pass
168
+ if not self.empty() and not getter.cancelled():
169
+ # We were woken up by put_nowait(), but can't take
170
+ # the call. Wake up the next in line.
171
+ self._wakeup_next(self._getters)
172
+ raise
173
+ return self.get_nowait()
174
+
175
+ def get_nowait(self):
176
+ """Remove and return an item from the queue.
177
+
178
+ Return an item if one is immediately available, else raise QueueEmpty.
179
+ """
180
+ if self.empty():
181
+ raise QueueEmpty
182
+ item = self._get()
183
+ self._wakeup_next(self._putters)
184
+ return item
185
+
186
+ def task_done(self):
187
+ """Indicate that a formerly enqueued task is complete.
188
+
189
+ Used by queue consumers. For each get() used to fetch a task,
190
+ a subsequent call to task_done() tells the queue that the processing
191
+ on the task is complete.
192
+
193
+ If a join() is currently blocking, it will resume when all items have
194
+ been processed (meaning that a task_done() call was received for every
195
+ item that had been put() into the queue).
196
+
197
+ Raises ValueError if called more times than there were items placed in
198
+ the queue.
199
+ """
200
+ if self._unfinished_tasks <= 0:
201
+ raise ValueError('task_done() called too many times')
202
+ self._unfinished_tasks -= 1
203
+ if self._unfinished_tasks == 0:
204
+ self._finished.set()
205
+
206
+ async def join(self):
207
+ """Block until all items in the queue have been gotten and processed.
208
+
209
+ The count of unfinished tasks goes up whenever an item is added to the
210
+ queue. The count goes down whenever a consumer calls task_done() to
211
+ indicate that the item was retrieved and all work on it is complete.
212
+ When the count of unfinished tasks drops to zero, join() unblocks.
213
+ """
214
+ if self._unfinished_tasks > 0:
215
+ await self._finished.wait()
216
+
217
+
218
+ class PriorityQueue(Queue):
219
+ """A subclass of Queue; retrieves entries in priority order (lowest first).
220
+
221
+ Entries are typically tuples of the form: (priority number, data).
222
+ """
223
+
224
+ def _init(self, maxsize):
225
+ self._queue = []
226
+
227
+ def _put(self, item, heappush=heapq.heappush):
228
+ heappush(self._queue, item)
229
+
230
+ def _get(self, heappop=heapq.heappop):
231
+ return heappop(self._queue)
232
+
233
+
234
+ class LifoQueue(Queue):
235
+ """A subclass of Queue that retrieves most recently added entries first."""
236
+
237
+ def _init(self, maxsize):
238
+ self._queue = []
239
+
240
+ def _put(self, item):
241
+ self._queue.append(item)
242
+
243
+ def _get(self):
244
+ return self._queue.pop()
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/runners.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ('Runner', 'run')
2
+
3
+ import contextvars
4
+ import enum
5
+ import functools
6
+ import threading
7
+ import signal
8
+ import sys
9
+ from . import coroutines
10
+ from . import events
11
+ from . import exceptions
12
+ from . import tasks
13
+
14
+
15
+ class _State(enum.Enum):
16
+ CREATED = "created"
17
+ INITIALIZED = "initialized"
18
+ CLOSED = "closed"
19
+
20
+
21
+ class Runner:
22
+ """A context manager that controls event loop life cycle.
23
+
24
+ The context manager always creates a new event loop,
25
+ allows to run async functions inside it,
26
+ and properly finalizes the loop at the context manager exit.
27
+
28
+ If debug is True, the event loop will be run in debug mode.
29
+ If loop_factory is passed, it is used for new event loop creation.
30
+
31
+ asyncio.run(main(), debug=True)
32
+
33
+ is a shortcut for
34
+
35
+ with asyncio.Runner(debug=True) as runner:
36
+ runner.run(main())
37
+
38
+ The run() method can be called multiple times within the runner's context.
39
+
40
+ This can be useful for interactive console (e.g. IPython),
41
+ unittest runners, console tools, -- everywhere when async code
42
+ is called from existing sync framework and where the preferred single
43
+ asyncio.run() call doesn't work.
44
+
45
+ """
46
+
47
+ # Note: the class is final, it is not intended for inheritance.
48
+
49
+ def __init__(self, *, debug=None, loop_factory=None):
50
+ self._state = _State.CREATED
51
+ self._debug = debug
52
+ self._loop_factory = loop_factory
53
+ self._loop = None
54
+ self._context = None
55
+ self._interrupt_count = 0
56
+ self._set_event_loop = False
57
+
58
+ def __enter__(self):
59
+ self._lazy_init()
60
+ return self
61
+
62
+ def __exit__(self, exc_type, exc_val, exc_tb):
63
+ self.close()
64
+
65
+ def close(self):
66
+ """Shutdown and close event loop."""
67
+ if self._state is not _State.INITIALIZED:
68
+ return
69
+ try:
70
+ loop = self._loop
71
+ _cancel_all_tasks(loop)
72
+ loop.run_until_complete(loop.shutdown_asyncgens())
73
+ loop.run_until_complete(loop.shutdown_default_executor())
74
+ finally:
75
+ if self._set_event_loop:
76
+ events.set_event_loop(None)
77
+ loop.close()
78
+ self._loop = None
79
+ self._state = _State.CLOSED
80
+
81
+ def get_loop(self):
82
+ """Return embedded event loop."""
83
+ self._lazy_init()
84
+ return self._loop
85
+
86
+ def run(self, coro, *, context=None):
87
+ """Run a coroutine inside the embedded event loop."""
88
+ if not coroutines.iscoroutine(coro):
89
+ raise ValueError("a coroutine was expected, got {!r}".format(coro))
90
+
91
+ if events._get_running_loop() is not None:
92
+ # fail fast with short traceback
93
+ raise RuntimeError(
94
+ "Runner.run() cannot be called from a running event loop")
95
+
96
+ self._lazy_init()
97
+
98
+ if context is None:
99
+ context = self._context
100
+ task = self._loop.create_task(coro, context=context)
101
+
102
+ if (threading.current_thread() is threading.main_thread()
103
+ and signal.getsignal(signal.SIGINT) is signal.default_int_handler
104
+ ):
105
+ sigint_handler = functools.partial(self._on_sigint, main_task=task)
106
+ try:
107
+ signal.signal(signal.SIGINT, sigint_handler)
108
+ except ValueError:
109
+ # `signal.signal` may throw if `threading.main_thread` does
110
+ # not support signals (e.g. embedded interpreter with signals
111
+ # not registered - see gh-91880)
112
+ sigint_handler = None
113
+ else:
114
+ sigint_handler = None
115
+
116
+ self._interrupt_count = 0
117
+ try:
118
+ return self._loop.run_until_complete(task)
119
+ except exceptions.CancelledError:
120
+ if self._interrupt_count > 0:
121
+ uncancel = getattr(task, "uncancel", None)
122
+ if uncancel is not None and uncancel() == 0:
123
+ raise KeyboardInterrupt()
124
+ raise # CancelledError
125
+ finally:
126
+ if (sigint_handler is not None
127
+ and signal.getsignal(signal.SIGINT) is sigint_handler
128
+ ):
129
+ signal.signal(signal.SIGINT, signal.default_int_handler)
130
+
131
+ def _lazy_init(self):
132
+ if self._state is _State.CLOSED:
133
+ raise RuntimeError("Runner is closed")
134
+ if self._state is _State.INITIALIZED:
135
+ return
136
+ if self._loop_factory is None:
137
+ self._loop = events.new_event_loop()
138
+ if not self._set_event_loop:
139
+ # Call set_event_loop only once to avoid calling
140
+ # attach_loop multiple times on child watchers
141
+ events.set_event_loop(self._loop)
142
+ self._set_event_loop = True
143
+ else:
144
+ self._loop = self._loop_factory()
145
+ if self._debug is not None:
146
+ self._loop.set_debug(self._debug)
147
+ self._context = contextvars.copy_context()
148
+ self._state = _State.INITIALIZED
149
+
150
+ def _on_sigint(self, signum, frame, main_task):
151
+ self._interrupt_count += 1
152
+ if self._interrupt_count == 1 and not main_task.done():
153
+ main_task.cancel()
154
+ # wakeup loop if it is blocked by select() with long timeout
155
+ self._loop.call_soon_threadsafe(lambda: None)
156
+ return
157
+ raise KeyboardInterrupt()
158
+
159
+
160
+ def run(main, *, debug=None):
161
+ """Execute the coroutine and return the result.
162
+
163
+ This function runs the passed coroutine, taking care of
164
+ managing the asyncio event loop and finalizing asynchronous
165
+ generators.
166
+
167
+ This function cannot be called when another asyncio event loop is
168
+ running in the same thread.
169
+
170
+ If debug is True, the event loop will be run in debug mode.
171
+
172
+ This function always creates a new event loop and closes it at the end.
173
+ It should be used as a main entry point for asyncio programs, and should
174
+ ideally only be called once.
175
+
176
+ Example:
177
+
178
+ async def main():
179
+ await asyncio.sleep(1)
180
+ print('hello')
181
+
182
+ asyncio.run(main())
183
+ """
184
+ if events._get_running_loop() is not None:
185
+ # fail fast with short traceback
186
+ raise RuntimeError(
187
+ "asyncio.run() cannot be called from a running event loop")
188
+
189
+ with Runner(debug=debug) as runner:
190
+ return runner.run(main)
191
+
192
+
193
+ def _cancel_all_tasks(loop):
194
+ to_cancel = tasks.all_tasks(loop)
195
+ if not to_cancel:
196
+ return
197
+
198
+ for task in to_cancel:
199
+ task.cancel()
200
+
201
+ loop.run_until_complete(tasks.gather(*to_cancel, return_exceptions=True))
202
+
203
+ for task in to_cancel:
204
+ if task.cancelled():
205
+ continue
206
+ if task.exception() is not None:
207
+ loop.call_exception_handler({
208
+ 'message': 'unhandled exception during asyncio.run() shutdown',
209
+ 'exception': task.exception(),
210
+ 'task': task,
211
+ })
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/selector_events.py ADDED
@@ -0,0 +1,1246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Event loop using a selector and related classes.
2
+
3
+ A selector is a "notify-when-ready" multiplexer. For a subclass which
4
+ also includes support for signal handling, see the unix_events sub-module.
5
+ """
6
+
7
+ __all__ = 'BaseSelectorEventLoop',
8
+
9
+ import collections
10
+ import errno
11
+ import functools
12
+ import selectors
13
+ import socket
14
+ import warnings
15
+ import weakref
16
+ try:
17
+ import ssl
18
+ except ImportError: # pragma: no cover
19
+ ssl = None
20
+
21
+ from . import base_events
22
+ from . import constants
23
+ from . import events
24
+ from . import futures
25
+ from . import protocols
26
+ from . import sslproto
27
+ from . import transports
28
+ from . import trsock
29
+ from .log import logger
30
+
31
+
32
+ def _test_selector_event(selector, fd, event):
33
+ # Test if the selector is monitoring 'event' events
34
+ # for the file descriptor 'fd'.
35
+ try:
36
+ key = selector.get_key(fd)
37
+ except KeyError:
38
+ return False
39
+ else:
40
+ return bool(key.events & event)
41
+
42
+
43
+ class BaseSelectorEventLoop(base_events.BaseEventLoop):
44
+ """Selector event loop.
45
+
46
+ See events.EventLoop for API specification.
47
+ """
48
+
49
+ def __init__(self, selector=None):
50
+ super().__init__()
51
+
52
+ if selector is None:
53
+ selector = selectors.DefaultSelector()
54
+ logger.debug('Using selector: %s', selector.__class__.__name__)
55
+ self._selector = selector
56
+ self._make_self_pipe()
57
+ self._transports = weakref.WeakValueDictionary()
58
+
59
+ def _make_socket_transport(self, sock, protocol, waiter=None, *,
60
+ extra=None, server=None):
61
+ return _SelectorSocketTransport(self, sock, protocol, waiter,
62
+ extra, server)
63
+
64
+ def _make_ssl_transport(
65
+ self, rawsock, protocol, sslcontext, waiter=None,
66
+ *, server_side=False, server_hostname=None,
67
+ extra=None, server=None,
68
+ ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT,
69
+ ssl_shutdown_timeout=constants.SSL_SHUTDOWN_TIMEOUT,
70
+ ):
71
+ ssl_protocol = sslproto.SSLProtocol(
72
+ self, protocol, sslcontext, waiter,
73
+ server_side, server_hostname,
74
+ ssl_handshake_timeout=ssl_handshake_timeout,
75
+ ssl_shutdown_timeout=ssl_shutdown_timeout
76
+ )
77
+ _SelectorSocketTransport(self, rawsock, ssl_protocol,
78
+ extra=extra, server=server)
79
+ return ssl_protocol._app_transport
80
+
81
+ def _make_datagram_transport(self, sock, protocol,
82
+ address=None, waiter=None, extra=None):
83
+ return _SelectorDatagramTransport(self, sock, protocol,
84
+ address, waiter, extra)
85
+
86
+ def close(self):
87
+ if self.is_running():
88
+ raise RuntimeError("Cannot close a running event loop")
89
+ if self.is_closed():
90
+ return
91
+ self._close_self_pipe()
92
+ super().close()
93
+ if self._selector is not None:
94
+ self._selector.close()
95
+ self._selector = None
96
+
97
+ def _close_self_pipe(self):
98
+ self._remove_reader(self._ssock.fileno())
99
+ self._ssock.close()
100
+ self._ssock = None
101
+ self._csock.close()
102
+ self._csock = None
103
+ self._internal_fds -= 1
104
+
105
+ def _make_self_pipe(self):
106
+ # A self-socket, really. :-)
107
+ self._ssock, self._csock = socket.socketpair()
108
+ self._ssock.setblocking(False)
109
+ self._csock.setblocking(False)
110
+ self._internal_fds += 1
111
+ self._add_reader(self._ssock.fileno(), self._read_from_self)
112
+
113
+ def _process_self_data(self, data):
114
+ pass
115
+
116
+ def _read_from_self(self):
117
+ while True:
118
+ try:
119
+ data = self._ssock.recv(4096)
120
+ if not data:
121
+ break
122
+ self._process_self_data(data)
123
+ except InterruptedError:
124
+ continue
125
+ except BlockingIOError:
126
+ break
127
+
128
+ def _write_to_self(self):
129
+ # This may be called from a different thread, possibly after
130
+ # _close_self_pipe() has been called or even while it is
131
+ # running. Guard for self._csock being None or closed. When
132
+ # a socket is closed, send() raises OSError (with errno set to
133
+ # EBADF, but let's not rely on the exact error code).
134
+ csock = self._csock
135
+ if csock is None:
136
+ return
137
+
138
+ try:
139
+ csock.send(b'\0')
140
+ except OSError:
141
+ if self._debug:
142
+ logger.debug("Fail to write a null byte into the "
143
+ "self-pipe socket",
144
+ exc_info=True)
145
+
146
+ def _start_serving(self, protocol_factory, sock,
147
+ sslcontext=None, server=None, backlog=100,
148
+ ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT,
149
+ ssl_shutdown_timeout=constants.SSL_SHUTDOWN_TIMEOUT):
150
+ self._add_reader(sock.fileno(), self._accept_connection,
151
+ protocol_factory, sock, sslcontext, server, backlog,
152
+ ssl_handshake_timeout, ssl_shutdown_timeout)
153
+
154
+ def _accept_connection(
155
+ self, protocol_factory, sock,
156
+ sslcontext=None, server=None, backlog=100,
157
+ ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT,
158
+ ssl_shutdown_timeout=constants.SSL_SHUTDOWN_TIMEOUT):
159
+ # This method is only called once for each event loop tick where the
160
+ # listening socket has triggered an EVENT_READ. There may be multiple
161
+ # connections waiting for an .accept() so it is called in a loop.
162
+ # See https://bugs.python.org/issue27906 for more details.
163
+ for _ in range(backlog):
164
+ try:
165
+ conn, addr = sock.accept()
166
+ if self._debug:
167
+ logger.debug("%r got a new connection from %r: %r",
168
+ server, addr, conn)
169
+ conn.setblocking(False)
170
+ except (BlockingIOError, InterruptedError, ConnectionAbortedError):
171
+ # Early exit because the socket accept buffer is empty.
172
+ return None
173
+ except OSError as exc:
174
+ # There's nowhere to send the error, so just log it.
175
+ if exc.errno in (errno.EMFILE, errno.ENFILE,
176
+ errno.ENOBUFS, errno.ENOMEM):
177
+ # Some platforms (e.g. Linux keep reporting the FD as
178
+ # ready, so we remove the read handler temporarily.
179
+ # We'll try again in a while.
180
+ self.call_exception_handler({
181
+ 'message': 'socket.accept() out of system resource',
182
+ 'exception': exc,
183
+ 'socket': trsock.TransportSocket(sock),
184
+ })
185
+ self._remove_reader(sock.fileno())
186
+ self.call_later(constants.ACCEPT_RETRY_DELAY,
187
+ self._start_serving,
188
+ protocol_factory, sock, sslcontext, server,
189
+ backlog, ssl_handshake_timeout,
190
+ ssl_shutdown_timeout)
191
+ else:
192
+ raise # The event loop will catch, log and ignore it.
193
+ else:
194
+ extra = {'peername': addr}
195
+ accept = self._accept_connection2(
196
+ protocol_factory, conn, extra, sslcontext, server,
197
+ ssl_handshake_timeout, ssl_shutdown_timeout)
198
+ self.create_task(accept)
199
+
200
+ async def _accept_connection2(
201
+ self, protocol_factory, conn, extra,
202
+ sslcontext=None, server=None,
203
+ ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT,
204
+ ssl_shutdown_timeout=constants.SSL_SHUTDOWN_TIMEOUT):
205
+ protocol = None
206
+ transport = None
207
+ try:
208
+ protocol = protocol_factory()
209
+ waiter = self.create_future()
210
+ if sslcontext:
211
+ transport = self._make_ssl_transport(
212
+ conn, protocol, sslcontext, waiter=waiter,
213
+ server_side=True, extra=extra, server=server,
214
+ ssl_handshake_timeout=ssl_handshake_timeout,
215
+ ssl_shutdown_timeout=ssl_shutdown_timeout)
216
+ else:
217
+ transport = self._make_socket_transport(
218
+ conn, protocol, waiter=waiter, extra=extra,
219
+ server=server)
220
+
221
+ try:
222
+ await waiter
223
+ except BaseException:
224
+ transport.close()
225
+ # gh-109534: When an exception is raised by the SSLProtocol object the
226
+ # exception set in this future can keep the protocol object alive and
227
+ # cause a reference cycle.
228
+ waiter = None
229
+ raise
230
+ # It's now up to the protocol to handle the connection.
231
+
232
+ except (SystemExit, KeyboardInterrupt):
233
+ raise
234
+ except BaseException as exc:
235
+ if self._debug:
236
+ context = {
237
+ 'message':
238
+ 'Error on transport creation for incoming connection',
239
+ 'exception': exc,
240
+ }
241
+ if protocol is not None:
242
+ context['protocol'] = protocol
243
+ if transport is not None:
244
+ context['transport'] = transport
245
+ self.call_exception_handler(context)
246
+
247
+ def _ensure_fd_no_transport(self, fd):
248
+ fileno = fd
249
+ if not isinstance(fileno, int):
250
+ try:
251
+ fileno = int(fileno.fileno())
252
+ except (AttributeError, TypeError, ValueError):
253
+ # This code matches selectors._fileobj_to_fd function.
254
+ raise ValueError(f"Invalid file object: {fd!r}") from None
255
+ try:
256
+ transport = self._transports[fileno]
257
+ except KeyError:
258
+ pass
259
+ else:
260
+ if not transport.is_closing():
261
+ raise RuntimeError(
262
+ f'File descriptor {fd!r} is used by transport '
263
+ f'{transport!r}')
264
+
265
+ def _add_reader(self, fd, callback, *args):
266
+ self._check_closed()
267
+ handle = events.Handle(callback, args, self, None)
268
+ try:
269
+ key = self._selector.get_key(fd)
270
+ except KeyError:
271
+ self._selector.register(fd, selectors.EVENT_READ,
272
+ (handle, None))
273
+ else:
274
+ mask, (reader, writer) = key.events, key.data
275
+ self._selector.modify(fd, mask | selectors.EVENT_READ,
276
+ (handle, writer))
277
+ if reader is not None:
278
+ reader.cancel()
279
+ return handle
280
+
281
+ def _remove_reader(self, fd):
282
+ if self.is_closed():
283
+ return False
284
+ try:
285
+ key = self._selector.get_key(fd)
286
+ except KeyError:
287
+ return False
288
+ else:
289
+ mask, (reader, writer) = key.events, key.data
290
+ mask &= ~selectors.EVENT_READ
291
+ if not mask:
292
+ self._selector.unregister(fd)
293
+ else:
294
+ self._selector.modify(fd, mask, (None, writer))
295
+
296
+ if reader is not None:
297
+ reader.cancel()
298
+ return True
299
+ else:
300
+ return False
301
+
302
+ def _add_writer(self, fd, callback, *args):
303
+ self._check_closed()
304
+ handle = events.Handle(callback, args, self, None)
305
+ try:
306
+ key = self._selector.get_key(fd)
307
+ except KeyError:
308
+ self._selector.register(fd, selectors.EVENT_WRITE,
309
+ (None, handle))
310
+ else:
311
+ mask, (reader, writer) = key.events, key.data
312
+ self._selector.modify(fd, mask | selectors.EVENT_WRITE,
313
+ (reader, handle))
314
+ if writer is not None:
315
+ writer.cancel()
316
+ return handle
317
+
318
+ def _remove_writer(self, fd):
319
+ """Remove a writer callback."""
320
+ if self.is_closed():
321
+ return False
322
+ try:
323
+ key = self._selector.get_key(fd)
324
+ except KeyError:
325
+ return False
326
+ else:
327
+ mask, (reader, writer) = key.events, key.data
328
+ # Remove both writer and connector.
329
+ mask &= ~selectors.EVENT_WRITE
330
+ if not mask:
331
+ self._selector.unregister(fd)
332
+ else:
333
+ self._selector.modify(fd, mask, (reader, None))
334
+
335
+ if writer is not None:
336
+ writer.cancel()
337
+ return True
338
+ else:
339
+ return False
340
+
341
+ def add_reader(self, fd, callback, *args):
342
+ """Add a reader callback."""
343
+ self._ensure_fd_no_transport(fd)
344
+ self._add_reader(fd, callback, *args)
345
+
346
+ def remove_reader(self, fd):
347
+ """Remove a reader callback."""
348
+ self._ensure_fd_no_transport(fd)
349
+ return self._remove_reader(fd)
350
+
351
+ def add_writer(self, fd, callback, *args):
352
+ """Add a writer callback.."""
353
+ self._ensure_fd_no_transport(fd)
354
+ self._add_writer(fd, callback, *args)
355
+
356
+ def remove_writer(self, fd):
357
+ """Remove a writer callback."""
358
+ self._ensure_fd_no_transport(fd)
359
+ return self._remove_writer(fd)
360
+
361
+ async def sock_recv(self, sock, n):
362
+ """Receive data from the socket.
363
+
364
+ The return value is a bytes object representing the data received.
365
+ The maximum amount of data to be received at once is specified by
366
+ nbytes.
367
+ """
368
+ base_events._check_ssl_socket(sock)
369
+ if self._debug and sock.gettimeout() != 0:
370
+ raise ValueError("the socket must be non-blocking")
371
+ try:
372
+ return sock.recv(n)
373
+ except (BlockingIOError, InterruptedError):
374
+ pass
375
+ fut = self.create_future()
376
+ fd = sock.fileno()
377
+ self._ensure_fd_no_transport(fd)
378
+ handle = self._add_reader(fd, self._sock_recv, fut, sock, n)
379
+ fut.add_done_callback(
380
+ functools.partial(self._sock_read_done, fd, handle=handle))
381
+ return await fut
382
+
383
+ def _sock_read_done(self, fd, fut, handle=None):
384
+ if handle is None or not handle.cancelled():
385
+ self.remove_reader(fd)
386
+
387
+ def _sock_recv(self, fut, sock, n):
388
+ # _sock_recv() can add itself as an I/O callback if the operation can't
389
+ # be done immediately. Don't use it directly, call sock_recv().
390
+ if fut.done():
391
+ return
392
+ try:
393
+ data = sock.recv(n)
394
+ except (BlockingIOError, InterruptedError):
395
+ return # try again next time
396
+ except (SystemExit, KeyboardInterrupt):
397
+ raise
398
+ except BaseException as exc:
399
+ fut.set_exception(exc)
400
+ else:
401
+ fut.set_result(data)
402
+
403
+ async def sock_recv_into(self, sock, buf):
404
+ """Receive data from the socket.
405
+
406
+ The received data is written into *buf* (a writable buffer).
407
+ The return value is the number of bytes written.
408
+ """
409
+ base_events._check_ssl_socket(sock)
410
+ if self._debug and sock.gettimeout() != 0:
411
+ raise ValueError("the socket must be non-blocking")
412
+ try:
413
+ return sock.recv_into(buf)
414
+ except (BlockingIOError, InterruptedError):
415
+ pass
416
+ fut = self.create_future()
417
+ fd = sock.fileno()
418
+ self._ensure_fd_no_transport(fd)
419
+ handle = self._add_reader(fd, self._sock_recv_into, fut, sock, buf)
420
+ fut.add_done_callback(
421
+ functools.partial(self._sock_read_done, fd, handle=handle))
422
+ return await fut
423
+
424
+ def _sock_recv_into(self, fut, sock, buf):
425
+ # _sock_recv_into() can add itself as an I/O callback if the operation
426
+ # can't be done immediately. Don't use it directly, call
427
+ # sock_recv_into().
428
+ if fut.done():
429
+ return
430
+ try:
431
+ nbytes = sock.recv_into(buf)
432
+ except (BlockingIOError, InterruptedError):
433
+ return # try again next time
434
+ except (SystemExit, KeyboardInterrupt):
435
+ raise
436
+ except BaseException as exc:
437
+ fut.set_exception(exc)
438
+ else:
439
+ fut.set_result(nbytes)
440
+
441
+ async def sock_recvfrom(self, sock, bufsize):
442
+ """Receive a datagram from a datagram socket.
443
+
444
+ The return value is a tuple of (bytes, address) representing the
445
+ datagram received and the address it came from.
446
+ The maximum amount of data to be received at once is specified by
447
+ nbytes.
448
+ """
449
+ base_events._check_ssl_socket(sock)
450
+ if self._debug and sock.gettimeout() != 0:
451
+ raise ValueError("the socket must be non-blocking")
452
+ try:
453
+ return sock.recvfrom(bufsize)
454
+ except (BlockingIOError, InterruptedError):
455
+ pass
456
+ fut = self.create_future()
457
+ fd = sock.fileno()
458
+ self._ensure_fd_no_transport(fd)
459
+ handle = self._add_reader(fd, self._sock_recvfrom, fut, sock, bufsize)
460
+ fut.add_done_callback(
461
+ functools.partial(self._sock_read_done, fd, handle=handle))
462
+ return await fut
463
+
464
+ def _sock_recvfrom(self, fut, sock, bufsize):
465
+ # _sock_recvfrom() can add itself as an I/O callback if the operation
466
+ # can't be done immediately. Don't use it directly, call
467
+ # sock_recvfrom().
468
+ if fut.done():
469
+ return
470
+ try:
471
+ result = sock.recvfrom(bufsize)
472
+ except (BlockingIOError, InterruptedError):
473
+ return # try again next time
474
+ except (SystemExit, KeyboardInterrupt):
475
+ raise
476
+ except BaseException as exc:
477
+ fut.set_exception(exc)
478
+ else:
479
+ fut.set_result(result)
480
+
481
+ async def sock_recvfrom_into(self, sock, buf, nbytes=0):
482
+ """Receive data from the socket.
483
+
484
+ The received data is written into *buf* (a writable buffer).
485
+ The return value is a tuple of (number of bytes written, address).
486
+ """
487
+ base_events._check_ssl_socket(sock)
488
+ if self._debug and sock.gettimeout() != 0:
489
+ raise ValueError("the socket must be non-blocking")
490
+ if not nbytes:
491
+ nbytes = len(buf)
492
+
493
+ try:
494
+ return sock.recvfrom_into(buf, nbytes)
495
+ except (BlockingIOError, InterruptedError):
496
+ pass
497
+ fut = self.create_future()
498
+ fd = sock.fileno()
499
+ self._ensure_fd_no_transport(fd)
500
+ handle = self._add_reader(fd, self._sock_recvfrom_into, fut, sock, buf,
501
+ nbytes)
502
+ fut.add_done_callback(
503
+ functools.partial(self._sock_read_done, fd, handle=handle))
504
+ return await fut
505
+
506
+ def _sock_recvfrom_into(self, fut, sock, buf, bufsize):
507
+ # _sock_recv_into() can add itself as an I/O callback if the operation
508
+ # can't be done immediately. Don't use it directly, call
509
+ # sock_recv_into().
510
+ if fut.done():
511
+ return
512
+ try:
513
+ result = sock.recvfrom_into(buf, bufsize)
514
+ except (BlockingIOError, InterruptedError):
515
+ return # try again next time
516
+ except (SystemExit, KeyboardInterrupt):
517
+ raise
518
+ except BaseException as exc:
519
+ fut.set_exception(exc)
520
+ else:
521
+ fut.set_result(result)
522
+
523
+ async def sock_sendall(self, sock, data):
524
+ """Send data to the socket.
525
+
526
+ The socket must be connected to a remote socket. This method continues
527
+ to send data from data until either all data has been sent or an
528
+ error occurs. None is returned on success. On error, an exception is
529
+ raised, and there is no way to determine how much data, if any, was
530
+ successfully processed by the receiving end of the connection.
531
+ """
532
+ base_events._check_ssl_socket(sock)
533
+ if self._debug and sock.gettimeout() != 0:
534
+ raise ValueError("the socket must be non-blocking")
535
+ try:
536
+ n = sock.send(data)
537
+ except (BlockingIOError, InterruptedError):
538
+ n = 0
539
+
540
+ if n == len(data):
541
+ # all data sent
542
+ return
543
+
544
+ fut = self.create_future()
545
+ fd = sock.fileno()
546
+ self._ensure_fd_no_transport(fd)
547
+ # use a trick with a list in closure to store a mutable state
548
+ handle = self._add_writer(fd, self._sock_sendall, fut, sock,
549
+ memoryview(data), [n])
550
+ fut.add_done_callback(
551
+ functools.partial(self._sock_write_done, fd, handle=handle))
552
+ return await fut
553
+
554
+ def _sock_sendall(self, fut, sock, view, pos):
555
+ if fut.done():
556
+ # Future cancellation can be scheduled on previous loop iteration
557
+ return
558
+ start = pos[0]
559
+ try:
560
+ n = sock.send(view[start:])
561
+ except (BlockingIOError, InterruptedError):
562
+ return
563
+ except (SystemExit, KeyboardInterrupt):
564
+ raise
565
+ except BaseException as exc:
566
+ fut.set_exception(exc)
567
+ return
568
+
569
+ start += n
570
+
571
+ if start == len(view):
572
+ fut.set_result(None)
573
+ else:
574
+ pos[0] = start
575
+
576
+ async def sock_sendto(self, sock, data, address):
577
+ """Send data to the socket.
578
+
579
+ The socket must be connected to a remote socket. This method continues
580
+ to send data from data until either all data has been sent or an
581
+ error occurs. None is returned on success. On error, an exception is
582
+ raised, and there is no way to determine how much data, if any, was
583
+ successfully processed by the receiving end of the connection.
584
+ """
585
+ base_events._check_ssl_socket(sock)
586
+ if self._debug and sock.gettimeout() != 0:
587
+ raise ValueError("the socket must be non-blocking")
588
+ try:
589
+ return sock.sendto(data, address)
590
+ except (BlockingIOError, InterruptedError):
591
+ pass
592
+
593
+ fut = self.create_future()
594
+ fd = sock.fileno()
595
+ self._ensure_fd_no_transport(fd)
596
+ # use a trick with a list in closure to store a mutable state
597
+ handle = self._add_writer(fd, self._sock_sendto, fut, sock, data,
598
+ address)
599
+ fut.add_done_callback(
600
+ functools.partial(self._sock_write_done, fd, handle=handle))
601
+ return await fut
602
+
603
+ def _sock_sendto(self, fut, sock, data, address):
604
+ if fut.done():
605
+ # Future cancellation can be scheduled on previous loop iteration
606
+ return
607
+ try:
608
+ n = sock.sendto(data, 0, address)
609
+ except (BlockingIOError, InterruptedError):
610
+ return
611
+ except (SystemExit, KeyboardInterrupt):
612
+ raise
613
+ except BaseException as exc:
614
+ fut.set_exception(exc)
615
+ else:
616
+ fut.set_result(n)
617
+
618
+ async def sock_connect(self, sock, address):
619
+ """Connect to a remote socket at address.
620
+
621
+ This method is a coroutine.
622
+ """
623
+ base_events._check_ssl_socket(sock)
624
+ if self._debug and sock.gettimeout() != 0:
625
+ raise ValueError("the socket must be non-blocking")
626
+
627
+ if sock.family == socket.AF_INET or (
628
+ base_events._HAS_IPv6 and sock.family == socket.AF_INET6):
629
+ resolved = await self._ensure_resolved(
630
+ address, family=sock.family, type=sock.type, proto=sock.proto,
631
+ loop=self,
632
+ )
633
+ _, _, _, _, address = resolved[0]
634
+
635
+ fut = self.create_future()
636
+ self._sock_connect(fut, sock, address)
637
+ try:
638
+ return await fut
639
+ finally:
640
+ # Needed to break cycles when an exception occurs.
641
+ fut = None
642
+
643
+ def _sock_connect(self, fut, sock, address):
644
+ fd = sock.fileno()
645
+ try:
646
+ sock.connect(address)
647
+ except (BlockingIOError, InterruptedError):
648
+ # Issue #23618: When the C function connect() fails with EINTR, the
649
+ # connection runs in background. We have to wait until the socket
650
+ # becomes writable to be notified when the connection succeed or
651
+ # fails.
652
+ self._ensure_fd_no_transport(fd)
653
+ handle = self._add_writer(
654
+ fd, self._sock_connect_cb, fut, sock, address)
655
+ fut.add_done_callback(
656
+ functools.partial(self._sock_write_done, fd, handle=handle))
657
+ except (SystemExit, KeyboardInterrupt):
658
+ raise
659
+ except BaseException as exc:
660
+ fut.set_exception(exc)
661
+ else:
662
+ fut.set_result(None)
663
+ finally:
664
+ fut = None
665
+
666
+ def _sock_write_done(self, fd, fut, handle=None):
667
+ if handle is None or not handle.cancelled():
668
+ self.remove_writer(fd)
669
+
670
+ def _sock_connect_cb(self, fut, sock, address):
671
+ if fut.done():
672
+ return
673
+
674
+ try:
675
+ err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
676
+ if err != 0:
677
+ # Jump to any except clause below.
678
+ raise OSError(err, f'Connect call failed {address}')
679
+ except (BlockingIOError, InterruptedError):
680
+ # socket is still registered, the callback will be retried later
681
+ pass
682
+ except (SystemExit, KeyboardInterrupt):
683
+ raise
684
+ except BaseException as exc:
685
+ fut.set_exception(exc)
686
+ else:
687
+ fut.set_result(None)
688
+ finally:
689
+ fut = None
690
+
691
+ async def sock_accept(self, sock):
692
+ """Accept a connection.
693
+
694
+ The socket must be bound to an address and listening for connections.
695
+ The return value is a pair (conn, address) where conn is a new socket
696
+ object usable to send and receive data on the connection, and address
697
+ is the address bound to the socket on the other end of the connection.
698
+ """
699
+ base_events._check_ssl_socket(sock)
700
+ if self._debug and sock.gettimeout() != 0:
701
+ raise ValueError("the socket must be non-blocking")
702
+ fut = self.create_future()
703
+ self._sock_accept(fut, sock)
704
+ return await fut
705
+
706
+ def _sock_accept(self, fut, sock):
707
+ fd = sock.fileno()
708
+ try:
709
+ conn, address = sock.accept()
710
+ conn.setblocking(False)
711
+ except (BlockingIOError, InterruptedError):
712
+ self._ensure_fd_no_transport(fd)
713
+ handle = self._add_reader(fd, self._sock_accept, fut, sock)
714
+ fut.add_done_callback(
715
+ functools.partial(self._sock_read_done, fd, handle=handle))
716
+ except (SystemExit, KeyboardInterrupt):
717
+ raise
718
+ except BaseException as exc:
719
+ fut.set_exception(exc)
720
+ else:
721
+ fut.set_result((conn, address))
722
+
723
+ async def _sendfile_native(self, transp, file, offset, count):
724
+ del self._transports[transp._sock_fd]
725
+ resume_reading = transp.is_reading()
726
+ transp.pause_reading()
727
+ await transp._make_empty_waiter()
728
+ try:
729
+ return await self.sock_sendfile(transp._sock, file, offset, count,
730
+ fallback=False)
731
+ finally:
732
+ transp._reset_empty_waiter()
733
+ if resume_reading:
734
+ transp.resume_reading()
735
+ self._transports[transp._sock_fd] = transp
736
+
737
+ def _process_events(self, event_list):
738
+ for key, mask in event_list:
739
+ fileobj, (reader, writer) = key.fileobj, key.data
740
+ if mask & selectors.EVENT_READ and reader is not None:
741
+ if reader._cancelled:
742
+ self._remove_reader(fileobj)
743
+ else:
744
+ self._add_callback(reader)
745
+ if mask & selectors.EVENT_WRITE and writer is not None:
746
+ if writer._cancelled:
747
+ self._remove_writer(fileobj)
748
+ else:
749
+ self._add_callback(writer)
750
+
751
+ def _stop_serving(self, sock):
752
+ self._remove_reader(sock.fileno())
753
+ sock.close()
754
+
755
+
756
+ class _SelectorTransport(transports._FlowControlMixin,
757
+ transports.Transport):
758
+
759
+ max_size = 256 * 1024 # Buffer size passed to recv().
760
+
761
+ _buffer_factory = bytearray # Constructs initial value for self._buffer.
762
+
763
+ # Attribute used in the destructor: it must be set even if the constructor
764
+ # is not called (see _SelectorSslTransport which may start by raising an
765
+ # exception)
766
+ _sock = None
767
+
768
+ def __init__(self, loop, sock, protocol, extra=None, server=None):
769
+ super().__init__(extra, loop)
770
+ self._extra['socket'] = trsock.TransportSocket(sock)
771
+ try:
772
+ self._extra['sockname'] = sock.getsockname()
773
+ except OSError:
774
+ self._extra['sockname'] = None
775
+ if 'peername' not in self._extra:
776
+ try:
777
+ self._extra['peername'] = sock.getpeername()
778
+ except socket.error:
779
+ self._extra['peername'] = None
780
+ self._sock = sock
781
+ self._sock_fd = sock.fileno()
782
+
783
+ self._protocol_connected = False
784
+ self.set_protocol(protocol)
785
+
786
+ self._server = server
787
+ self._buffer = self._buffer_factory()
788
+ self._conn_lost = 0 # Set when call to connection_lost scheduled.
789
+ self._closing = False # Set when close() called.
790
+ self._paused = False # Set when pause_reading() called
791
+
792
+ if self._server is not None:
793
+ self._server._attach()
794
+ loop._transports[self._sock_fd] = self
795
+
796
+ def __repr__(self):
797
+ info = [self.__class__.__name__]
798
+ if self._sock is None:
799
+ info.append('closed')
800
+ elif self._closing:
801
+ info.append('closing')
802
+ info.append(f'fd={self._sock_fd}')
803
+ # test if the transport was closed
804
+ if self._loop is not None and not self._loop.is_closed():
805
+ polling = _test_selector_event(self._loop._selector,
806
+ self._sock_fd, selectors.EVENT_READ)
807
+ if polling:
808
+ info.append('read=polling')
809
+ else:
810
+ info.append('read=idle')
811
+
812
+ polling = _test_selector_event(self._loop._selector,
813
+ self._sock_fd,
814
+ selectors.EVENT_WRITE)
815
+ if polling:
816
+ state = 'polling'
817
+ else:
818
+ state = 'idle'
819
+
820
+ bufsize = self.get_write_buffer_size()
821
+ info.append(f'write=<{state}, bufsize={bufsize}>')
822
+ return '<{}>'.format(' '.join(info))
823
+
824
+ def abort(self):
825
+ self._force_close(None)
826
+
827
+ def set_protocol(self, protocol):
828
+ self._protocol = protocol
829
+ self._protocol_connected = True
830
+
831
+ def get_protocol(self):
832
+ return self._protocol
833
+
834
+ def is_closing(self):
835
+ return self._closing
836
+
837
+ def is_reading(self):
838
+ return not self.is_closing() and not self._paused
839
+
840
+ def pause_reading(self):
841
+ if not self.is_reading():
842
+ return
843
+ self._paused = True
844
+ self._loop._remove_reader(self._sock_fd)
845
+ if self._loop.get_debug():
846
+ logger.debug("%r pauses reading", self)
847
+
848
+ def resume_reading(self):
849
+ if self._closing or not self._paused:
850
+ return
851
+ self._paused = False
852
+ self._add_reader(self._sock_fd, self._read_ready)
853
+ if self._loop.get_debug():
854
+ logger.debug("%r resumes reading", self)
855
+
856
+ def close(self):
857
+ if self._closing:
858
+ return
859
+ self._closing = True
860
+ self._loop._remove_reader(self._sock_fd)
861
+ if not self._buffer:
862
+ self._conn_lost += 1
863
+ self._loop._remove_writer(self._sock_fd)
864
+ self._loop.call_soon(self._call_connection_lost, None)
865
+
866
+ def __del__(self, _warn=warnings.warn):
867
+ if self._sock is not None:
868
+ _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
869
+ self._sock.close()
870
+
871
+ def _fatal_error(self, exc, message='Fatal error on transport'):
872
+ # Should be called from exception handler only.
873
+ if isinstance(exc, OSError):
874
+ if self._loop.get_debug():
875
+ logger.debug("%r: %s", self, message, exc_info=True)
876
+ else:
877
+ self._loop.call_exception_handler({
878
+ 'message': message,
879
+ 'exception': exc,
880
+ 'transport': self,
881
+ 'protocol': self._protocol,
882
+ })
883
+ self._force_close(exc)
884
+
885
+ def _force_close(self, exc):
886
+ if self._conn_lost:
887
+ return
888
+ if self._buffer:
889
+ self._buffer.clear()
890
+ self._loop._remove_writer(self._sock_fd)
891
+ if not self._closing:
892
+ self._closing = True
893
+ self._loop._remove_reader(self._sock_fd)
894
+ self._conn_lost += 1
895
+ self._loop.call_soon(self._call_connection_lost, exc)
896
+
897
+ def _call_connection_lost(self, exc):
898
+ try:
899
+ if self._protocol_connected:
900
+ self._protocol.connection_lost(exc)
901
+ finally:
902
+ self._sock.close()
903
+ self._sock = None
904
+ self._protocol = None
905
+ self._loop = None
906
+ server = self._server
907
+ if server is not None:
908
+ server._detach()
909
+ self._server = None
910
+
911
+ def get_write_buffer_size(self):
912
+ return len(self._buffer)
913
+
914
+ def _add_reader(self, fd, callback, *args):
915
+ if not self.is_reading():
916
+ return
917
+ self._loop._add_reader(fd, callback, *args)
918
+
919
+
920
+ class _SelectorSocketTransport(_SelectorTransport):
921
+
922
+ _start_tls_compatible = True
923
+ _sendfile_compatible = constants._SendfileMode.TRY_NATIVE
924
+
925
+ def __init__(self, loop, sock, protocol, waiter=None,
926
+ extra=None, server=None):
927
+
928
+ self._read_ready_cb = None
929
+ super().__init__(loop, sock, protocol, extra, server)
930
+ self._eof = False
931
+ self._empty_waiter = None
932
+
933
+ # Disable the Nagle algorithm -- small writes will be
934
+ # sent without waiting for the TCP ACK. This generally
935
+ # decreases the latency (in some cases significantly.)
936
+ base_events._set_nodelay(self._sock)
937
+
938
+ self._loop.call_soon(self._protocol.connection_made, self)
939
+ # only start reading when connection_made() has been called
940
+ self._loop.call_soon(self._add_reader,
941
+ self._sock_fd, self._read_ready)
942
+ if waiter is not None:
943
+ # only wake up the waiter when connection_made() has been called
944
+ self._loop.call_soon(futures._set_result_unless_cancelled,
945
+ waiter, None)
946
+
947
+ def set_protocol(self, protocol):
948
+ if isinstance(protocol, protocols.BufferedProtocol):
949
+ self._read_ready_cb = self._read_ready__get_buffer
950
+ else:
951
+ self._read_ready_cb = self._read_ready__data_received
952
+
953
+ super().set_protocol(protocol)
954
+
955
+ def _read_ready(self):
956
+ self._read_ready_cb()
957
+
958
+ def _read_ready__get_buffer(self):
959
+ if self._conn_lost:
960
+ return
961
+
962
+ try:
963
+ buf = self._protocol.get_buffer(-1)
964
+ if not len(buf):
965
+ raise RuntimeError('get_buffer() returned an empty buffer')
966
+ except (SystemExit, KeyboardInterrupt):
967
+ raise
968
+ except BaseException as exc:
969
+ self._fatal_error(
970
+ exc, 'Fatal error: protocol.get_buffer() call failed.')
971
+ return
972
+
973
+ try:
974
+ nbytes = self._sock.recv_into(buf)
975
+ except (BlockingIOError, InterruptedError):
976
+ return
977
+ except (SystemExit, KeyboardInterrupt):
978
+ raise
979
+ except BaseException as exc:
980
+ self._fatal_error(exc, 'Fatal read error on socket transport')
981
+ return
982
+
983
+ if not nbytes:
984
+ self._read_ready__on_eof()
985
+ return
986
+
987
+ try:
988
+ self._protocol.buffer_updated(nbytes)
989
+ except (SystemExit, KeyboardInterrupt):
990
+ raise
991
+ except BaseException as exc:
992
+ self._fatal_error(
993
+ exc, 'Fatal error: protocol.buffer_updated() call failed.')
994
+
995
+ def _read_ready__data_received(self):
996
+ if self._conn_lost:
997
+ return
998
+ try:
999
+ data = self._sock.recv(self.max_size)
1000
+ except (BlockingIOError, InterruptedError):
1001
+ return
1002
+ except (SystemExit, KeyboardInterrupt):
1003
+ raise
1004
+ except BaseException as exc:
1005
+ self._fatal_error(exc, 'Fatal read error on socket transport')
1006
+ return
1007
+
1008
+ if not data:
1009
+ self._read_ready__on_eof()
1010
+ return
1011
+
1012
+ try:
1013
+ self._protocol.data_received(data)
1014
+ except (SystemExit, KeyboardInterrupt):
1015
+ raise
1016
+ except BaseException as exc:
1017
+ self._fatal_error(
1018
+ exc, 'Fatal error: protocol.data_received() call failed.')
1019
+
1020
+ def _read_ready__on_eof(self):
1021
+ if self._loop.get_debug():
1022
+ logger.debug("%r received EOF", self)
1023
+
1024
+ try:
1025
+ keep_open = self._protocol.eof_received()
1026
+ except (SystemExit, KeyboardInterrupt):
1027
+ raise
1028
+ except BaseException as exc:
1029
+ self._fatal_error(
1030
+ exc, 'Fatal error: protocol.eof_received() call failed.')
1031
+ return
1032
+
1033
+ if keep_open:
1034
+ # We're keeping the connection open so the
1035
+ # protocol can write more, but we still can't
1036
+ # receive more, so remove the reader callback.
1037
+ self._loop._remove_reader(self._sock_fd)
1038
+ else:
1039
+ self.close()
1040
+
1041
+ def write(self, data):
1042
+ if not isinstance(data, (bytes, bytearray, memoryview)):
1043
+ raise TypeError(f'data argument must be a bytes-like object, '
1044
+ f'not {type(data).__name__!r}')
1045
+ if self._eof:
1046
+ raise RuntimeError('Cannot call write() after write_eof()')
1047
+ if self._empty_waiter is not None:
1048
+ raise RuntimeError('unable to write; sendfile is in progress')
1049
+ if not data:
1050
+ return
1051
+
1052
+ if self._conn_lost:
1053
+ if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
1054
+ logger.warning('socket.send() raised exception.')
1055
+ self._conn_lost += 1
1056
+ return
1057
+
1058
+ if not self._buffer:
1059
+ # Optimization: try to send now.
1060
+ try:
1061
+ n = self._sock.send(data)
1062
+ except (BlockingIOError, InterruptedError):
1063
+ pass
1064
+ except (SystemExit, KeyboardInterrupt):
1065
+ raise
1066
+ except BaseException as exc:
1067
+ self._fatal_error(exc, 'Fatal write error on socket transport')
1068
+ return
1069
+ else:
1070
+ data = data[n:]
1071
+ if not data:
1072
+ return
1073
+ # Not all was written; register write handler.
1074
+ self._loop._add_writer(self._sock_fd, self._write_ready)
1075
+
1076
+ # Add it to the buffer.
1077
+ self._buffer.extend(data)
1078
+ self._maybe_pause_protocol()
1079
+
1080
+ def _write_ready(self):
1081
+ assert self._buffer, 'Data should not be empty'
1082
+
1083
+ if self._conn_lost:
1084
+ return
1085
+ try:
1086
+ n = self._sock.send(self._buffer)
1087
+ except (BlockingIOError, InterruptedError):
1088
+ pass
1089
+ except (SystemExit, KeyboardInterrupt):
1090
+ raise
1091
+ except BaseException as exc:
1092
+ self._loop._remove_writer(self._sock_fd)
1093
+ self._buffer.clear()
1094
+ self._fatal_error(exc, 'Fatal write error on socket transport')
1095
+ if self._empty_waiter is not None:
1096
+ self._empty_waiter.set_exception(exc)
1097
+ else:
1098
+ if n:
1099
+ del self._buffer[:n]
1100
+ self._maybe_resume_protocol() # May append to buffer.
1101
+ if not self._buffer:
1102
+ self._loop._remove_writer(self._sock_fd)
1103
+ if self._empty_waiter is not None:
1104
+ self._empty_waiter.set_result(None)
1105
+ if self._closing:
1106
+ self._call_connection_lost(None)
1107
+ elif self._eof:
1108
+ self._sock.shutdown(socket.SHUT_WR)
1109
+
1110
+ def write_eof(self):
1111
+ if self._closing or self._eof:
1112
+ return
1113
+ self._eof = True
1114
+ if not self._buffer:
1115
+ self._sock.shutdown(socket.SHUT_WR)
1116
+
1117
+ def can_write_eof(self):
1118
+ return True
1119
+
1120
+ def _call_connection_lost(self, exc):
1121
+ super()._call_connection_lost(exc)
1122
+ if self._empty_waiter is not None:
1123
+ self._empty_waiter.set_exception(
1124
+ ConnectionError("Connection is closed by peer"))
1125
+
1126
+ def _make_empty_waiter(self):
1127
+ if self._empty_waiter is not None:
1128
+ raise RuntimeError("Empty waiter is already set")
1129
+ self._empty_waiter = self._loop.create_future()
1130
+ if not self._buffer:
1131
+ self._empty_waiter.set_result(None)
1132
+ return self._empty_waiter
1133
+
1134
+ def _reset_empty_waiter(self):
1135
+ self._empty_waiter = None
1136
+
1137
+
1138
+ class _SelectorDatagramTransport(_SelectorTransport):
1139
+
1140
+ _buffer_factory = collections.deque
1141
+
1142
+ def __init__(self, loop, sock, protocol, address=None,
1143
+ waiter=None, extra=None):
1144
+ super().__init__(loop, sock, protocol, extra)
1145
+ self._address = address
1146
+ self._buffer_size = 0
1147
+ self._loop.call_soon(self._protocol.connection_made, self)
1148
+ # only start reading when connection_made() has been called
1149
+ self._loop.call_soon(self._add_reader,
1150
+ self._sock_fd, self._read_ready)
1151
+ if waiter is not None:
1152
+ # only wake up the waiter when connection_made() has been called
1153
+ self._loop.call_soon(futures._set_result_unless_cancelled,
1154
+ waiter, None)
1155
+
1156
+ def get_write_buffer_size(self):
1157
+ return self._buffer_size
1158
+
1159
+ def _read_ready(self):
1160
+ if self._conn_lost:
1161
+ return
1162
+ try:
1163
+ data, addr = self._sock.recvfrom(self.max_size)
1164
+ except (BlockingIOError, InterruptedError):
1165
+ pass
1166
+ except OSError as exc:
1167
+ self._protocol.error_received(exc)
1168
+ except (SystemExit, KeyboardInterrupt):
1169
+ raise
1170
+ except BaseException as exc:
1171
+ self._fatal_error(exc, 'Fatal read error on datagram transport')
1172
+ else:
1173
+ self._protocol.datagram_received(data, addr)
1174
+
1175
+ def sendto(self, data, addr=None):
1176
+ if not isinstance(data, (bytes, bytearray, memoryview)):
1177
+ raise TypeError(f'data argument must be a bytes-like object, '
1178
+ f'not {type(data).__name__!r}')
1179
+ if not data:
1180
+ return
1181
+
1182
+ if self._address:
1183
+ if addr not in (None, self._address):
1184
+ raise ValueError(
1185
+ f'Invalid address: must be None or {self._address}')
1186
+ addr = self._address
1187
+
1188
+ if self._conn_lost and self._address:
1189
+ if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
1190
+ logger.warning('socket.send() raised exception.')
1191
+ self._conn_lost += 1
1192
+ return
1193
+
1194
+ if not self._buffer:
1195
+ # Attempt to send it right away first.
1196
+ try:
1197
+ if self._extra['peername']:
1198
+ self._sock.send(data)
1199
+ else:
1200
+ self._sock.sendto(data, addr)
1201
+ return
1202
+ except (BlockingIOError, InterruptedError):
1203
+ self._loop._add_writer(self._sock_fd, self._sendto_ready)
1204
+ except OSError as exc:
1205
+ self._protocol.error_received(exc)
1206
+ return
1207
+ except (SystemExit, KeyboardInterrupt):
1208
+ raise
1209
+ except BaseException as exc:
1210
+ self._fatal_error(
1211
+ exc, 'Fatal write error on datagram transport')
1212
+ return
1213
+
1214
+ # Ensure that what we buffer is immutable.
1215
+ self._buffer.append((bytes(data), addr))
1216
+ self._buffer_size += len(data)
1217
+ self._maybe_pause_protocol()
1218
+
1219
+ def _sendto_ready(self):
1220
+ while self._buffer:
1221
+ data, addr = self._buffer.popleft()
1222
+ self._buffer_size -= len(data)
1223
+ try:
1224
+ if self._extra['peername']:
1225
+ self._sock.send(data)
1226
+ else:
1227
+ self._sock.sendto(data, addr)
1228
+ except (BlockingIOError, InterruptedError):
1229
+ self._buffer.appendleft((data, addr)) # Try again later.
1230
+ self._buffer_size += len(data)
1231
+ break
1232
+ except OSError as exc:
1233
+ self._protocol.error_received(exc)
1234
+ return
1235
+ except (SystemExit, KeyboardInterrupt):
1236
+ raise
1237
+ except BaseException as exc:
1238
+ self._fatal_error(
1239
+ exc, 'Fatal write error on datagram transport')
1240
+ return
1241
+
1242
+ self._maybe_resume_protocol() # May append to buffer.
1243
+ if not self._buffer:
1244
+ self._loop._remove_writer(self._sock_fd)
1245
+ if self._closing:
1246
+ self._call_connection_lost(None)
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/sslproto.py ADDED
@@ -0,0 +1,926 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contains code from https://github.com/MagicStack/uvloop/tree/v0.16.0
2
+ # SPDX-License-Identifier: PSF-2.0 AND (MIT OR Apache-2.0)
3
+ # SPDX-FileCopyrightText: Copyright (c) 2015-2021 MagicStack Inc. http://magic.io
4
+
5
+ import collections
6
+ import enum
7
+ import warnings
8
+ try:
9
+ import ssl
10
+ except ImportError: # pragma: no cover
11
+ ssl = None
12
+
13
+ from . import constants
14
+ from . import exceptions
15
+ from . import protocols
16
+ from . import transports
17
+ from .log import logger
18
+
19
+ if ssl is not None:
20
+ SSLAgainErrors = (ssl.SSLWantReadError, ssl.SSLSyscallError)
21
+
22
+
23
+ class SSLProtocolState(enum.Enum):
24
+ UNWRAPPED = "UNWRAPPED"
25
+ DO_HANDSHAKE = "DO_HANDSHAKE"
26
+ WRAPPED = "WRAPPED"
27
+ FLUSHING = "FLUSHING"
28
+ SHUTDOWN = "SHUTDOWN"
29
+
30
+
31
+ class AppProtocolState(enum.Enum):
32
+ # This tracks the state of app protocol (https://git.io/fj59P):
33
+ #
34
+ # INIT -cm-> CON_MADE [-dr*->] [-er-> EOF?] -cl-> CON_LOST
35
+ #
36
+ # * cm: connection_made()
37
+ # * dr: data_received()
38
+ # * er: eof_received()
39
+ # * cl: connection_lost()
40
+
41
+ STATE_INIT = "STATE_INIT"
42
+ STATE_CON_MADE = "STATE_CON_MADE"
43
+ STATE_EOF = "STATE_EOF"
44
+ STATE_CON_LOST = "STATE_CON_LOST"
45
+
46
+
47
+ def _create_transport_context(server_side, server_hostname):
48
+ if server_side:
49
+ raise ValueError('Server side SSL needs a valid SSLContext')
50
+
51
+ # Client side may pass ssl=True to use a default
52
+ # context; in that case the sslcontext passed is None.
53
+ # The default is secure for client connections.
54
+ # Python 3.4+: use up-to-date strong settings.
55
+ sslcontext = ssl.create_default_context()
56
+ if not server_hostname:
57
+ sslcontext.check_hostname = False
58
+ return sslcontext
59
+
60
+
61
+ def add_flowcontrol_defaults(high, low, kb):
62
+ if high is None:
63
+ if low is None:
64
+ hi = kb * 1024
65
+ else:
66
+ lo = low
67
+ hi = 4 * lo
68
+ else:
69
+ hi = high
70
+ if low is None:
71
+ lo = hi // 4
72
+ else:
73
+ lo = low
74
+
75
+ if not hi >= lo >= 0:
76
+ raise ValueError('high (%r) must be >= low (%r) must be >= 0' %
77
+ (hi, lo))
78
+
79
+ return hi, lo
80
+
81
+
82
+ class _SSLProtocolTransport(transports._FlowControlMixin,
83
+ transports.Transport):
84
+
85
+ _start_tls_compatible = True
86
+ _sendfile_compatible = constants._SendfileMode.FALLBACK
87
+
88
+ def __init__(self, loop, ssl_protocol):
89
+ self._loop = loop
90
+ self._ssl_protocol = ssl_protocol
91
+ self._closed = False
92
+
93
+ def get_extra_info(self, name, default=None):
94
+ """Get optional transport information."""
95
+ return self._ssl_protocol._get_extra_info(name, default)
96
+
97
+ def set_protocol(self, protocol):
98
+ self._ssl_protocol._set_app_protocol(protocol)
99
+
100
+ def get_protocol(self):
101
+ return self._ssl_protocol._app_protocol
102
+
103
+ def is_closing(self):
104
+ return self._closed
105
+
106
+ def close(self):
107
+ """Close the transport.
108
+
109
+ Buffered data will be flushed asynchronously. No more data
110
+ will be received. After all buffered data is flushed, the
111
+ protocol's connection_lost() method will (eventually) called
112
+ with None as its argument.
113
+ """
114
+ if not self._closed:
115
+ self._closed = True
116
+ self._ssl_protocol._start_shutdown()
117
+ else:
118
+ self._ssl_protocol = None
119
+
120
+ def __del__(self, _warnings=warnings):
121
+ if not self._closed:
122
+ self._closed = True
123
+ _warnings.warn(
124
+ "unclosed transport <asyncio._SSLProtocolTransport "
125
+ "object>", ResourceWarning)
126
+
127
+ def is_reading(self):
128
+ return not self._ssl_protocol._app_reading_paused
129
+
130
+ def pause_reading(self):
131
+ """Pause the receiving end.
132
+
133
+ No data will be passed to the protocol's data_received()
134
+ method until resume_reading() is called.
135
+ """
136
+ self._ssl_protocol._pause_reading()
137
+
138
+ def resume_reading(self):
139
+ """Resume the receiving end.
140
+
141
+ Data received will once again be passed to the protocol's
142
+ data_received() method.
143
+ """
144
+ self._ssl_protocol._resume_reading()
145
+
146
+ def set_write_buffer_limits(self, high=None, low=None):
147
+ """Set the high- and low-water limits for write flow control.
148
+
149
+ These two values control when to call the protocol's
150
+ pause_writing() and resume_writing() methods. If specified,
151
+ the low-water limit must be less than or equal to the
152
+ high-water limit. Neither value can be negative.
153
+
154
+ The defaults are implementation-specific. If only the
155
+ high-water limit is given, the low-water limit defaults to an
156
+ implementation-specific value less than or equal to the
157
+ high-water limit. Setting high to zero forces low to zero as
158
+ well, and causes pause_writing() to be called whenever the
159
+ buffer becomes non-empty. Setting low to zero causes
160
+ resume_writing() to be called only once the buffer is empty.
161
+ Use of zero for either limit is generally sub-optimal as it
162
+ reduces opportunities for doing I/O and computation
163
+ concurrently.
164
+ """
165
+ self._ssl_protocol._set_write_buffer_limits(high, low)
166
+ self._ssl_protocol._control_app_writing()
167
+
168
+ def get_write_buffer_limits(self):
169
+ return (self._ssl_protocol._outgoing_low_water,
170
+ self._ssl_protocol._outgoing_high_water)
171
+
172
+ def get_write_buffer_size(self):
173
+ """Return the current size of the write buffers."""
174
+ return self._ssl_protocol._get_write_buffer_size()
175
+
176
+ def set_read_buffer_limits(self, high=None, low=None):
177
+ """Set the high- and low-water limits for read flow control.
178
+
179
+ These two values control when to call the upstream transport's
180
+ pause_reading() and resume_reading() methods. If specified,
181
+ the low-water limit must be less than or equal to the
182
+ high-water limit. Neither value can be negative.
183
+
184
+ The defaults are implementation-specific. If only the
185
+ high-water limit is given, the low-water limit defaults to an
186
+ implementation-specific value less than or equal to the
187
+ high-water limit. Setting high to zero forces low to zero as
188
+ well, and causes pause_reading() to be called whenever the
189
+ buffer becomes non-empty. Setting low to zero causes
190
+ resume_reading() to be called only once the buffer is empty.
191
+ Use of zero for either limit is generally sub-optimal as it
192
+ reduces opportunities for doing I/O and computation
193
+ concurrently.
194
+ """
195
+ self._ssl_protocol._set_read_buffer_limits(high, low)
196
+ self._ssl_protocol._control_ssl_reading()
197
+
198
+ def get_read_buffer_limits(self):
199
+ return (self._ssl_protocol._incoming_low_water,
200
+ self._ssl_protocol._incoming_high_water)
201
+
202
+ def get_read_buffer_size(self):
203
+ """Return the current size of the read buffer."""
204
+ return self._ssl_protocol._get_read_buffer_size()
205
+
206
+ @property
207
+ def _protocol_paused(self):
208
+ # Required for sendfile fallback pause_writing/resume_writing logic
209
+ return self._ssl_protocol._app_writing_paused
210
+
211
+ def write(self, data):
212
+ """Write some data bytes to the transport.
213
+
214
+ This does not block; it buffers the data and arranges for it
215
+ to be sent out asynchronously.
216
+ """
217
+ if not isinstance(data, (bytes, bytearray, memoryview)):
218
+ raise TypeError(f"data: expecting a bytes-like instance, "
219
+ f"got {type(data).__name__}")
220
+ if not data:
221
+ return
222
+ self._ssl_protocol._write_appdata((data,))
223
+
224
+ def writelines(self, list_of_data):
225
+ """Write a list (or any iterable) of data bytes to the transport.
226
+
227
+ The default implementation concatenates the arguments and
228
+ calls write() on the result.
229
+ """
230
+ self._ssl_protocol._write_appdata(list_of_data)
231
+
232
+ def write_eof(self):
233
+ """Close the write end after flushing buffered data.
234
+
235
+ This raises :exc:`NotImplementedError` right now.
236
+ """
237
+ raise NotImplementedError
238
+
239
+ def can_write_eof(self):
240
+ """Return True if this transport supports write_eof(), False if not."""
241
+ return False
242
+
243
+ def abort(self):
244
+ """Close the transport immediately.
245
+
246
+ Buffered data will be lost. No more data will be received.
247
+ The protocol's connection_lost() method will (eventually) be
248
+ called with None as its argument.
249
+ """
250
+ self._force_close(None)
251
+
252
+ def _force_close(self, exc):
253
+ self._closed = True
254
+ if self._ssl_protocol is not None:
255
+ self._ssl_protocol._abort(exc)
256
+
257
+ def _test__append_write_backlog(self, data):
258
+ # for test only
259
+ self._ssl_protocol._write_backlog.append(data)
260
+ self._ssl_protocol._write_buffer_size += len(data)
261
+
262
+
263
+ class SSLProtocol(protocols.BufferedProtocol):
264
+ max_size = 256 * 1024 # Buffer size passed to read()
265
+
266
+ _handshake_start_time = None
267
+ _handshake_timeout_handle = None
268
+ _shutdown_timeout_handle = None
269
+
270
+ def __init__(self, loop, app_protocol, sslcontext, waiter,
271
+ server_side=False, server_hostname=None,
272
+ call_connection_made=True,
273
+ ssl_handshake_timeout=None,
274
+ ssl_shutdown_timeout=None):
275
+ if ssl is None:
276
+ raise RuntimeError("stdlib ssl module not available")
277
+
278
+ self._ssl_buffer = bytearray(self.max_size)
279
+ self._ssl_buffer_view = memoryview(self._ssl_buffer)
280
+
281
+ if ssl_handshake_timeout is None:
282
+ ssl_handshake_timeout = constants.SSL_HANDSHAKE_TIMEOUT
283
+ elif ssl_handshake_timeout <= 0:
284
+ raise ValueError(
285
+ f"ssl_handshake_timeout should be a positive number, "
286
+ f"got {ssl_handshake_timeout}")
287
+ if ssl_shutdown_timeout is None:
288
+ ssl_shutdown_timeout = constants.SSL_SHUTDOWN_TIMEOUT
289
+ elif ssl_shutdown_timeout <= 0:
290
+ raise ValueError(
291
+ f"ssl_shutdown_timeout should be a positive number, "
292
+ f"got {ssl_shutdown_timeout}")
293
+
294
+ if not sslcontext:
295
+ sslcontext = _create_transport_context(
296
+ server_side, server_hostname)
297
+
298
+ self._server_side = server_side
299
+ if server_hostname and not server_side:
300
+ self._server_hostname = server_hostname
301
+ else:
302
+ self._server_hostname = None
303
+ self._sslcontext = sslcontext
304
+ # SSL-specific extra info. More info are set when the handshake
305
+ # completes.
306
+ self._extra = dict(sslcontext=sslcontext)
307
+
308
+ # App data write buffering
309
+ self._write_backlog = collections.deque()
310
+ self._write_buffer_size = 0
311
+
312
+ self._waiter = waiter
313
+ self._loop = loop
314
+ self._set_app_protocol(app_protocol)
315
+ self._app_transport = None
316
+ self._app_transport_created = False
317
+ # transport, ex: SelectorSocketTransport
318
+ self._transport = None
319
+ self._ssl_handshake_timeout = ssl_handshake_timeout
320
+ self._ssl_shutdown_timeout = ssl_shutdown_timeout
321
+ # SSL and state machine
322
+ self._incoming = ssl.MemoryBIO()
323
+ self._outgoing = ssl.MemoryBIO()
324
+ self._state = SSLProtocolState.UNWRAPPED
325
+ self._conn_lost = 0 # Set when connection_lost called
326
+ if call_connection_made:
327
+ self._app_state = AppProtocolState.STATE_INIT
328
+ else:
329
+ self._app_state = AppProtocolState.STATE_CON_MADE
330
+ self._sslobj = self._sslcontext.wrap_bio(
331
+ self._incoming, self._outgoing,
332
+ server_side=self._server_side,
333
+ server_hostname=self._server_hostname)
334
+
335
+ # Flow Control
336
+
337
+ self._ssl_writing_paused = False
338
+
339
+ self._app_reading_paused = False
340
+
341
+ self._ssl_reading_paused = False
342
+ self._incoming_high_water = 0
343
+ self._incoming_low_water = 0
344
+ self._set_read_buffer_limits()
345
+ self._eof_received = False
346
+
347
+ self._app_writing_paused = False
348
+ self._outgoing_high_water = 0
349
+ self._outgoing_low_water = 0
350
+ self._set_write_buffer_limits()
351
+ self._get_app_transport()
352
+
353
+ def _set_app_protocol(self, app_protocol):
354
+ self._app_protocol = app_protocol
355
+ # Make fast hasattr check first
356
+ if (hasattr(app_protocol, 'get_buffer') and
357
+ isinstance(app_protocol, protocols.BufferedProtocol)):
358
+ self._app_protocol_get_buffer = app_protocol.get_buffer
359
+ self._app_protocol_buffer_updated = app_protocol.buffer_updated
360
+ self._app_protocol_is_buffer = True
361
+ else:
362
+ self._app_protocol_is_buffer = False
363
+
364
+ def _wakeup_waiter(self, exc=None):
365
+ if self._waiter is None:
366
+ return
367
+ if not self._waiter.cancelled():
368
+ if exc is not None:
369
+ self._waiter.set_exception(exc)
370
+ else:
371
+ self._waiter.set_result(None)
372
+ self._waiter = None
373
+
374
+ def _get_app_transport(self):
375
+ if self._app_transport is None:
376
+ if self._app_transport_created:
377
+ raise RuntimeError('Creating _SSLProtocolTransport twice')
378
+ self._app_transport = _SSLProtocolTransport(self._loop, self)
379
+ self._app_transport_created = True
380
+ return self._app_transport
381
+
382
+ def connection_made(self, transport):
383
+ """Called when the low-level connection is made.
384
+
385
+ Start the SSL handshake.
386
+ """
387
+ self._transport = transport
388
+ self._start_handshake()
389
+
390
+ def connection_lost(self, exc):
391
+ """Called when the low-level connection is lost or closed.
392
+
393
+ The argument is an exception object or None (the latter
394
+ meaning a regular EOF is received or the connection was
395
+ aborted or closed).
396
+ """
397
+ self._write_backlog.clear()
398
+ self._outgoing.read()
399
+ self._conn_lost += 1
400
+
401
+ # Just mark the app transport as closed so that its __dealloc__
402
+ # doesn't complain.
403
+ if self._app_transport is not None:
404
+ self._app_transport._closed = True
405
+
406
+ if self._state != SSLProtocolState.DO_HANDSHAKE:
407
+ if (
408
+ self._app_state == AppProtocolState.STATE_CON_MADE or
409
+ self._app_state == AppProtocolState.STATE_EOF
410
+ ):
411
+ self._app_state = AppProtocolState.STATE_CON_LOST
412
+ self._loop.call_soon(self._app_protocol.connection_lost, exc)
413
+ self._set_state(SSLProtocolState.UNWRAPPED)
414
+ self._transport = None
415
+ self._app_transport = None
416
+ self._app_protocol = None
417
+ self._wakeup_waiter(exc)
418
+
419
+ if self._shutdown_timeout_handle:
420
+ self._shutdown_timeout_handle.cancel()
421
+ self._shutdown_timeout_handle = None
422
+ if self._handshake_timeout_handle:
423
+ self._handshake_timeout_handle.cancel()
424
+ self._handshake_timeout_handle = None
425
+
426
+ def get_buffer(self, n):
427
+ want = n
428
+ if want <= 0 or want > self.max_size:
429
+ want = self.max_size
430
+ if len(self._ssl_buffer) < want:
431
+ self._ssl_buffer = bytearray(want)
432
+ self._ssl_buffer_view = memoryview(self._ssl_buffer)
433
+ return self._ssl_buffer_view
434
+
435
+ def buffer_updated(self, nbytes):
436
+ self._incoming.write(self._ssl_buffer_view[:nbytes])
437
+
438
+ if self._state == SSLProtocolState.DO_HANDSHAKE:
439
+ self._do_handshake()
440
+
441
+ elif self._state == SSLProtocolState.WRAPPED:
442
+ self._do_read()
443
+
444
+ elif self._state == SSLProtocolState.FLUSHING:
445
+ self._do_flush()
446
+
447
+ elif self._state == SSLProtocolState.SHUTDOWN:
448
+ self._do_shutdown()
449
+
450
+ def eof_received(self):
451
+ """Called when the other end of the low-level stream
452
+ is half-closed.
453
+
454
+ If this returns a false value (including None), the transport
455
+ will close itself. If it returns a true value, closing the
456
+ transport is up to the protocol.
457
+ """
458
+ self._eof_received = True
459
+ try:
460
+ if self._loop.get_debug():
461
+ logger.debug("%r received EOF", self)
462
+
463
+ if self._state == SSLProtocolState.DO_HANDSHAKE:
464
+ self._on_handshake_complete(ConnectionResetError)
465
+
466
+ elif self._state == SSLProtocolState.WRAPPED:
467
+ self._set_state(SSLProtocolState.FLUSHING)
468
+ if self._app_reading_paused:
469
+ return True
470
+ else:
471
+ self._do_flush()
472
+
473
+ elif self._state == SSLProtocolState.FLUSHING:
474
+ self._do_write()
475
+ self._set_state(SSLProtocolState.SHUTDOWN)
476
+ self._do_shutdown()
477
+
478
+ elif self._state == SSLProtocolState.SHUTDOWN:
479
+ self._do_shutdown()
480
+
481
+ except Exception:
482
+ self._transport.close()
483
+ raise
484
+
485
+ def _get_extra_info(self, name, default=None):
486
+ if name in self._extra:
487
+ return self._extra[name]
488
+ elif self._transport is not None:
489
+ return self._transport.get_extra_info(name, default)
490
+ else:
491
+ return default
492
+
493
+ def _set_state(self, new_state):
494
+ allowed = False
495
+
496
+ if new_state == SSLProtocolState.UNWRAPPED:
497
+ allowed = True
498
+
499
+ elif (
500
+ self._state == SSLProtocolState.UNWRAPPED and
501
+ new_state == SSLProtocolState.DO_HANDSHAKE
502
+ ):
503
+ allowed = True
504
+
505
+ elif (
506
+ self._state == SSLProtocolState.DO_HANDSHAKE and
507
+ new_state == SSLProtocolState.WRAPPED
508
+ ):
509
+ allowed = True
510
+
511
+ elif (
512
+ self._state == SSLProtocolState.WRAPPED and
513
+ new_state == SSLProtocolState.FLUSHING
514
+ ):
515
+ allowed = True
516
+
517
+ elif (
518
+ self._state == SSLProtocolState.FLUSHING and
519
+ new_state == SSLProtocolState.SHUTDOWN
520
+ ):
521
+ allowed = True
522
+
523
+ if allowed:
524
+ self._state = new_state
525
+
526
+ else:
527
+ raise RuntimeError(
528
+ 'cannot switch state from {} to {}'.format(
529
+ self._state, new_state))
530
+
531
+ # Handshake flow
532
+
533
+ def _start_handshake(self):
534
+ if self._loop.get_debug():
535
+ logger.debug("%r starts SSL handshake", self)
536
+ self._handshake_start_time = self._loop.time()
537
+ else:
538
+ self._handshake_start_time = None
539
+
540
+ self._set_state(SSLProtocolState.DO_HANDSHAKE)
541
+
542
+ # start handshake timeout count down
543
+ self._handshake_timeout_handle = \
544
+ self._loop.call_later(self._ssl_handshake_timeout,
545
+ lambda: self._check_handshake_timeout())
546
+
547
+ self._do_handshake()
548
+
549
+ def _check_handshake_timeout(self):
550
+ if self._state == SSLProtocolState.DO_HANDSHAKE:
551
+ msg = (
552
+ f"SSL handshake is taking longer than "
553
+ f"{self._ssl_handshake_timeout} seconds: "
554
+ f"aborting the connection"
555
+ )
556
+ self._fatal_error(ConnectionAbortedError(msg))
557
+
558
+ def _do_handshake(self):
559
+ try:
560
+ self._sslobj.do_handshake()
561
+ except SSLAgainErrors:
562
+ self._process_outgoing()
563
+ except ssl.SSLError as exc:
564
+ self._on_handshake_complete(exc)
565
+ else:
566
+ self._on_handshake_complete(None)
567
+
568
+ def _on_handshake_complete(self, handshake_exc):
569
+ if self._handshake_timeout_handle is not None:
570
+ self._handshake_timeout_handle.cancel()
571
+ self._handshake_timeout_handle = None
572
+
573
+ sslobj = self._sslobj
574
+ try:
575
+ if handshake_exc is None:
576
+ self._set_state(SSLProtocolState.WRAPPED)
577
+ else:
578
+ raise handshake_exc
579
+
580
+ peercert = sslobj.getpeercert()
581
+ except Exception as exc:
582
+ handshake_exc = None
583
+ self._set_state(SSLProtocolState.UNWRAPPED)
584
+ if isinstance(exc, ssl.CertificateError):
585
+ msg = 'SSL handshake failed on verifying the certificate'
586
+ else:
587
+ msg = 'SSL handshake failed'
588
+ self._fatal_error(exc, msg)
589
+ self._wakeup_waiter(exc)
590
+ return
591
+
592
+ if self._loop.get_debug():
593
+ dt = self._loop.time() - self._handshake_start_time
594
+ logger.debug("%r: SSL handshake took %.1f ms", self, dt * 1e3)
595
+
596
+ # Add extra info that becomes available after handshake.
597
+ self._extra.update(peercert=peercert,
598
+ cipher=sslobj.cipher(),
599
+ compression=sslobj.compression(),
600
+ ssl_object=sslobj)
601
+ if self._app_state == AppProtocolState.STATE_INIT:
602
+ self._app_state = AppProtocolState.STATE_CON_MADE
603
+ self._app_protocol.connection_made(self._get_app_transport())
604
+ self._wakeup_waiter()
605
+ self._do_read()
606
+
607
+ # Shutdown flow
608
+
609
+ def _start_shutdown(self):
610
+ if (
611
+ self._state in (
612
+ SSLProtocolState.FLUSHING,
613
+ SSLProtocolState.SHUTDOWN,
614
+ SSLProtocolState.UNWRAPPED
615
+ )
616
+ ):
617
+ return
618
+ if self._app_transport is not None:
619
+ self._app_transport._closed = True
620
+ if self._state == SSLProtocolState.DO_HANDSHAKE:
621
+ self._abort(None)
622
+ else:
623
+ self._set_state(SSLProtocolState.FLUSHING)
624
+ self._shutdown_timeout_handle = self._loop.call_later(
625
+ self._ssl_shutdown_timeout,
626
+ lambda: self._check_shutdown_timeout()
627
+ )
628
+ self._do_flush()
629
+
630
+ def _check_shutdown_timeout(self):
631
+ if (
632
+ self._state in (
633
+ SSLProtocolState.FLUSHING,
634
+ SSLProtocolState.SHUTDOWN
635
+ )
636
+ ):
637
+ self._transport._force_close(
638
+ exceptions.TimeoutError('SSL shutdown timed out'))
639
+
640
+ def _do_flush(self):
641
+ self._do_read()
642
+ self._set_state(SSLProtocolState.SHUTDOWN)
643
+ self._do_shutdown()
644
+
645
+ def _do_shutdown(self):
646
+ try:
647
+ if not self._eof_received:
648
+ self._sslobj.unwrap()
649
+ except SSLAgainErrors:
650
+ self._process_outgoing()
651
+ except ssl.SSLError as exc:
652
+ self._on_shutdown_complete(exc)
653
+ else:
654
+ self._process_outgoing()
655
+ self._call_eof_received()
656
+ self._on_shutdown_complete(None)
657
+
658
+ def _on_shutdown_complete(self, shutdown_exc):
659
+ if self._shutdown_timeout_handle is not None:
660
+ self._shutdown_timeout_handle.cancel()
661
+ self._shutdown_timeout_handle = None
662
+
663
+ if shutdown_exc:
664
+ self._fatal_error(shutdown_exc)
665
+ else:
666
+ self._loop.call_soon(self._transport.close)
667
+
668
+ def _abort(self, exc):
669
+ self._set_state(SSLProtocolState.UNWRAPPED)
670
+ if self._transport is not None:
671
+ self._transport._force_close(exc)
672
+
673
+ # Outgoing flow
674
+
675
+ def _write_appdata(self, list_of_data):
676
+ if (
677
+ self._state in (
678
+ SSLProtocolState.FLUSHING,
679
+ SSLProtocolState.SHUTDOWN,
680
+ SSLProtocolState.UNWRAPPED
681
+ )
682
+ ):
683
+ if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
684
+ logger.warning('SSL connection is closed')
685
+ self._conn_lost += 1
686
+ return
687
+
688
+ for data in list_of_data:
689
+ self._write_backlog.append(data)
690
+ self._write_buffer_size += len(data)
691
+
692
+ try:
693
+ if self._state == SSLProtocolState.WRAPPED:
694
+ self._do_write()
695
+
696
+ except Exception as ex:
697
+ self._fatal_error(ex, 'Fatal error on SSL protocol')
698
+
699
+ def _do_write(self):
700
+ try:
701
+ while self._write_backlog:
702
+ data = self._write_backlog[0]
703
+ count = self._sslobj.write(data)
704
+ data_len = len(data)
705
+ if count < data_len:
706
+ self._write_backlog[0] = data[count:]
707
+ self._write_buffer_size -= count
708
+ else:
709
+ del self._write_backlog[0]
710
+ self._write_buffer_size -= data_len
711
+ except SSLAgainErrors:
712
+ pass
713
+ self._process_outgoing()
714
+
715
+ def _process_outgoing(self):
716
+ if not self._ssl_writing_paused:
717
+ data = self._outgoing.read()
718
+ if len(data):
719
+ self._transport.write(data)
720
+ self._control_app_writing()
721
+
722
+ # Incoming flow
723
+
724
+ def _do_read(self):
725
+ if (
726
+ self._state not in (
727
+ SSLProtocolState.WRAPPED,
728
+ SSLProtocolState.FLUSHING,
729
+ )
730
+ ):
731
+ return
732
+ try:
733
+ if not self._app_reading_paused:
734
+ if self._app_protocol_is_buffer:
735
+ self._do_read__buffered()
736
+ else:
737
+ self._do_read__copied()
738
+ if self._write_backlog:
739
+ self._do_write()
740
+ else:
741
+ self._process_outgoing()
742
+ self._control_ssl_reading()
743
+ except Exception as ex:
744
+ self._fatal_error(ex, 'Fatal error on SSL protocol')
745
+
746
+ def _do_read__buffered(self):
747
+ offset = 0
748
+ count = 1
749
+
750
+ buf = self._app_protocol_get_buffer(self._get_read_buffer_size())
751
+ wants = len(buf)
752
+
753
+ try:
754
+ count = self._sslobj.read(wants, buf)
755
+
756
+ if count > 0:
757
+ offset = count
758
+ while offset < wants:
759
+ count = self._sslobj.read(wants - offset, buf[offset:])
760
+ if count > 0:
761
+ offset += count
762
+ else:
763
+ break
764
+ else:
765
+ self._loop.call_soon(lambda: self._do_read())
766
+ except SSLAgainErrors:
767
+ pass
768
+ if offset > 0:
769
+ self._app_protocol_buffer_updated(offset)
770
+ if not count:
771
+ # close_notify
772
+ self._call_eof_received()
773
+ self._start_shutdown()
774
+
775
+ def _do_read__copied(self):
776
+ chunk = b'1'
777
+ zero = True
778
+ one = False
779
+
780
+ try:
781
+ while True:
782
+ chunk = self._sslobj.read(self.max_size)
783
+ if not chunk:
784
+ break
785
+ if zero:
786
+ zero = False
787
+ one = True
788
+ first = chunk
789
+ elif one:
790
+ one = False
791
+ data = [first, chunk]
792
+ else:
793
+ data.append(chunk)
794
+ except SSLAgainErrors:
795
+ pass
796
+ if one:
797
+ self._app_protocol.data_received(first)
798
+ elif not zero:
799
+ self._app_protocol.data_received(b''.join(data))
800
+ if not chunk:
801
+ # close_notify
802
+ self._call_eof_received()
803
+ self._start_shutdown()
804
+
805
+ def _call_eof_received(self):
806
+ try:
807
+ if self._app_state == AppProtocolState.STATE_CON_MADE:
808
+ self._app_state = AppProtocolState.STATE_EOF
809
+ keep_open = self._app_protocol.eof_received()
810
+ if keep_open:
811
+ logger.warning('returning true from eof_received() '
812
+ 'has no effect when using ssl')
813
+ except (KeyboardInterrupt, SystemExit):
814
+ raise
815
+ except BaseException as ex:
816
+ self._fatal_error(ex, 'Error calling eof_received()')
817
+
818
+ # Flow control for writes from APP socket
819
+
820
+ def _control_app_writing(self):
821
+ size = self._get_write_buffer_size()
822
+ if size >= self._outgoing_high_water and not self._app_writing_paused:
823
+ self._app_writing_paused = True
824
+ try:
825
+ self._app_protocol.pause_writing()
826
+ except (KeyboardInterrupt, SystemExit):
827
+ raise
828
+ except BaseException as exc:
829
+ self._loop.call_exception_handler({
830
+ 'message': 'protocol.pause_writing() failed',
831
+ 'exception': exc,
832
+ 'transport': self._app_transport,
833
+ 'protocol': self,
834
+ })
835
+ elif size <= self._outgoing_low_water and self._app_writing_paused:
836
+ self._app_writing_paused = False
837
+ try:
838
+ self._app_protocol.resume_writing()
839
+ except (KeyboardInterrupt, SystemExit):
840
+ raise
841
+ except BaseException as exc:
842
+ self._loop.call_exception_handler({
843
+ 'message': 'protocol.resume_writing() failed',
844
+ 'exception': exc,
845
+ 'transport': self._app_transport,
846
+ 'protocol': self,
847
+ })
848
+
849
+ def _get_write_buffer_size(self):
850
+ return self._outgoing.pending + self._write_buffer_size
851
+
852
+ def _set_write_buffer_limits(self, high=None, low=None):
853
+ high, low = add_flowcontrol_defaults(
854
+ high, low, constants.FLOW_CONTROL_HIGH_WATER_SSL_WRITE)
855
+ self._outgoing_high_water = high
856
+ self._outgoing_low_water = low
857
+
858
+ # Flow control for reads to APP socket
859
+
860
+ def _pause_reading(self):
861
+ self._app_reading_paused = True
862
+
863
+ def _resume_reading(self):
864
+ if self._app_reading_paused:
865
+ self._app_reading_paused = False
866
+
867
+ def resume():
868
+ if self._state == SSLProtocolState.WRAPPED:
869
+ self._do_read()
870
+ elif self._state == SSLProtocolState.FLUSHING:
871
+ self._do_flush()
872
+ elif self._state == SSLProtocolState.SHUTDOWN:
873
+ self._do_shutdown()
874
+ self._loop.call_soon(resume)
875
+
876
+ # Flow control for reads from SSL socket
877
+
878
+ def _control_ssl_reading(self):
879
+ size = self._get_read_buffer_size()
880
+ if size >= self._incoming_high_water and not self._ssl_reading_paused:
881
+ self._ssl_reading_paused = True
882
+ self._transport.pause_reading()
883
+ elif size <= self._incoming_low_water and self._ssl_reading_paused:
884
+ self._ssl_reading_paused = False
885
+ self._transport.resume_reading()
886
+
887
+ def _set_read_buffer_limits(self, high=None, low=None):
888
+ high, low = add_flowcontrol_defaults(
889
+ high, low, constants.FLOW_CONTROL_HIGH_WATER_SSL_READ)
890
+ self._incoming_high_water = high
891
+ self._incoming_low_water = low
892
+
893
+ def _get_read_buffer_size(self):
894
+ return self._incoming.pending
895
+
896
+ # Flow control for writes to SSL socket
897
+
898
+ def pause_writing(self):
899
+ """Called when the low-level transport's buffer goes over
900
+ the high-water mark.
901
+ """
902
+ assert not self._ssl_writing_paused
903
+ self._ssl_writing_paused = True
904
+
905
+ def resume_writing(self):
906
+ """Called when the low-level transport's buffer drains below
907
+ the low-water mark.
908
+ """
909
+ assert self._ssl_writing_paused
910
+ self._ssl_writing_paused = False
911
+ self._process_outgoing()
912
+
913
+ def _fatal_error(self, exc, message='Fatal error on transport'):
914
+ if self._transport:
915
+ self._transport._force_close(exc)
916
+
917
+ if isinstance(exc, OSError):
918
+ if self._loop.get_debug():
919
+ logger.debug("%r: %s", self, message, exc_info=True)
920
+ elif not isinstance(exc, exceptions.CancelledError):
921
+ self._loop.call_exception_handler({
922
+ 'message': message,
923
+ 'exception': exc,
924
+ 'transport': self._transport,
925
+ 'protocol': self,
926
+ })
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/staggered.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Support for running coroutines in parallel with staggered start times."""
2
+
3
+ __all__ = 'staggered_race',
4
+
5
+ import contextlib
6
+ import typing
7
+
8
+ from . import events
9
+ from . import exceptions as exceptions_mod
10
+ from . import locks
11
+ from . import tasks
12
+
13
+
14
+ async def staggered_race(
15
+ coro_fns: typing.Iterable[typing.Callable[[], typing.Awaitable]],
16
+ delay: typing.Optional[float],
17
+ *,
18
+ loop: events.AbstractEventLoop = None,
19
+ ) -> typing.Tuple[
20
+ typing.Any,
21
+ typing.Optional[int],
22
+ typing.List[typing.Optional[Exception]]
23
+ ]:
24
+ """Run coroutines with staggered start times and take the first to finish.
25
+
26
+ This method takes an iterable of coroutine functions. The first one is
27
+ started immediately. From then on, whenever the immediately preceding one
28
+ fails (raises an exception), or when *delay* seconds has passed, the next
29
+ coroutine is started. This continues until one of the coroutines complete
30
+ successfully, in which case all others are cancelled, or until all
31
+ coroutines fail.
32
+
33
+ The coroutines provided should be well-behaved in the following way:
34
+
35
+ * They should only ``return`` if completed successfully.
36
+
37
+ * They should always raise an exception if they did not complete
38
+ successfully. In particular, if they handle cancellation, they should
39
+ probably reraise, like this::
40
+
41
+ try:
42
+ # do work
43
+ except asyncio.CancelledError:
44
+ # undo partially completed work
45
+ raise
46
+
47
+ Args:
48
+ coro_fns: an iterable of coroutine functions, i.e. callables that
49
+ return a coroutine object when called. Use ``functools.partial`` or
50
+ lambdas to pass arguments.
51
+
52
+ delay: amount of time, in seconds, between starting coroutines. If
53
+ ``None``, the coroutines will run sequentially.
54
+
55
+ loop: the event loop to use.
56
+
57
+ Returns:
58
+ tuple *(winner_result, winner_index, exceptions)* where
59
+
60
+ - *winner_result*: the result of the winning coroutine, or ``None``
61
+ if no coroutines won.
62
+
63
+ - *winner_index*: the index of the winning coroutine in
64
+ ``coro_fns``, or ``None`` if no coroutines won. If the winning
65
+ coroutine may return None on success, *winner_index* can be used
66
+ to definitively determine whether any coroutine won.
67
+
68
+ - *exceptions*: list of exceptions returned by the coroutines.
69
+ ``len(exceptions)`` is equal to the number of coroutines actually
70
+ started, and the order is the same as in ``coro_fns``. The winning
71
+ coroutine's entry is ``None``.
72
+
73
+ """
74
+ # TODO: when we have aiter() and anext(), allow async iterables in coro_fns.
75
+ loop = loop or events.get_running_loop()
76
+ enum_coro_fns = enumerate(coro_fns)
77
+ winner_result = None
78
+ winner_index = None
79
+ exceptions = []
80
+ running_tasks = []
81
+
82
+ async def run_one_coro(
83
+ previous_failed: typing.Optional[locks.Event]) -> None:
84
+ # Wait for the previous task to finish, or for delay seconds
85
+ if previous_failed is not None:
86
+ with contextlib.suppress(exceptions_mod.TimeoutError):
87
+ # Use asyncio.wait_for() instead of asyncio.wait() here, so
88
+ # that if we get cancelled at this point, Event.wait() is also
89
+ # cancelled, otherwise there will be a "Task destroyed but it is
90
+ # pending" later.
91
+ await tasks.wait_for(previous_failed.wait(), delay)
92
+ # Get the next coroutine to run
93
+ try:
94
+ this_index, coro_fn = next(enum_coro_fns)
95
+ except StopIteration:
96
+ return
97
+ # Start task that will run the next coroutine
98
+ this_failed = locks.Event()
99
+ next_task = loop.create_task(run_one_coro(this_failed))
100
+ running_tasks.append(next_task)
101
+ assert len(running_tasks) == this_index + 2
102
+ # Prepare place to put this coroutine's exceptions if not won
103
+ exceptions.append(None)
104
+ assert len(exceptions) == this_index + 1
105
+
106
+ try:
107
+ result = await coro_fn()
108
+ except (SystemExit, KeyboardInterrupt):
109
+ raise
110
+ except BaseException as e:
111
+ exceptions[this_index] = e
112
+ this_failed.set() # Kickstart the next coroutine
113
+ else:
114
+ # Store winner's results
115
+ nonlocal winner_index, winner_result
116
+ assert winner_index is None
117
+ winner_index = this_index
118
+ winner_result = result
119
+ # Cancel all other tasks. We take care to not cancel the current
120
+ # task as well. If we do so, then since there is no `await` after
121
+ # here and CancelledError are usually thrown at one, we will
122
+ # encounter a curious corner case where the current task will end
123
+ # up as done() == True, cancelled() == False, exception() ==
124
+ # asyncio.CancelledError. This behavior is specified in
125
+ # https://bugs.python.org/issue30048
126
+ for i, t in enumerate(running_tasks):
127
+ if i != this_index:
128
+ t.cancel()
129
+
130
+ first_task = loop.create_task(run_one_coro(None))
131
+ running_tasks.append(first_task)
132
+ try:
133
+ # Wait for a growing list of tasks to all finish: poor man's version of
134
+ # curio's TaskGroup or trio's nursery
135
+ done_count = 0
136
+ while done_count != len(running_tasks):
137
+ done, _ = await tasks.wait(running_tasks)
138
+ done_count = len(done)
139
+ # If run_one_coro raises an unhandled exception, it's probably a
140
+ # programming error, and I want to see it.
141
+ if __debug__:
142
+ for d in done:
143
+ if d.done() and not d.cancelled() and d.exception():
144
+ raise d.exception()
145
+ return winner_result, winner_index, exceptions
146
+ finally:
147
+ # Make sure no tasks are left running if we leave this function
148
+ for t in running_tasks:
149
+ t.cancel()
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/streams.py ADDED
@@ -0,0 +1,768 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = (
2
+ 'StreamReader', 'StreamWriter', 'StreamReaderProtocol',
3
+ 'open_connection', 'start_server')
4
+
5
+ import collections
6
+ import socket
7
+ import sys
8
+ import warnings
9
+ import weakref
10
+
11
+ if hasattr(socket, 'AF_UNIX'):
12
+ __all__ += ('open_unix_connection', 'start_unix_server')
13
+
14
+ from . import coroutines
15
+ from . import events
16
+ from . import exceptions
17
+ from . import format_helpers
18
+ from . import protocols
19
+ from .log import logger
20
+ from .tasks import sleep
21
+
22
+
23
+ _DEFAULT_LIMIT = 2 ** 16 # 64 KiB
24
+
25
+
26
+ async def open_connection(host=None, port=None, *,
27
+ limit=_DEFAULT_LIMIT, **kwds):
28
+ """A wrapper for create_connection() returning a (reader, writer) pair.
29
+
30
+ The reader returned is a StreamReader instance; the writer is a
31
+ StreamWriter instance.
32
+
33
+ The arguments are all the usual arguments to create_connection()
34
+ except protocol_factory; most common are positional host and port,
35
+ with various optional keyword arguments following.
36
+
37
+ Additional optional keyword arguments are loop (to set the event loop
38
+ instance to use) and limit (to set the buffer limit passed to the
39
+ StreamReader).
40
+
41
+ (If you want to customize the StreamReader and/or
42
+ StreamReaderProtocol classes, just copy the code -- there's
43
+ really nothing special here except some convenience.)
44
+ """
45
+ loop = events.get_running_loop()
46
+ reader = StreamReader(limit=limit, loop=loop)
47
+ protocol = StreamReaderProtocol(reader, loop=loop)
48
+ transport, _ = await loop.create_connection(
49
+ lambda: protocol, host, port, **kwds)
50
+ writer = StreamWriter(transport, protocol, reader, loop)
51
+ return reader, writer
52
+
53
+
54
+ async def start_server(client_connected_cb, host=None, port=None, *,
55
+ limit=_DEFAULT_LIMIT, **kwds):
56
+ """Start a socket server, call back for each client connected.
57
+
58
+ The first parameter, `client_connected_cb`, takes two parameters:
59
+ client_reader, client_writer. client_reader is a StreamReader
60
+ object, while client_writer is a StreamWriter object. This
61
+ parameter can either be a plain callback function or a coroutine;
62
+ if it is a coroutine, it will be automatically converted into a
63
+ Task.
64
+
65
+ The rest of the arguments are all the usual arguments to
66
+ loop.create_server() except protocol_factory; most common are
67
+ positional host and port, with various optional keyword arguments
68
+ following. The return value is the same as loop.create_server().
69
+
70
+ Additional optional keyword argument is limit (to set the buffer
71
+ limit passed to the StreamReader).
72
+
73
+ The return value is the same as loop.create_server(), i.e. a
74
+ Server object which can be used to stop the service.
75
+ """
76
+ loop = events.get_running_loop()
77
+
78
+ def factory():
79
+ reader = StreamReader(limit=limit, loop=loop)
80
+ protocol = StreamReaderProtocol(reader, client_connected_cb,
81
+ loop=loop)
82
+ return protocol
83
+
84
+ return await loop.create_server(factory, host, port, **kwds)
85
+
86
+
87
+ if hasattr(socket, 'AF_UNIX'):
88
+ # UNIX Domain Sockets are supported on this platform
89
+
90
+ async def open_unix_connection(path=None, *,
91
+ limit=_DEFAULT_LIMIT, **kwds):
92
+ """Similar to `open_connection` but works with UNIX Domain Sockets."""
93
+ loop = events.get_running_loop()
94
+
95
+ reader = StreamReader(limit=limit, loop=loop)
96
+ protocol = StreamReaderProtocol(reader, loop=loop)
97
+ transport, _ = await loop.create_unix_connection(
98
+ lambda: protocol, path, **kwds)
99
+ writer = StreamWriter(transport, protocol, reader, loop)
100
+ return reader, writer
101
+
102
+ async def start_unix_server(client_connected_cb, path=None, *,
103
+ limit=_DEFAULT_LIMIT, **kwds):
104
+ """Similar to `start_server` but works with UNIX Domain Sockets."""
105
+ loop = events.get_running_loop()
106
+
107
+ def factory():
108
+ reader = StreamReader(limit=limit, loop=loop)
109
+ protocol = StreamReaderProtocol(reader, client_connected_cb,
110
+ loop=loop)
111
+ return protocol
112
+
113
+ return await loop.create_unix_server(factory, path, **kwds)
114
+
115
+
116
+ class FlowControlMixin(protocols.Protocol):
117
+ """Reusable flow control logic for StreamWriter.drain().
118
+
119
+ This implements the protocol methods pause_writing(),
120
+ resume_writing() and connection_lost(). If the subclass overrides
121
+ these it must call the super methods.
122
+
123
+ StreamWriter.drain() must wait for _drain_helper() coroutine.
124
+ """
125
+
126
+ def __init__(self, loop=None):
127
+ if loop is None:
128
+ self._loop = events._get_event_loop(stacklevel=4)
129
+ else:
130
+ self._loop = loop
131
+ self._paused = False
132
+ self._drain_waiters = collections.deque()
133
+ self._connection_lost = False
134
+
135
+ def pause_writing(self):
136
+ assert not self._paused
137
+ self._paused = True
138
+ if self._loop.get_debug():
139
+ logger.debug("%r pauses writing", self)
140
+
141
+ def resume_writing(self):
142
+ assert self._paused
143
+ self._paused = False
144
+ if self._loop.get_debug():
145
+ logger.debug("%r resumes writing", self)
146
+
147
+ for waiter in self._drain_waiters:
148
+ if not waiter.done():
149
+ waiter.set_result(None)
150
+
151
+ def connection_lost(self, exc):
152
+ self._connection_lost = True
153
+ # Wake up the writer(s) if currently paused.
154
+ if not self._paused:
155
+ return
156
+
157
+ for waiter in self._drain_waiters:
158
+ if not waiter.done():
159
+ if exc is None:
160
+ waiter.set_result(None)
161
+ else:
162
+ waiter.set_exception(exc)
163
+
164
+ async def _drain_helper(self):
165
+ if self._connection_lost:
166
+ raise ConnectionResetError('Connection lost')
167
+ if not self._paused:
168
+ return
169
+ waiter = self._loop.create_future()
170
+ self._drain_waiters.append(waiter)
171
+ try:
172
+ await waiter
173
+ finally:
174
+ self._drain_waiters.remove(waiter)
175
+
176
+ def _get_close_waiter(self, stream):
177
+ raise NotImplementedError
178
+
179
+
180
+ class StreamReaderProtocol(FlowControlMixin, protocols.Protocol):
181
+ """Helper class to adapt between Protocol and StreamReader.
182
+
183
+ (This is a helper class instead of making StreamReader itself a
184
+ Protocol subclass, because the StreamReader has other potential
185
+ uses, and to prevent the user of the StreamReader to accidentally
186
+ call inappropriate methods of the protocol.)
187
+ """
188
+
189
+ _source_traceback = None
190
+
191
+ def __init__(self, stream_reader, client_connected_cb=None, loop=None):
192
+ super().__init__(loop=loop)
193
+ if stream_reader is not None:
194
+ self._stream_reader_wr = weakref.ref(stream_reader)
195
+ self._source_traceback = stream_reader._source_traceback
196
+ else:
197
+ self._stream_reader_wr = None
198
+ if client_connected_cb is not None:
199
+ # This is a stream created by the `create_server()` function.
200
+ # Keep a strong reference to the reader until a connection
201
+ # is established.
202
+ self._strong_reader = stream_reader
203
+ self._reject_connection = False
204
+ self._stream_writer = None
205
+ self._task = None
206
+ self._transport = None
207
+ self._client_connected_cb = client_connected_cb
208
+ self._over_ssl = False
209
+ self._closed = self._loop.create_future()
210
+
211
+ @property
212
+ def _stream_reader(self):
213
+ if self._stream_reader_wr is None:
214
+ return None
215
+ return self._stream_reader_wr()
216
+
217
+ def _replace_writer(self, writer):
218
+ loop = self._loop
219
+ transport = writer.transport
220
+ self._stream_writer = writer
221
+ self._transport = transport
222
+ self._over_ssl = transport.get_extra_info('sslcontext') is not None
223
+
224
+ def connection_made(self, transport):
225
+ if self._reject_connection:
226
+ context = {
227
+ 'message': ('An open stream was garbage collected prior to '
228
+ 'establishing network connection; '
229
+ 'call "stream.close()" explicitly.')
230
+ }
231
+ if self._source_traceback:
232
+ context['source_traceback'] = self._source_traceback
233
+ self._loop.call_exception_handler(context)
234
+ transport.abort()
235
+ return
236
+ self._transport = transport
237
+ reader = self._stream_reader
238
+ if reader is not None:
239
+ reader.set_transport(transport)
240
+ self._over_ssl = transport.get_extra_info('sslcontext') is not None
241
+ if self._client_connected_cb is not None:
242
+ self._stream_writer = StreamWriter(transport, self,
243
+ reader,
244
+ self._loop)
245
+ res = self._client_connected_cb(reader,
246
+ self._stream_writer)
247
+ if coroutines.iscoroutine(res):
248
+ def callback(task):
249
+ if task.cancelled():
250
+ transport.close()
251
+ return
252
+ exc = task.exception()
253
+ if exc is not None:
254
+ self._loop.call_exception_handler({
255
+ 'message': 'Unhandled exception in client_connected_cb',
256
+ 'exception': exc,
257
+ 'transport': transport,
258
+ })
259
+ transport.close()
260
+
261
+ self._task = self._loop.create_task(res)
262
+ self._task.add_done_callback(callback)
263
+
264
+ self._strong_reader = None
265
+
266
+ def connection_lost(self, exc):
267
+ reader = self._stream_reader
268
+ if reader is not None:
269
+ if exc is None:
270
+ reader.feed_eof()
271
+ else:
272
+ reader.set_exception(exc)
273
+ if not self._closed.done():
274
+ if exc is None:
275
+ self._closed.set_result(None)
276
+ else:
277
+ self._closed.set_exception(exc)
278
+ super().connection_lost(exc)
279
+ self._stream_reader_wr = None
280
+ self._stream_writer = None
281
+ self._task = None
282
+ self._transport = None
283
+
284
+ def data_received(self, data):
285
+ reader = self._stream_reader
286
+ if reader is not None:
287
+ reader.feed_data(data)
288
+
289
+ def eof_received(self):
290
+ reader = self._stream_reader
291
+ if reader is not None:
292
+ reader.feed_eof()
293
+ if self._over_ssl:
294
+ # Prevent a warning in SSLProtocol.eof_received:
295
+ # "returning true from eof_received()
296
+ # has no effect when using ssl"
297
+ return False
298
+ return True
299
+
300
+ def _get_close_waiter(self, stream):
301
+ return self._closed
302
+
303
+ def __del__(self):
304
+ # Prevent reports about unhandled exceptions.
305
+ # Better than self._closed._log_traceback = False hack
306
+ try:
307
+ closed = self._closed
308
+ except AttributeError:
309
+ pass # failed constructor
310
+ else:
311
+ if closed.done() and not closed.cancelled():
312
+ closed.exception()
313
+
314
+
315
+ class StreamWriter:
316
+ """Wraps a Transport.
317
+
318
+ This exposes write(), writelines(), [can_]write_eof(),
319
+ get_extra_info() and close(). It adds drain() which returns an
320
+ optional Future on which you can wait for flow control. It also
321
+ adds a transport property which references the Transport
322
+ directly.
323
+ """
324
+
325
+ def __init__(self, transport, protocol, reader, loop):
326
+ self._transport = transport
327
+ self._protocol = protocol
328
+ # drain() expects that the reader has an exception() method
329
+ assert reader is None or isinstance(reader, StreamReader)
330
+ self._reader = reader
331
+ self._loop = loop
332
+ self._complete_fut = self._loop.create_future()
333
+ self._complete_fut.set_result(None)
334
+
335
+ def __repr__(self):
336
+ info = [self.__class__.__name__, f'transport={self._transport!r}']
337
+ if self._reader is not None:
338
+ info.append(f'reader={self._reader!r}')
339
+ return '<{}>'.format(' '.join(info))
340
+
341
+ @property
342
+ def transport(self):
343
+ return self._transport
344
+
345
+ def write(self, data):
346
+ self._transport.write(data)
347
+
348
+ def writelines(self, data):
349
+ self._transport.writelines(data)
350
+
351
+ def write_eof(self):
352
+ return self._transport.write_eof()
353
+
354
+ def can_write_eof(self):
355
+ return self._transport.can_write_eof()
356
+
357
+ def close(self):
358
+ return self._transport.close()
359
+
360
+ def is_closing(self):
361
+ return self._transport.is_closing()
362
+
363
+ async def wait_closed(self):
364
+ await self._protocol._get_close_waiter(self)
365
+
366
+ def get_extra_info(self, name, default=None):
367
+ return self._transport.get_extra_info(name, default)
368
+
369
+ async def drain(self):
370
+ """Flush the write buffer.
371
+
372
+ The intended use is to write
373
+
374
+ w.write(data)
375
+ await w.drain()
376
+ """
377
+ if self._reader is not None:
378
+ exc = self._reader.exception()
379
+ if exc is not None:
380
+ raise exc
381
+ if self._transport.is_closing():
382
+ # Wait for protocol.connection_lost() call
383
+ # Raise connection closing error if any,
384
+ # ConnectionResetError otherwise
385
+ # Yield to the event loop so connection_lost() may be
386
+ # called. Without this, _drain_helper() would return
387
+ # immediately, and code that calls
388
+ # write(...); await drain()
389
+ # in a loop would never call connection_lost(), so it
390
+ # would not see an error when the socket is closed.
391
+ await sleep(0)
392
+ await self._protocol._drain_helper()
393
+
394
+ async def start_tls(self, sslcontext, *,
395
+ server_hostname=None,
396
+ ssl_handshake_timeout=None):
397
+ """Upgrade an existing stream-based connection to TLS."""
398
+ server_side = self._protocol._client_connected_cb is not None
399
+ protocol = self._protocol
400
+ await self.drain()
401
+ new_transport = await self._loop.start_tls( # type: ignore
402
+ self._transport, protocol, sslcontext,
403
+ server_side=server_side, server_hostname=server_hostname,
404
+ ssl_handshake_timeout=ssl_handshake_timeout)
405
+ self._transport = new_transport
406
+ protocol._replace_writer(self)
407
+
408
+ def __del__(self):
409
+ if not self._transport.is_closing():
410
+ if self._loop.is_closed():
411
+ warnings.warn("loop is closed", ResourceWarning)
412
+ else:
413
+ self.close()
414
+ warnings.warn(f"unclosed {self!r}", ResourceWarning)
415
+
416
+ class StreamReader:
417
+
418
+ _source_traceback = None
419
+
420
+ def __init__(self, limit=_DEFAULT_LIMIT, loop=None):
421
+ # The line length limit is a security feature;
422
+ # it also doubles as half the buffer limit.
423
+
424
+ if limit <= 0:
425
+ raise ValueError('Limit cannot be <= 0')
426
+
427
+ self._limit = limit
428
+ if loop is None:
429
+ self._loop = events._get_event_loop()
430
+ else:
431
+ self._loop = loop
432
+ self._buffer = bytearray()
433
+ self._eof = False # Whether we're done.
434
+ self._waiter = None # A future used by _wait_for_data()
435
+ self._exception = None
436
+ self._transport = None
437
+ self._paused = False
438
+ if self._loop.get_debug():
439
+ self._source_traceback = format_helpers.extract_stack(
440
+ sys._getframe(1))
441
+
442
+ def __repr__(self):
443
+ info = ['StreamReader']
444
+ if self._buffer:
445
+ info.append(f'{len(self._buffer)} bytes')
446
+ if self._eof:
447
+ info.append('eof')
448
+ if self._limit != _DEFAULT_LIMIT:
449
+ info.append(f'limit={self._limit}')
450
+ if self._waiter:
451
+ info.append(f'waiter={self._waiter!r}')
452
+ if self._exception:
453
+ info.append(f'exception={self._exception!r}')
454
+ if self._transport:
455
+ info.append(f'transport={self._transport!r}')
456
+ if self._paused:
457
+ info.append('paused')
458
+ return '<{}>'.format(' '.join(info))
459
+
460
+ def exception(self):
461
+ return self._exception
462
+
463
+ def set_exception(self, exc):
464
+ self._exception = exc
465
+
466
+ waiter = self._waiter
467
+ if waiter is not None:
468
+ self._waiter = None
469
+ if not waiter.cancelled():
470
+ waiter.set_exception(exc)
471
+
472
+ def _wakeup_waiter(self):
473
+ """Wakeup read*() functions waiting for data or EOF."""
474
+ waiter = self._waiter
475
+ if waiter is not None:
476
+ self._waiter = None
477
+ if not waiter.cancelled():
478
+ waiter.set_result(None)
479
+
480
+ def set_transport(self, transport):
481
+ assert self._transport is None, 'Transport already set'
482
+ self._transport = transport
483
+
484
+ def _maybe_resume_transport(self):
485
+ if self._paused and len(self._buffer) <= self._limit:
486
+ self._paused = False
487
+ self._transport.resume_reading()
488
+
489
+ def feed_eof(self):
490
+ self._eof = True
491
+ self._wakeup_waiter()
492
+
493
+ def at_eof(self):
494
+ """Return True if the buffer is empty and 'feed_eof' was called."""
495
+ return self._eof and not self._buffer
496
+
497
+ def feed_data(self, data):
498
+ assert not self._eof, 'feed_data after feed_eof'
499
+
500
+ if not data:
501
+ return
502
+
503
+ self._buffer.extend(data)
504
+ self._wakeup_waiter()
505
+
506
+ if (self._transport is not None and
507
+ not self._paused and
508
+ len(self._buffer) > 2 * self._limit):
509
+ try:
510
+ self._transport.pause_reading()
511
+ except NotImplementedError:
512
+ # The transport can't be paused.
513
+ # We'll just have to buffer all data.
514
+ # Forget the transport so we don't keep trying.
515
+ self._transport = None
516
+ else:
517
+ self._paused = True
518
+
519
+ async def _wait_for_data(self, func_name):
520
+ """Wait until feed_data() or feed_eof() is called.
521
+
522
+ If stream was paused, automatically resume it.
523
+ """
524
+ # StreamReader uses a future to link the protocol feed_data() method
525
+ # to a read coroutine. Running two read coroutines at the same time
526
+ # would have an unexpected behaviour. It would not possible to know
527
+ # which coroutine would get the next data.
528
+ if self._waiter is not None:
529
+ raise RuntimeError(
530
+ f'{func_name}() called while another coroutine is '
531
+ f'already waiting for incoming data')
532
+
533
+ assert not self._eof, '_wait_for_data after EOF'
534
+
535
+ # Waiting for data while paused will make deadlock, so prevent it.
536
+ # This is essential for readexactly(n) for case when n > self._limit.
537
+ if self._paused:
538
+ self._paused = False
539
+ self._transport.resume_reading()
540
+
541
+ self._waiter = self._loop.create_future()
542
+ try:
543
+ await self._waiter
544
+ finally:
545
+ self._waiter = None
546
+
547
+ async def readline(self):
548
+ """Read chunk of data from the stream until newline (b'\n') is found.
549
+
550
+ On success, return chunk that ends with newline. If only partial
551
+ line can be read due to EOF, return incomplete line without
552
+ terminating newline. When EOF was reached while no bytes read, empty
553
+ bytes object is returned.
554
+
555
+ If limit is reached, ValueError will be raised. In that case, if
556
+ newline was found, complete line including newline will be removed
557
+ from internal buffer. Else, internal buffer will be cleared. Limit is
558
+ compared against part of the line without newline.
559
+
560
+ If stream was paused, this function will automatically resume it if
561
+ needed.
562
+ """
563
+ sep = b'\n'
564
+ seplen = len(sep)
565
+ try:
566
+ line = await self.readuntil(sep)
567
+ except exceptions.IncompleteReadError as e:
568
+ return e.partial
569
+ except exceptions.LimitOverrunError as e:
570
+ if self._buffer.startswith(sep, e.consumed):
571
+ del self._buffer[:e.consumed + seplen]
572
+ else:
573
+ self._buffer.clear()
574
+ self._maybe_resume_transport()
575
+ raise ValueError(e.args[0])
576
+ return line
577
+
578
+ async def readuntil(self, separator=b'\n'):
579
+ """Read data from the stream until ``separator`` is found.
580
+
581
+ On success, the data and separator will be removed from the
582
+ internal buffer (consumed). Returned data will include the
583
+ separator at the end.
584
+
585
+ Configured stream limit is used to check result. Limit sets the
586
+ maximal length of data that can be returned, not counting the
587
+ separator.
588
+
589
+ If an EOF occurs and the complete separator is still not found,
590
+ an IncompleteReadError exception will be raised, and the internal
591
+ buffer will be reset. The IncompleteReadError.partial attribute
592
+ may contain the separator partially.
593
+
594
+ If the data cannot be read because of over limit, a
595
+ LimitOverrunError exception will be raised, and the data
596
+ will be left in the internal buffer, so it can be read again.
597
+ """
598
+ seplen = len(separator)
599
+ if seplen == 0:
600
+ raise ValueError('Separator should be at least one-byte string')
601
+
602
+ if self._exception is not None:
603
+ raise self._exception
604
+
605
+ # Consume whole buffer except last bytes, which length is
606
+ # one less than seplen. Let's check corner cases with
607
+ # separator='SEPARATOR':
608
+ # * we have received almost complete separator (without last
609
+ # byte). i.e buffer='some textSEPARATO'. In this case we
610
+ # can safely consume len(separator) - 1 bytes.
611
+ # * last byte of buffer is first byte of separator, i.e.
612
+ # buffer='abcdefghijklmnopqrS'. We may safely consume
613
+ # everything except that last byte, but this require to
614
+ # analyze bytes of buffer that match partial separator.
615
+ # This is slow and/or require FSM. For this case our
616
+ # implementation is not optimal, since require rescanning
617
+ # of data that is known to not belong to separator. In
618
+ # real world, separator will not be so long to notice
619
+ # performance problems. Even when reading MIME-encoded
620
+ # messages :)
621
+
622
+ # `offset` is the number of bytes from the beginning of the buffer
623
+ # where there is no occurrence of `separator`.
624
+ offset = 0
625
+
626
+ # Loop until we find `separator` in the buffer, exceed the buffer size,
627
+ # or an EOF has happened.
628
+ while True:
629
+ buflen = len(self._buffer)
630
+
631
+ # Check if we now have enough data in the buffer for `separator` to
632
+ # fit.
633
+ if buflen - offset >= seplen:
634
+ isep = self._buffer.find(separator, offset)
635
+
636
+ if isep != -1:
637
+ # `separator` is in the buffer. `isep` will be used later
638
+ # to retrieve the data.
639
+ break
640
+
641
+ # see upper comment for explanation.
642
+ offset = buflen + 1 - seplen
643
+ if offset > self._limit:
644
+ raise exceptions.LimitOverrunError(
645
+ 'Separator is not found, and chunk exceed the limit',
646
+ offset)
647
+
648
+ # Complete message (with full separator) may be present in buffer
649
+ # even when EOF flag is set. This may happen when the last chunk
650
+ # adds data which makes separator be found. That's why we check for
651
+ # EOF *ater* inspecting the buffer.
652
+ if self._eof:
653
+ chunk = bytes(self._buffer)
654
+ self._buffer.clear()
655
+ raise exceptions.IncompleteReadError(chunk, None)
656
+
657
+ # _wait_for_data() will resume reading if stream was paused.
658
+ await self._wait_for_data('readuntil')
659
+
660
+ if isep > self._limit:
661
+ raise exceptions.LimitOverrunError(
662
+ 'Separator is found, but chunk is longer than limit', isep)
663
+
664
+ chunk = self._buffer[:isep + seplen]
665
+ del self._buffer[:isep + seplen]
666
+ self._maybe_resume_transport()
667
+ return bytes(chunk)
668
+
669
+ async def read(self, n=-1):
670
+ """Read up to `n` bytes from the stream.
671
+
672
+ If `n` is not provided or set to -1,
673
+ read until EOF, then return all read bytes.
674
+ If EOF was received and the internal buffer is empty,
675
+ return an empty bytes object.
676
+
677
+ If `n` is 0, return an empty bytes object immediately.
678
+
679
+ If `n` is positive, return at most `n` available bytes
680
+ as soon as at least 1 byte is available in the internal buffer.
681
+ If EOF is received before any byte is read, return an empty
682
+ bytes object.
683
+
684
+ Returned value is not limited with limit, configured at stream
685
+ creation.
686
+
687
+ If stream was paused, this function will automatically resume it if
688
+ needed.
689
+ """
690
+
691
+ if self._exception is not None:
692
+ raise self._exception
693
+
694
+ if n == 0:
695
+ return b''
696
+
697
+ if n < 0:
698
+ # This used to just loop creating a new waiter hoping to
699
+ # collect everything in self._buffer, but that would
700
+ # deadlock if the subprocess sends more than self.limit
701
+ # bytes. So just call self.read(self._limit) until EOF.
702
+ blocks = []
703
+ while True:
704
+ block = await self.read(self._limit)
705
+ if not block:
706
+ break
707
+ blocks.append(block)
708
+ return b''.join(blocks)
709
+
710
+ if not self._buffer and not self._eof:
711
+ await self._wait_for_data('read')
712
+
713
+ # This will work right even if buffer is less than n bytes
714
+ data = bytes(self._buffer[:n])
715
+ del self._buffer[:n]
716
+
717
+ self._maybe_resume_transport()
718
+ return data
719
+
720
+ async def readexactly(self, n):
721
+ """Read exactly `n` bytes.
722
+
723
+ Raise an IncompleteReadError if EOF is reached before `n` bytes can be
724
+ read. The IncompleteReadError.partial attribute of the exception will
725
+ contain the partial read bytes.
726
+
727
+ if n is zero, return empty bytes object.
728
+
729
+ Returned value is not limited with limit, configured at stream
730
+ creation.
731
+
732
+ If stream was paused, this function will automatically resume it if
733
+ needed.
734
+ """
735
+ if n < 0:
736
+ raise ValueError('readexactly size can not be less than zero')
737
+
738
+ if self._exception is not None:
739
+ raise self._exception
740
+
741
+ if n == 0:
742
+ return b''
743
+
744
+ while len(self._buffer) < n:
745
+ if self._eof:
746
+ incomplete = bytes(self._buffer)
747
+ self._buffer.clear()
748
+ raise exceptions.IncompleteReadError(incomplete, n)
749
+
750
+ await self._wait_for_data('readexactly')
751
+
752
+ if len(self._buffer) == n:
753
+ data = bytes(self._buffer)
754
+ self._buffer.clear()
755
+ else:
756
+ data = bytes(self._buffer[:n])
757
+ del self._buffer[:n]
758
+ self._maybe_resume_transport()
759
+ return data
760
+
761
+ def __aiter__(self):
762
+ return self
763
+
764
+ async def __anext__(self):
765
+ val = await self.readline()
766
+ if val == b'':
767
+ raise StopAsyncIteration
768
+ return val
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/subprocess.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = 'create_subprocess_exec', 'create_subprocess_shell'
2
+
3
+ import subprocess
4
+
5
+ from . import events
6
+ from . import protocols
7
+ from . import streams
8
+ from . import tasks
9
+ from .log import logger
10
+
11
+
12
+ PIPE = subprocess.PIPE
13
+ STDOUT = subprocess.STDOUT
14
+ DEVNULL = subprocess.DEVNULL
15
+
16
+
17
+ class SubprocessStreamProtocol(streams.FlowControlMixin,
18
+ protocols.SubprocessProtocol):
19
+ """Like StreamReaderProtocol, but for a subprocess."""
20
+
21
+ def __init__(self, limit, loop):
22
+ super().__init__(loop=loop)
23
+ self._limit = limit
24
+ self.stdin = self.stdout = self.stderr = None
25
+ self._transport = None
26
+ self._process_exited = False
27
+ self._pipe_fds = []
28
+ self._stdin_closed = self._loop.create_future()
29
+
30
+ def __repr__(self):
31
+ info = [self.__class__.__name__]
32
+ if self.stdin is not None:
33
+ info.append(f'stdin={self.stdin!r}')
34
+ if self.stdout is not None:
35
+ info.append(f'stdout={self.stdout!r}')
36
+ if self.stderr is not None:
37
+ info.append(f'stderr={self.stderr!r}')
38
+ return '<{}>'.format(' '.join(info))
39
+
40
+ def connection_made(self, transport):
41
+ self._transport = transport
42
+
43
+ stdout_transport = transport.get_pipe_transport(1)
44
+ if stdout_transport is not None:
45
+ self.stdout = streams.StreamReader(limit=self._limit,
46
+ loop=self._loop)
47
+ self.stdout.set_transport(stdout_transport)
48
+ self._pipe_fds.append(1)
49
+
50
+ stderr_transport = transport.get_pipe_transport(2)
51
+ if stderr_transport is not None:
52
+ self.stderr = streams.StreamReader(limit=self._limit,
53
+ loop=self._loop)
54
+ self.stderr.set_transport(stderr_transport)
55
+ self._pipe_fds.append(2)
56
+
57
+ stdin_transport = transport.get_pipe_transport(0)
58
+ if stdin_transport is not None:
59
+ self.stdin = streams.StreamWriter(stdin_transport,
60
+ protocol=self,
61
+ reader=None,
62
+ loop=self._loop)
63
+
64
+ def pipe_data_received(self, fd, data):
65
+ if fd == 1:
66
+ reader = self.stdout
67
+ elif fd == 2:
68
+ reader = self.stderr
69
+ else:
70
+ reader = None
71
+ if reader is not None:
72
+ reader.feed_data(data)
73
+
74
+ def pipe_connection_lost(self, fd, exc):
75
+ if fd == 0:
76
+ pipe = self.stdin
77
+ if pipe is not None:
78
+ pipe.close()
79
+ self.connection_lost(exc)
80
+ if exc is None:
81
+ self._stdin_closed.set_result(None)
82
+ else:
83
+ self._stdin_closed.set_exception(exc)
84
+ # Since calling `wait_closed()` is not mandatory,
85
+ # we shouldn't log the traceback if this is not awaited.
86
+ self._stdin_closed._log_traceback = False
87
+ return
88
+ if fd == 1:
89
+ reader = self.stdout
90
+ elif fd == 2:
91
+ reader = self.stderr
92
+ else:
93
+ reader = None
94
+ if reader is not None:
95
+ if exc is None:
96
+ reader.feed_eof()
97
+ else:
98
+ reader.set_exception(exc)
99
+
100
+ if fd in self._pipe_fds:
101
+ self._pipe_fds.remove(fd)
102
+ self._maybe_close_transport()
103
+
104
+ def process_exited(self):
105
+ self._process_exited = True
106
+ self._maybe_close_transport()
107
+
108
+ def _maybe_close_transport(self):
109
+ if len(self._pipe_fds) == 0 and self._process_exited:
110
+ self._transport.close()
111
+ self._transport = None
112
+
113
+ def _get_close_waiter(self, stream):
114
+ if stream is self.stdin:
115
+ return self._stdin_closed
116
+
117
+
118
+ class Process:
119
+ def __init__(self, transport, protocol, loop):
120
+ self._transport = transport
121
+ self._protocol = protocol
122
+ self._loop = loop
123
+ self.stdin = protocol.stdin
124
+ self.stdout = protocol.stdout
125
+ self.stderr = protocol.stderr
126
+ self.pid = transport.get_pid()
127
+
128
+ def __repr__(self):
129
+ return f'<{self.__class__.__name__} {self.pid}>'
130
+
131
+ @property
132
+ def returncode(self):
133
+ return self._transport.get_returncode()
134
+
135
+ async def wait(self):
136
+ """Wait until the process exit and return the process return code."""
137
+ return await self._transport._wait()
138
+
139
+ def send_signal(self, signal):
140
+ self._transport.send_signal(signal)
141
+
142
+ def terminate(self):
143
+ self._transport.terminate()
144
+
145
+ def kill(self):
146
+ self._transport.kill()
147
+
148
+ async def _feed_stdin(self, input):
149
+ debug = self._loop.get_debug()
150
+ try:
151
+ self.stdin.write(input)
152
+ if debug:
153
+ logger.debug(
154
+ '%r communicate: feed stdin (%s bytes)', self, len(input))
155
+
156
+ await self.stdin.drain()
157
+ except (BrokenPipeError, ConnectionResetError) as exc:
158
+ # communicate() ignores BrokenPipeError and ConnectionResetError.
159
+ # write() and drain() can raise these exceptions.
160
+ if debug:
161
+ logger.debug('%r communicate: stdin got %r', self, exc)
162
+
163
+ if debug:
164
+ logger.debug('%r communicate: close stdin', self)
165
+ self.stdin.close()
166
+
167
+ async def _noop(self):
168
+ return None
169
+
170
+ async def _read_stream(self, fd):
171
+ transport = self._transport.get_pipe_transport(fd)
172
+ if fd == 2:
173
+ stream = self.stderr
174
+ else:
175
+ assert fd == 1
176
+ stream = self.stdout
177
+ if self._loop.get_debug():
178
+ name = 'stdout' if fd == 1 else 'stderr'
179
+ logger.debug('%r communicate: read %s', self, name)
180
+ output = await stream.read()
181
+ if self._loop.get_debug():
182
+ name = 'stdout' if fd == 1 else 'stderr'
183
+ logger.debug('%r communicate: close %s', self, name)
184
+ transport.close()
185
+ return output
186
+
187
+ async def communicate(self, input=None):
188
+ if input is not None:
189
+ stdin = self._feed_stdin(input)
190
+ else:
191
+ stdin = self._noop()
192
+ if self.stdout is not None:
193
+ stdout = self._read_stream(1)
194
+ else:
195
+ stdout = self._noop()
196
+ if self.stderr is not None:
197
+ stderr = self._read_stream(2)
198
+ else:
199
+ stderr = self._noop()
200
+ stdin, stdout, stderr = await tasks.gather(stdin, stdout, stderr)
201
+ await self.wait()
202
+ return (stdout, stderr)
203
+
204
+
205
+ async def create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None,
206
+ limit=streams._DEFAULT_LIMIT, **kwds):
207
+ loop = events.get_running_loop()
208
+ protocol_factory = lambda: SubprocessStreamProtocol(limit=limit,
209
+ loop=loop)
210
+ transport, protocol = await loop.subprocess_shell(
211
+ protocol_factory,
212
+ cmd, stdin=stdin, stdout=stdout,
213
+ stderr=stderr, **kwds)
214
+ return Process(transport, protocol, loop)
215
+
216
+
217
+ async def create_subprocess_exec(program, *args, stdin=None, stdout=None,
218
+ stderr=None, limit=streams._DEFAULT_LIMIT,
219
+ **kwds):
220
+ loop = events.get_running_loop()
221
+ protocol_factory = lambda: SubprocessStreamProtocol(limit=limit,
222
+ loop=loop)
223
+ transport, protocol = await loop.subprocess_exec(
224
+ protocol_factory,
225
+ program, *args,
226
+ stdin=stdin, stdout=stdout,
227
+ stderr=stderr, **kwds)
228
+ return Process(transport, protocol, loop)
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/taskgroups.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted with permission from the EdgeDB project;
2
+ # license: PSFL.
3
+
4
+
5
+ __all__ = ["TaskGroup"]
6
+
7
+ from . import events
8
+ from . import exceptions
9
+ from . import tasks
10
+
11
+
12
+ class TaskGroup:
13
+ """Asynchronous context manager for managing groups of tasks.
14
+
15
+ Example use:
16
+
17
+ async with asyncio.TaskGroup() as group:
18
+ task1 = group.create_task(some_coroutine(...))
19
+ task2 = group.create_task(other_coroutine(...))
20
+ print("Both tasks have completed now.")
21
+
22
+ All tasks are awaited when the context manager exits.
23
+
24
+ Any exceptions other than `asyncio.CancelledError` raised within
25
+ a task will cancel all remaining tasks and wait for them to exit.
26
+ The exceptions are then combined and raised as an `ExceptionGroup`.
27
+ """
28
+ def __init__(self):
29
+ self._entered = False
30
+ self._exiting = False
31
+ self._aborting = False
32
+ self._loop = None
33
+ self._parent_task = None
34
+ self._parent_cancel_requested = False
35
+ self._tasks = set()
36
+ self._errors = []
37
+ self._base_error = None
38
+ self._on_completed_fut = None
39
+
40
+ def __repr__(self):
41
+ info = ['']
42
+ if self._tasks:
43
+ info.append(f'tasks={len(self._tasks)}')
44
+ if self._errors:
45
+ info.append(f'errors={len(self._errors)}')
46
+ if self._aborting:
47
+ info.append('cancelling')
48
+ elif self._entered:
49
+ info.append('entered')
50
+
51
+ info_str = ' '.join(info)
52
+ return f'<TaskGroup{info_str}>'
53
+
54
+ async def __aenter__(self):
55
+ if self._entered:
56
+ raise RuntimeError(
57
+ f"TaskGroup {self!r} has already been entered")
58
+ if self._loop is None:
59
+ self._loop = events.get_running_loop()
60
+ self._parent_task = tasks.current_task(self._loop)
61
+ if self._parent_task is None:
62
+ raise RuntimeError(
63
+ f'TaskGroup {self!r} cannot determine the parent task')
64
+ self._entered = True
65
+
66
+ return self
67
+
68
+ async def __aexit__(self, et, exc, tb):
69
+ self._exiting = True
70
+
71
+ if (exc is not None and
72
+ self._is_base_error(exc) and
73
+ self._base_error is None):
74
+ self._base_error = exc
75
+
76
+ propagate_cancellation_error = \
77
+ exc if et is exceptions.CancelledError else None
78
+ if self._parent_cancel_requested:
79
+ # If this flag is set we *must* call uncancel().
80
+ if self._parent_task.uncancel() == 0:
81
+ # If there are no pending cancellations left,
82
+ # don't propagate CancelledError.
83
+ propagate_cancellation_error = None
84
+
85
+ if et is not None:
86
+ if not self._aborting:
87
+ # Our parent task is being cancelled:
88
+ #
89
+ # async with TaskGroup() as g:
90
+ # g.create_task(...)
91
+ # await ... # <- CancelledError
92
+ #
93
+ # or there's an exception in "async with":
94
+ #
95
+ # async with TaskGroup() as g:
96
+ # g.create_task(...)
97
+ # 1 / 0
98
+ #
99
+ self._abort()
100
+
101
+ # We use while-loop here because "self._on_completed_fut"
102
+ # can be cancelled multiple times if our parent task
103
+ # is being cancelled repeatedly (or even once, when
104
+ # our own cancellation is already in progress)
105
+ while self._tasks:
106
+ if self._on_completed_fut is None:
107
+ self._on_completed_fut = self._loop.create_future()
108
+
109
+ try:
110
+ await self._on_completed_fut
111
+ except exceptions.CancelledError as ex:
112
+ if not self._aborting:
113
+ # Our parent task is being cancelled:
114
+ #
115
+ # async def wrapper():
116
+ # async with TaskGroup() as g:
117
+ # g.create_task(foo)
118
+ #
119
+ # "wrapper" is being cancelled while "foo" is
120
+ # still running.
121
+ propagate_cancellation_error = ex
122
+ self._abort()
123
+
124
+ self._on_completed_fut = None
125
+
126
+ assert not self._tasks
127
+
128
+ if self._base_error is not None:
129
+ raise self._base_error
130
+
131
+ # Propagate CancelledError if there is one, except if there
132
+ # are other errors -- those have priority.
133
+ if propagate_cancellation_error and not self._errors:
134
+ raise propagate_cancellation_error
135
+
136
+ if et is not None and et is not exceptions.CancelledError:
137
+ self._errors.append(exc)
138
+
139
+ if self._errors:
140
+ # Exceptions are heavy objects that can have object
141
+ # cycles (bad for GC); let's not keep a reference to
142
+ # a bunch of them.
143
+ try:
144
+ me = BaseExceptionGroup('unhandled errors in a TaskGroup', self._errors)
145
+ raise me from None
146
+ finally:
147
+ self._errors = None
148
+
149
+ def create_task(self, coro, *, name=None, context=None):
150
+ """Create a new task in this group and return it.
151
+
152
+ Similar to `asyncio.create_task`.
153
+ """
154
+ if not self._entered:
155
+ raise RuntimeError(f"TaskGroup {self!r} has not been entered")
156
+ if self._exiting and not self._tasks:
157
+ raise RuntimeError(f"TaskGroup {self!r} is finished")
158
+ if self._aborting:
159
+ raise RuntimeError(f"TaskGroup {self!r} is shutting down")
160
+ if context is None:
161
+ task = self._loop.create_task(coro)
162
+ else:
163
+ task = self._loop.create_task(coro, context=context)
164
+ tasks._set_task_name(task, name)
165
+ task.add_done_callback(self._on_task_done)
166
+ self._tasks.add(task)
167
+ return task
168
+
169
+ # Since Python 3.8 Tasks propagate all exceptions correctly,
170
+ # except for KeyboardInterrupt and SystemExit which are
171
+ # still considered special.
172
+
173
+ def _is_base_error(self, exc: BaseException) -> bool:
174
+ assert isinstance(exc, BaseException)
175
+ return isinstance(exc, (SystemExit, KeyboardInterrupt))
176
+
177
+ def _abort(self):
178
+ self._aborting = True
179
+
180
+ for t in self._tasks:
181
+ if not t.done():
182
+ t.cancel()
183
+
184
+ def _on_task_done(self, task):
185
+ self._tasks.discard(task)
186
+
187
+ if self._on_completed_fut is not None and not self._tasks:
188
+ if not self._on_completed_fut.done():
189
+ self._on_completed_fut.set_result(True)
190
+
191
+ if task.cancelled():
192
+ return
193
+
194
+ exc = task.exception()
195
+ if exc is None:
196
+ return
197
+
198
+ self._errors.append(exc)
199
+ if self._is_base_error(exc) and self._base_error is None:
200
+ self._base_error = exc
201
+
202
+ if self._parent_task.done():
203
+ # Not sure if this case is possible, but we want to handle
204
+ # it anyways.
205
+ self._loop.call_exception_handler({
206
+ 'message': f'Task {task!r} has errored out but its parent '
207
+ f'task {self._parent_task} is already completed',
208
+ 'exception': exc,
209
+ 'task': task,
210
+ })
211
+ return
212
+
213
+ if not self._aborting and not self._parent_cancel_requested:
214
+ # If parent task *is not* being cancelled, it means that we want
215
+ # to manually cancel it to abort whatever is being run right now
216
+ # in the TaskGroup. But we want to mark parent task as
217
+ # "not cancelled" later in __aexit__. Example situation that
218
+ # we need to handle:
219
+ #
220
+ # async def foo():
221
+ # try:
222
+ # async with TaskGroup() as g:
223
+ # g.create_task(crash_soon())
224
+ # await something # <- this needs to be canceled
225
+ # # by the TaskGroup, e.g.
226
+ # # foo() needs to be cancelled
227
+ # except Exception:
228
+ # # Ignore any exceptions raised in the TaskGroup
229
+ # pass
230
+ # await something_else # this line has to be called
231
+ # # after TaskGroup is finished.
232
+ self._abort()
233
+ self._parent_cancel_requested = True
234
+ self._parent_task.cancel()
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/tasks.py ADDED
@@ -0,0 +1,990 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Support for tasks, coroutines and the scheduler."""
2
+
3
+ __all__ = (
4
+ 'Task', 'create_task',
5
+ 'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED',
6
+ 'wait', 'wait_for', 'as_completed', 'sleep',
7
+ 'gather', 'shield', 'ensure_future', 'run_coroutine_threadsafe',
8
+ 'current_task', 'all_tasks',
9
+ '_register_task', '_unregister_task', '_enter_task', '_leave_task',
10
+ )
11
+
12
+ import concurrent.futures
13
+ import contextvars
14
+ import functools
15
+ import inspect
16
+ import itertools
17
+ import types
18
+ import warnings
19
+ import weakref
20
+ from types import GenericAlias
21
+
22
+ from . import base_tasks
23
+ from . import coroutines
24
+ from . import events
25
+ from . import exceptions
26
+ from . import futures
27
+ from .coroutines import _is_coroutine
28
+
29
+ # Helper to generate new task names
30
+ # This uses itertools.count() instead of a "+= 1" operation because the latter
31
+ # is not thread safe. See bpo-11866 for a longer explanation.
32
+ _task_name_counter = itertools.count(1).__next__
33
+
34
+
35
+ def current_task(loop=None):
36
+ """Return a currently executed task."""
37
+ if loop is None:
38
+ loop = events.get_running_loop()
39
+ return _current_tasks.get(loop)
40
+
41
+
42
+ def all_tasks(loop=None):
43
+ """Return a set of all tasks for the loop."""
44
+ if loop is None:
45
+ loop = events.get_running_loop()
46
+ # Looping over a WeakSet (_all_tasks) isn't safe as it can be updated from another
47
+ # thread while we do so. Therefore we cast it to list prior to filtering. The list
48
+ # cast itself requires iteration, so we repeat it several times ignoring
49
+ # RuntimeErrors (which are not very likely to occur). See issues 34970 and 36607 for
50
+ # details.
51
+ i = 0
52
+ while True:
53
+ try:
54
+ tasks = list(_all_tasks)
55
+ except RuntimeError:
56
+ i += 1
57
+ if i >= 1000:
58
+ raise
59
+ else:
60
+ break
61
+ return {t for t in tasks
62
+ if futures._get_loop(t) is loop and not t.done()}
63
+
64
+
65
+ def _set_task_name(task, name):
66
+ if name is not None:
67
+ try:
68
+ set_name = task.set_name
69
+ except AttributeError:
70
+ warnings.warn("Task.set_name() was added in Python 3.8, "
71
+ "the method support will be mandatory for third-party "
72
+ "task implementations since 3.13.",
73
+ DeprecationWarning, stacklevel=3)
74
+ else:
75
+ set_name(name)
76
+
77
+
78
+ class Task(futures._PyFuture): # Inherit Python Task implementation
79
+ # from a Python Future implementation.
80
+
81
+ """A coroutine wrapped in a Future."""
82
+
83
+ # An important invariant maintained while a Task not done:
84
+ # _fut_waiter is either None or a Future. The Future
85
+ # can be either done() or not done().
86
+ # The task can be in any of 3 states:
87
+ #
88
+ # - 1: _fut_waiter is not None and not _fut_waiter.done():
89
+ # __step() is *not* scheduled and the Task is waiting for _fut_waiter.
90
+ # - 2: (_fut_waiter is None or _fut_waiter.done()) and __step() is scheduled:
91
+ # the Task is waiting for __step() to be executed.
92
+ # - 3: _fut_waiter is None and __step() is *not* scheduled:
93
+ # the Task is currently executing (in __step()).
94
+ #
95
+ # * In state 1, one of the callbacks of __fut_waiter must be __wakeup().
96
+ # * The transition from 1 to 2 happens when _fut_waiter becomes done(),
97
+ # as it schedules __wakeup() to be called (which calls __step() so
98
+ # we way that __step() is scheduled).
99
+ # * It transitions from 2 to 3 when __step() is executed, and it clears
100
+ # _fut_waiter to None.
101
+
102
+ # If False, don't log a message if the task is destroyed while its
103
+ # status is still pending
104
+ _log_destroy_pending = True
105
+
106
+ def __init__(self, coro, *, loop=None, name=None, context=None):
107
+ super().__init__(loop=loop)
108
+ if self._source_traceback:
109
+ del self._source_traceback[-1]
110
+ if not coroutines.iscoroutine(coro):
111
+ # raise after Future.__init__(), attrs are required for __del__
112
+ # prevent logging for pending task in __del__
113
+ self._log_destroy_pending = False
114
+ raise TypeError(f"a coroutine was expected, got {coro!r}")
115
+
116
+ if name is None:
117
+ self._name = f'Task-{_task_name_counter()}'
118
+ else:
119
+ self._name = str(name)
120
+
121
+ self._num_cancels_requested = 0
122
+ self._must_cancel = False
123
+ self._fut_waiter = None
124
+ self._coro = coro
125
+ if context is None:
126
+ self._context = contextvars.copy_context()
127
+ else:
128
+ self._context = context
129
+
130
+ self._loop.call_soon(self.__step, context=self._context)
131
+ _register_task(self)
132
+
133
+ def __del__(self):
134
+ if self._state == futures._PENDING and self._log_destroy_pending:
135
+ context = {
136
+ 'task': self,
137
+ 'message': 'Task was destroyed but it is pending!',
138
+ }
139
+ if self._source_traceback:
140
+ context['source_traceback'] = self._source_traceback
141
+ self._loop.call_exception_handler(context)
142
+ super().__del__()
143
+
144
+ __class_getitem__ = classmethod(GenericAlias)
145
+
146
+ def __repr__(self):
147
+ return base_tasks._task_repr(self)
148
+
149
+ def get_coro(self):
150
+ return self._coro
151
+
152
+ def get_name(self):
153
+ return self._name
154
+
155
+ def set_name(self, value):
156
+ self._name = str(value)
157
+
158
+ def set_result(self, result):
159
+ raise RuntimeError('Task does not support set_result operation')
160
+
161
+ def set_exception(self, exception):
162
+ raise RuntimeError('Task does not support set_exception operation')
163
+
164
+ def get_stack(self, *, limit=None):
165
+ """Return the list of stack frames for this task's coroutine.
166
+
167
+ If the coroutine is not done, this returns the stack where it is
168
+ suspended. If the coroutine has completed successfully or was
169
+ cancelled, this returns an empty list. If the coroutine was
170
+ terminated by an exception, this returns the list of traceback
171
+ frames.
172
+
173
+ The frames are always ordered from oldest to newest.
174
+
175
+ The optional limit gives the maximum number of frames to
176
+ return; by default all available frames are returned. Its
177
+ meaning differs depending on whether a stack or a traceback is
178
+ returned: the newest frames of a stack are returned, but the
179
+ oldest frames of a traceback are returned. (This matches the
180
+ behavior of the traceback module.)
181
+
182
+ For reasons beyond our control, only one stack frame is
183
+ returned for a suspended coroutine.
184
+ """
185
+ return base_tasks._task_get_stack(self, limit)
186
+
187
+ def print_stack(self, *, limit=None, file=None):
188
+ """Print the stack or traceback for this task's coroutine.
189
+
190
+ This produces output similar to that of the traceback module,
191
+ for the frames retrieved by get_stack(). The limit argument
192
+ is passed to get_stack(). The file argument is an I/O stream
193
+ to which the output is written; by default output is written
194
+ to sys.stderr.
195
+ """
196
+ return base_tasks._task_print_stack(self, limit, file)
197
+
198
+ def cancel(self, msg=None):
199
+ """Request that this task cancel itself.
200
+
201
+ This arranges for a CancelledError to be thrown into the
202
+ wrapped coroutine on the next cycle through the event loop.
203
+ The coroutine then has a chance to clean up or even deny
204
+ the request using try/except/finally.
205
+
206
+ Unlike Future.cancel, this does not guarantee that the
207
+ task will be cancelled: the exception might be caught and
208
+ acted upon, delaying cancellation of the task or preventing
209
+ cancellation completely. The task may also return a value or
210
+ raise a different exception.
211
+
212
+ Immediately after this method is called, Task.cancelled() will
213
+ not return True (unless the task was already cancelled). A
214
+ task will be marked as cancelled when the wrapped coroutine
215
+ terminates with a CancelledError exception (even if cancel()
216
+ was not called).
217
+
218
+ This also increases the task's count of cancellation requests.
219
+ """
220
+ self._log_traceback = False
221
+ if self.done():
222
+ return False
223
+ self._num_cancels_requested += 1
224
+ # These two lines are controversial. See discussion starting at
225
+ # https://github.com/python/cpython/pull/31394#issuecomment-1053545331
226
+ # Also remember that this is duplicated in _asynciomodule.c.
227
+ # if self._num_cancels_requested > 1:
228
+ # return False
229
+ if self._fut_waiter is not None:
230
+ if self._fut_waiter.cancel(msg=msg):
231
+ # Leave self._fut_waiter; it may be a Task that
232
+ # catches and ignores the cancellation so we may have
233
+ # to cancel it again later.
234
+ return True
235
+ # It must be the case that self.__step is already scheduled.
236
+ self._must_cancel = True
237
+ self._cancel_message = msg
238
+ return True
239
+
240
+ def cancelling(self):
241
+ """Return the count of the task's cancellation requests.
242
+
243
+ This count is incremented when .cancel() is called
244
+ and may be decremented using .uncancel().
245
+ """
246
+ return self._num_cancels_requested
247
+
248
+ def uncancel(self):
249
+ """Decrement the task's count of cancellation requests.
250
+
251
+ This should be called by the party that called `cancel()` on the task
252
+ beforehand.
253
+
254
+ Returns the remaining number of cancellation requests.
255
+ """
256
+ if self._num_cancels_requested > 0:
257
+ self._num_cancels_requested -= 1
258
+ return self._num_cancels_requested
259
+
260
+ def __step(self, exc=None):
261
+ if self.done():
262
+ raise exceptions.InvalidStateError(
263
+ f'_step(): already done: {self!r}, {exc!r}')
264
+ if self._must_cancel:
265
+ if not isinstance(exc, exceptions.CancelledError):
266
+ exc = self._make_cancelled_error()
267
+ self._must_cancel = False
268
+ coro = self._coro
269
+ self._fut_waiter = None
270
+
271
+ _enter_task(self._loop, self)
272
+ # Call either coro.throw(exc) or coro.send(None).
273
+ try:
274
+ if exc is None:
275
+ # We use the `send` method directly, because coroutines
276
+ # don't have `__iter__` and `__next__` methods.
277
+ result = coro.send(None)
278
+ else:
279
+ result = coro.throw(exc)
280
+ except StopIteration as exc:
281
+ if self._must_cancel:
282
+ # Task is cancelled right before coro stops.
283
+ self._must_cancel = False
284
+ super().cancel(msg=self._cancel_message)
285
+ else:
286
+ super().set_result(exc.value)
287
+ except exceptions.CancelledError as exc:
288
+ # Save the original exception so we can chain it later.
289
+ self._cancelled_exc = exc
290
+ super().cancel() # I.e., Future.cancel(self).
291
+ except (KeyboardInterrupt, SystemExit) as exc:
292
+ super().set_exception(exc)
293
+ raise
294
+ except BaseException as exc:
295
+ super().set_exception(exc)
296
+ else:
297
+ blocking = getattr(result, '_asyncio_future_blocking', None)
298
+ if blocking is not None:
299
+ # Yielded Future must come from Future.__iter__().
300
+ if futures._get_loop(result) is not self._loop:
301
+ new_exc = RuntimeError(
302
+ f'Task {self!r} got Future '
303
+ f'{result!r} attached to a different loop')
304
+ self._loop.call_soon(
305
+ self.__step, new_exc, context=self._context)
306
+ elif blocking:
307
+ if result is self:
308
+ new_exc = RuntimeError(
309
+ f'Task cannot await on itself: {self!r}')
310
+ self._loop.call_soon(
311
+ self.__step, new_exc, context=self._context)
312
+ else:
313
+ result._asyncio_future_blocking = False
314
+ result.add_done_callback(
315
+ self.__wakeup, context=self._context)
316
+ self._fut_waiter = result
317
+ if self._must_cancel:
318
+ if self._fut_waiter.cancel(
319
+ msg=self._cancel_message):
320
+ self._must_cancel = False
321
+ else:
322
+ new_exc = RuntimeError(
323
+ f'yield was used instead of yield from '
324
+ f'in task {self!r} with {result!r}')
325
+ self._loop.call_soon(
326
+ self.__step, new_exc, context=self._context)
327
+
328
+ elif result is None:
329
+ # Bare yield relinquishes control for one event loop iteration.
330
+ self._loop.call_soon(self.__step, context=self._context)
331
+ elif inspect.isgenerator(result):
332
+ # Yielding a generator is just wrong.
333
+ new_exc = RuntimeError(
334
+ f'yield was used instead of yield from for '
335
+ f'generator in task {self!r} with {result!r}')
336
+ self._loop.call_soon(
337
+ self.__step, new_exc, context=self._context)
338
+ else:
339
+ # Yielding something else is an error.
340
+ new_exc = RuntimeError(f'Task got bad yield: {result!r}')
341
+ self._loop.call_soon(
342
+ self.__step, new_exc, context=self._context)
343
+ finally:
344
+ _leave_task(self._loop, self)
345
+ self = None # Needed to break cycles when an exception occurs.
346
+
347
+ def __wakeup(self, future):
348
+ try:
349
+ future.result()
350
+ except BaseException as exc:
351
+ # This may also be a cancellation.
352
+ self.__step(exc)
353
+ else:
354
+ # Don't pass the value of `future.result()` explicitly,
355
+ # as `Future.__iter__` and `Future.__await__` don't need it.
356
+ # If we call `_step(value, None)` instead of `_step()`,
357
+ # Python eval loop would use `.send(value)` method call,
358
+ # instead of `__next__()`, which is slower for futures
359
+ # that return non-generator iterators from their `__iter__`.
360
+ self.__step()
361
+ self = None # Needed to break cycles when an exception occurs.
362
+
363
+
364
+ _PyTask = Task
365
+
366
+
367
+ try:
368
+ import _asyncio
369
+ except ImportError:
370
+ pass
371
+ else:
372
+ # _CTask is needed for tests.
373
+ Task = _CTask = _asyncio.Task
374
+
375
+
376
+ def create_task(coro, *, name=None, context=None):
377
+ """Schedule the execution of a coroutine object in a spawn task.
378
+
379
+ Return a Task object.
380
+ """
381
+ loop = events.get_running_loop()
382
+ if context is None:
383
+ # Use legacy API if context is not needed
384
+ task = loop.create_task(coro)
385
+ else:
386
+ task = loop.create_task(coro, context=context)
387
+
388
+ _set_task_name(task, name)
389
+ return task
390
+
391
+
392
+ # wait() and as_completed() similar to those in PEP 3148.
393
+
394
+ FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED
395
+ FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION
396
+ ALL_COMPLETED = concurrent.futures.ALL_COMPLETED
397
+
398
+
399
+ async def wait(fs, *, timeout=None, return_when=ALL_COMPLETED):
400
+ """Wait for the Futures or Tasks given by fs to complete.
401
+
402
+ The fs iterable must not be empty.
403
+
404
+ Coroutines will be wrapped in Tasks.
405
+
406
+ Returns two sets of Future: (done, pending).
407
+
408
+ Usage:
409
+
410
+ done, pending = await asyncio.wait(fs)
411
+
412
+ Note: This does not raise TimeoutError! Futures that aren't done
413
+ when the timeout occurs are returned in the second set.
414
+ """
415
+ if futures.isfuture(fs) or coroutines.iscoroutine(fs):
416
+ raise TypeError(f"expect a list of futures, not {type(fs).__name__}")
417
+ if not fs:
418
+ raise ValueError('Set of Tasks/Futures is empty.')
419
+ if return_when not in (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED):
420
+ raise ValueError(f'Invalid return_when value: {return_when}')
421
+
422
+ fs = set(fs)
423
+
424
+ if any(coroutines.iscoroutine(f) for f in fs):
425
+ raise TypeError("Passing coroutines is forbidden, use tasks explicitly.")
426
+
427
+ loop = events.get_running_loop()
428
+ return await _wait(fs, timeout, return_when, loop)
429
+
430
+
431
+ def _release_waiter(waiter, *args):
432
+ if not waiter.done():
433
+ waiter.set_result(None)
434
+
435
+
436
+ async def wait_for(fut, timeout):
437
+ """Wait for the single Future or coroutine to complete, with timeout.
438
+
439
+ Coroutine will be wrapped in Task.
440
+
441
+ Returns result of the Future or coroutine. When a timeout occurs,
442
+ it cancels the task and raises TimeoutError. To avoid the task
443
+ cancellation, wrap it in shield().
444
+
445
+ If the wait is cancelled, the task is also cancelled.
446
+
447
+ This function is a coroutine.
448
+ """
449
+ loop = events.get_running_loop()
450
+
451
+ if timeout is None:
452
+ return await fut
453
+
454
+ if timeout <= 0:
455
+ fut = ensure_future(fut, loop=loop)
456
+
457
+ if fut.done():
458
+ return fut.result()
459
+
460
+ await _cancel_and_wait(fut, loop=loop)
461
+ try:
462
+ return fut.result()
463
+ except exceptions.CancelledError as exc:
464
+ raise exceptions.TimeoutError() from exc
465
+
466
+ waiter = loop.create_future()
467
+ timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
468
+ cb = functools.partial(_release_waiter, waiter)
469
+
470
+ fut = ensure_future(fut, loop=loop)
471
+ fut.add_done_callback(cb)
472
+
473
+ try:
474
+ # wait until the future completes or the timeout
475
+ try:
476
+ await waiter
477
+ except exceptions.CancelledError:
478
+ if fut.done():
479
+ return fut.result()
480
+ else:
481
+ fut.remove_done_callback(cb)
482
+ # We must ensure that the task is not running
483
+ # after wait_for() returns.
484
+ # See https://bugs.python.org/issue32751
485
+ await _cancel_and_wait(fut, loop=loop)
486
+ raise
487
+
488
+ if fut.done():
489
+ return fut.result()
490
+ else:
491
+ fut.remove_done_callback(cb)
492
+ # We must ensure that the task is not running
493
+ # after wait_for() returns.
494
+ # See https://bugs.python.org/issue32751
495
+ await _cancel_and_wait(fut, loop=loop)
496
+ # In case task cancellation failed with some
497
+ # exception, we should re-raise it
498
+ # See https://bugs.python.org/issue40607
499
+ try:
500
+ return fut.result()
501
+ except exceptions.CancelledError as exc:
502
+ raise exceptions.TimeoutError() from exc
503
+ finally:
504
+ timeout_handle.cancel()
505
+
506
+
507
+ async def _wait(fs, timeout, return_when, loop):
508
+ """Internal helper for wait().
509
+
510
+ The fs argument must be a collection of Futures.
511
+ """
512
+ assert fs, 'Set of Futures is empty.'
513
+ waiter = loop.create_future()
514
+ timeout_handle = None
515
+ if timeout is not None:
516
+ timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
517
+ counter = len(fs)
518
+
519
+ def _on_completion(f):
520
+ nonlocal counter
521
+ counter -= 1
522
+ if (counter <= 0 or
523
+ return_when == FIRST_COMPLETED or
524
+ return_when == FIRST_EXCEPTION and (not f.cancelled() and
525
+ f.exception() is not None)):
526
+ if timeout_handle is not None:
527
+ timeout_handle.cancel()
528
+ if not waiter.done():
529
+ waiter.set_result(None)
530
+
531
+ for f in fs:
532
+ f.add_done_callback(_on_completion)
533
+
534
+ try:
535
+ await waiter
536
+ finally:
537
+ if timeout_handle is not None:
538
+ timeout_handle.cancel()
539
+ for f in fs:
540
+ f.remove_done_callback(_on_completion)
541
+
542
+ done, pending = set(), set()
543
+ for f in fs:
544
+ if f.done():
545
+ done.add(f)
546
+ else:
547
+ pending.add(f)
548
+ return done, pending
549
+
550
+
551
+ async def _cancel_and_wait(fut, loop):
552
+ """Cancel the *fut* future or task and wait until it completes."""
553
+
554
+ waiter = loop.create_future()
555
+ cb = functools.partial(_release_waiter, waiter)
556
+ fut.add_done_callback(cb)
557
+
558
+ try:
559
+ fut.cancel()
560
+ # We cannot wait on *fut* directly to make
561
+ # sure _cancel_and_wait itself is reliably cancellable.
562
+ await waiter
563
+ finally:
564
+ fut.remove_done_callback(cb)
565
+
566
+
567
+ # This is *not* a @coroutine! It is just an iterator (yielding Futures).
568
+ def as_completed(fs, *, timeout=None):
569
+ """Return an iterator whose values are coroutines.
570
+
571
+ When waiting for the yielded coroutines you'll get the results (or
572
+ exceptions!) of the original Futures (or coroutines), in the order
573
+ in which and as soon as they complete.
574
+
575
+ This differs from PEP 3148; the proper way to use this is:
576
+
577
+ for f in as_completed(fs):
578
+ result = await f # The 'await' may raise.
579
+ # Use result.
580
+
581
+ If a timeout is specified, the 'await' will raise
582
+ TimeoutError when the timeout occurs before all Futures are done.
583
+
584
+ Note: The futures 'f' are not necessarily members of fs.
585
+ """
586
+ if futures.isfuture(fs) or coroutines.iscoroutine(fs):
587
+ raise TypeError(f"expect an iterable of futures, not {type(fs).__name__}")
588
+
589
+ from .queues import Queue # Import here to avoid circular import problem.
590
+ done = Queue()
591
+
592
+ loop = events._get_event_loop()
593
+ todo = {ensure_future(f, loop=loop) for f in set(fs)}
594
+ timeout_handle = None
595
+
596
+ def _on_timeout():
597
+ for f in todo:
598
+ f.remove_done_callback(_on_completion)
599
+ done.put_nowait(None) # Queue a dummy value for _wait_for_one().
600
+ todo.clear() # Can't do todo.remove(f) in the loop.
601
+
602
+ def _on_completion(f):
603
+ if not todo:
604
+ return # _on_timeout() was here first.
605
+ todo.remove(f)
606
+ done.put_nowait(f)
607
+ if not todo and timeout_handle is not None:
608
+ timeout_handle.cancel()
609
+
610
+ async def _wait_for_one():
611
+ f = await done.get()
612
+ if f is None:
613
+ # Dummy value from _on_timeout().
614
+ raise exceptions.TimeoutError
615
+ return f.result() # May raise f.exception().
616
+
617
+ for f in todo:
618
+ f.add_done_callback(_on_completion)
619
+ if todo and timeout is not None:
620
+ timeout_handle = loop.call_later(timeout, _on_timeout)
621
+ for _ in range(len(todo)):
622
+ yield _wait_for_one()
623
+
624
+
625
+ @types.coroutine
626
+ def __sleep0():
627
+ """Skip one event loop run cycle.
628
+
629
+ This is a private helper for 'asyncio.sleep()', used
630
+ when the 'delay' is set to 0. It uses a bare 'yield'
631
+ expression (which Task.__step knows how to handle)
632
+ instead of creating a Future object.
633
+ """
634
+ yield
635
+
636
+
637
+ async def sleep(delay, result=None):
638
+ """Coroutine that completes after a given time (in seconds)."""
639
+ if delay <= 0:
640
+ await __sleep0()
641
+ return result
642
+
643
+ loop = events.get_running_loop()
644
+ future = loop.create_future()
645
+ h = loop.call_later(delay,
646
+ futures._set_result_unless_cancelled,
647
+ future, result)
648
+ try:
649
+ return await future
650
+ finally:
651
+ h.cancel()
652
+
653
+
654
+ def ensure_future(coro_or_future, *, loop=None):
655
+ """Wrap a coroutine or an awaitable in a future.
656
+
657
+ If the argument is a Future, it is returned directly.
658
+ """
659
+ return _ensure_future(coro_or_future, loop=loop)
660
+
661
+
662
+ def _ensure_future(coro_or_future, *, loop=None):
663
+ if futures.isfuture(coro_or_future):
664
+ if loop is not None and loop is not futures._get_loop(coro_or_future):
665
+ raise ValueError('The future belongs to a different loop than '
666
+ 'the one specified as the loop argument')
667
+ return coro_or_future
668
+ called_wrap_awaitable = False
669
+ if not coroutines.iscoroutine(coro_or_future):
670
+ if inspect.isawaitable(coro_or_future):
671
+ coro_or_future = _wrap_awaitable(coro_or_future)
672
+ called_wrap_awaitable = True
673
+ else:
674
+ raise TypeError('An asyncio.Future, a coroutine or an awaitable '
675
+ 'is required')
676
+
677
+ if loop is None:
678
+ loop = events._get_event_loop(stacklevel=4)
679
+ try:
680
+ return loop.create_task(coro_or_future)
681
+ except RuntimeError:
682
+ if not called_wrap_awaitable:
683
+ coro_or_future.close()
684
+ raise
685
+
686
+
687
+ @types.coroutine
688
+ def _wrap_awaitable(awaitable):
689
+ """Helper for asyncio.ensure_future().
690
+
691
+ Wraps awaitable (an object with __await__) into a coroutine
692
+ that will later be wrapped in a Task by ensure_future().
693
+ """
694
+ return (yield from awaitable.__await__())
695
+
696
+ _wrap_awaitable._is_coroutine = _is_coroutine
697
+
698
+
699
+ class _GatheringFuture(futures.Future):
700
+ """Helper for gather().
701
+
702
+ This overrides cancel() to cancel all the children and act more
703
+ like Task.cancel(), which doesn't immediately mark itself as
704
+ cancelled.
705
+ """
706
+
707
+ def __init__(self, children, *, loop):
708
+ assert loop is not None
709
+ super().__init__(loop=loop)
710
+ self._children = children
711
+ self._cancel_requested = False
712
+
713
+ def cancel(self, msg=None):
714
+ if self.done():
715
+ return False
716
+ ret = False
717
+ for child in self._children:
718
+ if child.cancel(msg=msg):
719
+ ret = True
720
+ if ret:
721
+ # If any child tasks were actually cancelled, we should
722
+ # propagate the cancellation request regardless of
723
+ # *return_exceptions* argument. See issue 32684.
724
+ self._cancel_requested = True
725
+ return ret
726
+
727
+
728
+ def gather(*coros_or_futures, return_exceptions=False):
729
+ """Return a future aggregating results from the given coroutines/futures.
730
+
731
+ Coroutines will be wrapped in a future and scheduled in the event
732
+ loop. They will not necessarily be scheduled in the same order as
733
+ passed in.
734
+
735
+ All futures must share the same event loop. If all the tasks are
736
+ done successfully, the returned future's result is the list of
737
+ results (in the order of the original sequence, not necessarily
738
+ the order of results arrival). If *return_exceptions* is True,
739
+ exceptions in the tasks are treated the same as successful
740
+ results, and gathered in the result list; otherwise, the first
741
+ raised exception will be immediately propagated to the returned
742
+ future.
743
+
744
+ Cancellation: if the outer Future is cancelled, all children (that
745
+ have not completed yet) are also cancelled. If any child is
746
+ cancelled, this is treated as if it raised CancelledError --
747
+ the outer Future is *not* cancelled in this case. (This is to
748
+ prevent the cancellation of one child to cause other children to
749
+ be cancelled.)
750
+
751
+ If *return_exceptions* is False, cancelling gather() after it
752
+ has been marked done won't cancel any submitted awaitables.
753
+ For instance, gather can be marked done after propagating an
754
+ exception to the caller, therefore, calling ``gather.cancel()``
755
+ after catching an exception (raised by one of the awaitables) from
756
+ gather won't cancel any other awaitables.
757
+ """
758
+ if not coros_or_futures:
759
+ loop = events._get_event_loop()
760
+ outer = loop.create_future()
761
+ outer.set_result([])
762
+ return outer
763
+
764
+ def _done_callback(fut):
765
+ nonlocal nfinished
766
+ nfinished += 1
767
+
768
+ if outer is None or outer.done():
769
+ if not fut.cancelled():
770
+ # Mark exception retrieved.
771
+ fut.exception()
772
+ return
773
+
774
+ if not return_exceptions:
775
+ if fut.cancelled():
776
+ # Check if 'fut' is cancelled first, as
777
+ # 'fut.exception()' will *raise* a CancelledError
778
+ # instead of returning it.
779
+ exc = fut._make_cancelled_error()
780
+ outer.set_exception(exc)
781
+ return
782
+ else:
783
+ exc = fut.exception()
784
+ if exc is not None:
785
+ outer.set_exception(exc)
786
+ return
787
+
788
+ if nfinished == nfuts:
789
+ # All futures are done; create a list of results
790
+ # and set it to the 'outer' future.
791
+ results = []
792
+
793
+ for fut in children:
794
+ if fut.cancelled():
795
+ # Check if 'fut' is cancelled first, as 'fut.exception()'
796
+ # will *raise* a CancelledError instead of returning it.
797
+ # Also, since we're adding the exception return value
798
+ # to 'results' instead of raising it, don't bother
799
+ # setting __context__. This also lets us preserve
800
+ # calling '_make_cancelled_error()' at most once.
801
+ res = exceptions.CancelledError(
802
+ '' if fut._cancel_message is None else
803
+ fut._cancel_message)
804
+ else:
805
+ res = fut.exception()
806
+ if res is None:
807
+ res = fut.result()
808
+ results.append(res)
809
+
810
+ if outer._cancel_requested:
811
+ # If gather is being cancelled we must propagate the
812
+ # cancellation regardless of *return_exceptions* argument.
813
+ # See issue 32684.
814
+ exc = fut._make_cancelled_error()
815
+ outer.set_exception(exc)
816
+ else:
817
+ outer.set_result(results)
818
+
819
+ arg_to_fut = {}
820
+ children = []
821
+ nfuts = 0
822
+ nfinished = 0
823
+ loop = None
824
+ outer = None # bpo-46672
825
+ for arg in coros_or_futures:
826
+ if arg not in arg_to_fut:
827
+ fut = _ensure_future(arg, loop=loop)
828
+ if loop is None:
829
+ loop = futures._get_loop(fut)
830
+ if fut is not arg:
831
+ # 'arg' was not a Future, therefore, 'fut' is a new
832
+ # Future created specifically for 'arg'. Since the caller
833
+ # can't control it, disable the "destroy pending task"
834
+ # warning.
835
+ fut._log_destroy_pending = False
836
+
837
+ nfuts += 1
838
+ arg_to_fut[arg] = fut
839
+ fut.add_done_callback(_done_callback)
840
+
841
+ else:
842
+ # There's a duplicate Future object in coros_or_futures.
843
+ fut = arg_to_fut[arg]
844
+
845
+ children.append(fut)
846
+
847
+ outer = _GatheringFuture(children, loop=loop)
848
+ return outer
849
+
850
+
851
+ def shield(arg):
852
+ """Wait for a future, shielding it from cancellation.
853
+
854
+ The statement
855
+
856
+ task = asyncio.create_task(something())
857
+ res = await shield(task)
858
+
859
+ is exactly equivalent to the statement
860
+
861
+ res = await something()
862
+
863
+ *except* that if the coroutine containing it is cancelled, the
864
+ task running in something() is not cancelled. From the POV of
865
+ something(), the cancellation did not happen. But its caller is
866
+ still cancelled, so the yield-from expression still raises
867
+ CancelledError. Note: If something() is cancelled by other means
868
+ this will still cancel shield().
869
+
870
+ If you want to completely ignore cancellation (not recommended)
871
+ you can combine shield() with a try/except clause, as follows:
872
+
873
+ task = asyncio.create_task(something())
874
+ try:
875
+ res = await shield(task)
876
+ except CancelledError:
877
+ res = None
878
+
879
+ Save a reference to tasks passed to this function, to avoid
880
+ a task disappearing mid-execution. The event loop only keeps
881
+ weak references to tasks. A task that isn't referenced elsewhere
882
+ may get garbage collected at any time, even before it's done.
883
+ """
884
+ inner = _ensure_future(arg)
885
+ if inner.done():
886
+ # Shortcut.
887
+ return inner
888
+ loop = futures._get_loop(inner)
889
+ outer = loop.create_future()
890
+
891
+ def _inner_done_callback(inner):
892
+ if outer.cancelled():
893
+ if not inner.cancelled():
894
+ # Mark inner's result as retrieved.
895
+ inner.exception()
896
+ return
897
+
898
+ if inner.cancelled():
899
+ outer.cancel()
900
+ else:
901
+ exc = inner.exception()
902
+ if exc is not None:
903
+ outer.set_exception(exc)
904
+ else:
905
+ outer.set_result(inner.result())
906
+
907
+
908
+ def _outer_done_callback(outer):
909
+ if not inner.done():
910
+ inner.remove_done_callback(_inner_done_callback)
911
+
912
+ inner.add_done_callback(_inner_done_callback)
913
+ outer.add_done_callback(_outer_done_callback)
914
+ return outer
915
+
916
+
917
+ def run_coroutine_threadsafe(coro, loop):
918
+ """Submit a coroutine object to a given event loop.
919
+
920
+ Return a concurrent.futures.Future to access the result.
921
+ """
922
+ if not coroutines.iscoroutine(coro):
923
+ raise TypeError('A coroutine object is required')
924
+ future = concurrent.futures.Future()
925
+
926
+ def callback():
927
+ try:
928
+ futures._chain_future(ensure_future(coro, loop=loop), future)
929
+ except (SystemExit, KeyboardInterrupt):
930
+ raise
931
+ except BaseException as exc:
932
+ if future.set_running_or_notify_cancel():
933
+ future.set_exception(exc)
934
+ raise
935
+
936
+ loop.call_soon_threadsafe(callback)
937
+ return future
938
+
939
+
940
+ # WeakSet containing all alive tasks.
941
+ _all_tasks = weakref.WeakSet()
942
+
943
+ # Dictionary containing tasks that are currently active in
944
+ # all running event loops. {EventLoop: Task}
945
+ _current_tasks = {}
946
+
947
+
948
+ def _register_task(task):
949
+ """Register a new task in asyncio as executed by loop."""
950
+ _all_tasks.add(task)
951
+
952
+
953
+ def _enter_task(loop, task):
954
+ current_task = _current_tasks.get(loop)
955
+ if current_task is not None:
956
+ raise RuntimeError(f"Cannot enter into task {task!r} while another "
957
+ f"task {current_task!r} is being executed.")
958
+ _current_tasks[loop] = task
959
+
960
+
961
+ def _leave_task(loop, task):
962
+ current_task = _current_tasks.get(loop)
963
+ if current_task is not task:
964
+ raise RuntimeError(f"Leaving task {task!r} does not match "
965
+ f"the current task {current_task!r}.")
966
+ del _current_tasks[loop]
967
+
968
+
969
+ def _unregister_task(task):
970
+ """Unregister a task."""
971
+ _all_tasks.discard(task)
972
+
973
+
974
+ _py_register_task = _register_task
975
+ _py_unregister_task = _unregister_task
976
+ _py_enter_task = _enter_task
977
+ _py_leave_task = _leave_task
978
+
979
+
980
+ try:
981
+ from _asyncio import (_register_task, _unregister_task,
982
+ _enter_task, _leave_task,
983
+ _all_tasks, _current_tasks)
984
+ except ImportError:
985
+ pass
986
+ else:
987
+ _c_register_task = _register_task
988
+ _c_unregister_task = _unregister_task
989
+ _c_enter_task = _enter_task
990
+ _c_leave_task = _leave_task
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/threads.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """High-level support for working with threads in asyncio"""
2
+
3
+ import functools
4
+ import contextvars
5
+
6
+ from . import events
7
+
8
+
9
+ __all__ = "to_thread",
10
+
11
+
12
+ async def to_thread(func, /, *args, **kwargs):
13
+ """Asynchronously run function *func* in a separate thread.
14
+
15
+ Any *args and **kwargs supplied for this function are directly passed
16
+ to *func*. Also, the current :class:`contextvars.Context` is propagated,
17
+ allowing context variables from the main thread to be accessed in the
18
+ separate thread.
19
+
20
+ Return a coroutine that can be awaited to get the eventual result of *func*.
21
+ """
22
+ loop = events.get_running_loop()
23
+ ctx = contextvars.copy_context()
24
+ func_call = functools.partial(ctx.run, func, *args, **kwargs)
25
+ return await loop.run_in_executor(None, func_call)
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.11.15-h0159041_0_cpython/Lib/asyncio/timeouts.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+
3
+ from types import TracebackType
4
+ from typing import final, Optional, Type
5
+
6
+ from . import events
7
+ from . import exceptions
8
+ from . import tasks
9
+
10
+
11
+ __all__ = (
12
+ "Timeout",
13
+ "timeout",
14
+ "timeout_at",
15
+ )
16
+
17
+
18
+ class _State(enum.Enum):
19
+ CREATED = "created"
20
+ ENTERED = "active"
21
+ EXPIRING = "expiring"
22
+ EXPIRED = "expired"
23
+ EXITED = "finished"
24
+
25
+
26
+ @final
27
+ class Timeout:
28
+ """Asynchronous context manager for cancelling overdue coroutines.
29
+
30
+ Use `timeout()` or `timeout_at()` rather than instantiating this class directly.
31
+ """
32
+
33
+ def __init__(self, when: Optional[float]) -> None:
34
+ """Schedule a timeout that will trigger at a given loop time.
35
+
36
+ - If `when` is `None`, the timeout will never trigger.
37
+ - If `when < loop.time()`, the timeout will trigger on the next
38
+ iteration of the event loop.
39
+ """
40
+ self._state = _State.CREATED
41
+
42
+ self._timeout_handler: Optional[events.TimerHandle] = None
43
+ self._task: Optional[tasks.Task] = None
44
+ self._when = when
45
+
46
+ def when(self) -> Optional[float]:
47
+ """Return the current deadline."""
48
+ return self._when
49
+
50
+ def reschedule(self, when: Optional[float]) -> None:
51
+ """Reschedule the timeout."""
52
+ if self._state is not _State.ENTERED:
53
+ if self._state is _State.CREATED:
54
+ raise RuntimeError("Timeout has not been entered")
55
+ raise RuntimeError(
56
+ f"Cannot change state of {self._state.value} Timeout",
57
+ )
58
+
59
+ self._when = when
60
+
61
+ if self._timeout_handler is not None:
62
+ self._timeout_handler.cancel()
63
+
64
+ if when is None:
65
+ self._timeout_handler = None
66
+ else:
67
+ loop = events.get_running_loop()
68
+ if when <= loop.time():
69
+ self._timeout_handler = loop.call_soon(self._on_timeout)
70
+ else:
71
+ self._timeout_handler = loop.call_at(when, self._on_timeout)
72
+
73
+ def expired(self) -> bool:
74
+ """Is timeout expired during execution?"""
75
+ return self._state in (_State.EXPIRING, _State.EXPIRED)
76
+
77
+ def __repr__(self) -> str:
78
+ info = ['']
79
+ if self._state is _State.ENTERED:
80
+ when = round(self._when, 3) if self._when is not None else None
81
+ info.append(f"when={when}")
82
+ info_str = ' '.join(info)
83
+ return f"<Timeout [{self._state.value}]{info_str}>"
84
+
85
+ async def __aenter__(self) -> "Timeout":
86
+ if self._state is not _State.CREATED:
87
+ raise RuntimeError("Timeout has already been entered")
88
+ task = tasks.current_task()
89
+ if task is None:
90
+ raise RuntimeError("Timeout should be used inside a task")
91
+ self._state = _State.ENTERED
92
+ self._task = task
93
+ self._cancelling = self._task.cancelling()
94
+ self.reschedule(self._when)
95
+ return self
96
+
97
+ async def __aexit__(
98
+ self,
99
+ exc_type: Optional[Type[BaseException]],
100
+ exc_val: Optional[BaseException],
101
+ exc_tb: Optional[TracebackType],
102
+ ) -> Optional[bool]:
103
+ assert self._state in (_State.ENTERED, _State.EXPIRING)
104
+
105
+ if self._timeout_handler is not None:
106
+ self._timeout_handler.cancel()
107
+ self._timeout_handler = None
108
+
109
+ if self._state is _State.EXPIRING:
110
+ self._state = _State.EXPIRED
111
+
112
+ if self._task.uncancel() <= self._cancelling and exc_type is exceptions.CancelledError:
113
+ # Since there are no new cancel requests, we're
114
+ # handling this.
115
+ raise TimeoutError from exc_val
116
+ elif self._state is _State.ENTERED:
117
+ self._state = _State.EXITED
118
+
119
+ return None
120
+
121
+ def _on_timeout(self) -> None:
122
+ assert self._state is _State.ENTERED
123
+ self._task.cancel()
124
+ self._state = _State.EXPIRING
125
+ # drop the reference early
126
+ self._timeout_handler = None
127
+
128
+
129
+ def timeout(delay: Optional[float]) -> Timeout:
130
+ """Timeout async context manager.
131
+
132
+ Useful in cases when you want to apply timeout logic around block
133
+ of code or in cases when asyncio.wait_for is not suitable. For example:
134
+
135
+ >>> async with asyncio.timeout(10): # 10 seconds timeout
136
+ ... await long_running_task()
137
+
138
+
139
+ delay - value in seconds or None to disable timeout logic
140
+
141
+ long_running_task() is interrupted by raising asyncio.CancelledError,
142
+ the top-most affected timeout() context manager converts CancelledError
143
+ into TimeoutError.
144
+ """
145
+ loop = events.get_running_loop()
146
+ return Timeout(loop.time() + delay if delay is not None else None)
147
+
148
+
149
+ def timeout_at(when: Optional[float]) -> Timeout:
150
+ """Schedule the timeout at absolute time.
151
+
152
+ Like timeout() but argument gives absolute time in the same clock system
153
+ as loop.time().
154
+
155
+ Please note: it is not POSIX time but a time with
156
+ undefined starting base, e.g. the time of the system power on.
157
+
158
+ >>> async with asyncio.timeout_at(loop.time() + 10):
159
+ ... await long_running_task()
160
+
161
+
162
+ when - a deadline when timeout occurs or None to disable timeout logic
163
+
164
+ long_running_task() is interrupted by raising asyncio.CancelledError,
165
+ the top-most affected timeout() context manager converts CancelledError
166
+ into TimeoutError.
167
+ """
168
+ return Timeout(when)