Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- micromamba_root/envs/hf_sync/DLLs/_asyncio.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_bz2.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_elementtree.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_hashlib.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_lzma.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_multiprocessing.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_overlapped.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_queue.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_remote_debugging.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_socket.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_testbuffer.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_testclinic.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_testclinic_limited.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_testconsole.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_testimportmultiple.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_testinternalcapi.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_testmultiphase.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_testsinglephase.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_tkinter.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_uuid.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_wmi.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_zoneinfo.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/_zstd.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/py.ico +0 -0
- micromamba_root/envs/hf_sync/DLLs/pyc.ico +0 -0
- micromamba_root/envs/hf_sync/DLLs/pyexpat.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/select.pyd +0 -0
- micromamba_root/envs/hf_sync/DLLs/winsound.pyd +0 -0
- micromamba_root/envs/hf_sync/Lib/abc.py +188 -0
- micromamba_root/envs/hf_sync/Lib/annotationlib.py +1165 -0
- micromamba_root/envs/hf_sync/Lib/antigravity.py +17 -0
- micromamba_root/envs/hf_sync/Lib/argparse.py +0 -0
- micromamba_root/envs/hf_sync/Lib/ast.py +680 -0
- micromamba_root/envs/hf_sync/Lib/base64.py +618 -0
- micromamba_root/envs/hf_sync/Lib/bdb.py +1206 -0
- micromamba_root/envs/hf_sync/Lib/bisect.py +118 -0
- micromamba_root/envs/hf_sync/Lib/bz2.py +352 -0
- micromamba_root/envs/hf_sync/Lib/cProfile.py +205 -0
- micromamba_root/envs/hf_sync/Lib/calendar.py +926 -0
- micromamba_root/envs/hf_sync/Lib/cmd.py +414 -0
- micromamba_root/envs/hf_sync/Lib/code.py +396 -0
- micromamba_root/envs/hf_sync/Lib/codecs.py +1125 -0
- micromamba_root/envs/hf_sync/Lib/codeop.py +154 -0
- micromamba_root/envs/hf_sync/Lib/colorsys.py +166 -0
- micromamba_root/envs/hf_sync/Lib/compileall.py +472 -0
- micromamba_root/envs/hf_sync/Lib/configparser.py +1415 -0
- micromamba_root/envs/hf_sync/Lib/contextlib.py +814 -0
- micromamba_root/envs/hf_sync/Lib/contextvars.py +8 -0
- micromamba_root/envs/hf_sync/Lib/copy.py +286 -0
- micromamba_root/envs/hf_sync/Lib/copyreg.py +222 -0
micromamba_root/envs/hf_sync/DLLs/_asyncio.pyd
ADDED
|
Binary file (64 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_bz2.pyd
ADDED
|
Binary file (24.6 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_elementtree.pyd
ADDED
|
Binary file (65 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_hashlib.pyd
ADDED
|
Binary file (51.7 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_lzma.pyd
ADDED
|
Binary file (36.9 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_multiprocessing.pyd
ADDED
|
Binary file (24.6 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_overlapped.pyd
ADDED
|
Binary file (44 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_queue.pyd
ADDED
|
Binary file (22 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_remote_debugging.pyd
ADDED
|
Binary file (62.5 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_socket.pyd
ADDED
|
Binary file (73.2 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_testbuffer.pyd
ADDED
|
Binary file (44.5 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_testclinic.pyd
ADDED
|
Binary file (97.3 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_testclinic_limited.pyd
ADDED
|
Binary file (16.4 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_testconsole.pyd
ADDED
|
Binary file (15.9 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_testimportmultiple.pyd
ADDED
|
Binary file (13.8 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_testinternalcapi.pyd
ADDED
|
Binary file (83.5 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_testmultiphase.pyd
ADDED
|
Binary file (28.7 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_testsinglephase.pyd
ADDED
|
Binary file (21 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_tkinter.pyd
ADDED
|
Binary file (59.4 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_uuid.pyd
ADDED
|
Binary file (13.8 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_wmi.pyd
ADDED
|
Binary file (25.6 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_zoneinfo.pyd
ADDED
|
Binary file (37.9 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/_zstd.pyd
ADDED
|
Binary file (52.2 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/py.ico
ADDED
|
|
micromamba_root/envs/hf_sync/DLLs/pyc.ico
ADDED
|
|
micromamba_root/envs/hf_sync/DLLs/pyexpat.pyd
ADDED
|
Binary file (59.9 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/select.pyd
ADDED
|
Binary file (18.9 kB). View file
|
|
|
micromamba_root/envs/hf_sync/DLLs/winsound.pyd
ADDED
|
Binary file (18.9 kB). View file
|
|
|
micromamba_root/envs/hf_sync/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/envs/hf_sync/Lib/annotationlib.py
ADDED
|
@@ -0,0 +1,1165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Helpers for introspecting and wrapping annotations."""
|
| 2 |
+
|
| 3 |
+
import ast
|
| 4 |
+
import builtins
|
| 5 |
+
import enum
|
| 6 |
+
import keyword
|
| 7 |
+
import sys
|
| 8 |
+
import types
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"Format",
|
| 12 |
+
"ForwardRef",
|
| 13 |
+
"call_annotate_function",
|
| 14 |
+
"call_evaluate_function",
|
| 15 |
+
"get_annotate_from_class_namespace",
|
| 16 |
+
"get_annotations",
|
| 17 |
+
"annotations_to_string",
|
| 18 |
+
"type_repr",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Format(enum.IntEnum):
|
| 23 |
+
VALUE = 1
|
| 24 |
+
VALUE_WITH_FAKE_GLOBALS = 2
|
| 25 |
+
FORWARDREF = 3
|
| 26 |
+
STRING = 4
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
_sentinel = object()
|
| 30 |
+
# Following `NAME_ERROR_MSG` in `ceval_macros.h`:
|
| 31 |
+
_NAME_ERROR_MSG = "name '{name:.200}' is not defined"
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# Slots shared by ForwardRef and _Stringifier. The __forward__ names must be
|
| 35 |
+
# preserved for compatibility with the old typing.ForwardRef class. The remaining
|
| 36 |
+
# names are private.
|
| 37 |
+
_SLOTS = (
|
| 38 |
+
"__forward_is_argument__",
|
| 39 |
+
"__forward_is_class__",
|
| 40 |
+
"__forward_module__",
|
| 41 |
+
"__weakref__",
|
| 42 |
+
"__arg__",
|
| 43 |
+
"__globals__",
|
| 44 |
+
"__extra_names__",
|
| 45 |
+
"__code__",
|
| 46 |
+
"__ast_node__",
|
| 47 |
+
"__cell__",
|
| 48 |
+
"__owner__",
|
| 49 |
+
"__stringifier_dict__",
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class ForwardRef:
|
| 54 |
+
"""Wrapper that holds a forward reference.
|
| 55 |
+
|
| 56 |
+
Constructor arguments:
|
| 57 |
+
* arg: a string representing the code to be evaluated.
|
| 58 |
+
* module: the module where the forward reference was created.
|
| 59 |
+
Must be a string, not a module object.
|
| 60 |
+
* owner: The owning object (module, class, or function).
|
| 61 |
+
* is_argument: Does nothing, retained for compatibility.
|
| 62 |
+
* is_class: True if the forward reference was created in class scope.
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
__slots__ = _SLOTS
|
| 67 |
+
|
| 68 |
+
def __init__(
|
| 69 |
+
self,
|
| 70 |
+
arg,
|
| 71 |
+
*,
|
| 72 |
+
module=None,
|
| 73 |
+
owner=None,
|
| 74 |
+
is_argument=True,
|
| 75 |
+
is_class=False,
|
| 76 |
+
):
|
| 77 |
+
if not isinstance(arg, str):
|
| 78 |
+
raise TypeError(f"Forward reference must be a string -- got {arg!r}")
|
| 79 |
+
|
| 80 |
+
self.__arg__ = arg
|
| 81 |
+
self.__forward_is_argument__ = is_argument
|
| 82 |
+
self.__forward_is_class__ = is_class
|
| 83 |
+
self.__forward_module__ = module
|
| 84 |
+
self.__owner__ = owner
|
| 85 |
+
# These are always set to None here but may be non-None if a ForwardRef
|
| 86 |
+
# is created through __class__ assignment on a _Stringifier object.
|
| 87 |
+
self.__globals__ = None
|
| 88 |
+
# This may be either a cell object (for a ForwardRef referring to a single name)
|
| 89 |
+
# or a dict mapping cell names to cell objects (for a ForwardRef containing references
|
| 90 |
+
# to multiple names).
|
| 91 |
+
self.__cell__ = None
|
| 92 |
+
self.__extra_names__ = None
|
| 93 |
+
# These are initially None but serve as a cache and may be set to a non-None
|
| 94 |
+
# value later.
|
| 95 |
+
self.__code__ = None
|
| 96 |
+
self.__ast_node__ = None
|
| 97 |
+
|
| 98 |
+
def __init_subclass__(cls, /, *args, **kwds):
|
| 99 |
+
raise TypeError("Cannot subclass ForwardRef")
|
| 100 |
+
|
| 101 |
+
def evaluate(
|
| 102 |
+
self,
|
| 103 |
+
*,
|
| 104 |
+
globals=None,
|
| 105 |
+
locals=None,
|
| 106 |
+
type_params=None,
|
| 107 |
+
owner=None,
|
| 108 |
+
format=Format.VALUE,
|
| 109 |
+
):
|
| 110 |
+
"""Evaluate the forward reference and return the value.
|
| 111 |
+
|
| 112 |
+
If the forward reference cannot be evaluated, raise an exception.
|
| 113 |
+
"""
|
| 114 |
+
match format:
|
| 115 |
+
case Format.STRING:
|
| 116 |
+
return self.__forward_arg__
|
| 117 |
+
case Format.VALUE:
|
| 118 |
+
is_forwardref_format = False
|
| 119 |
+
case Format.FORWARDREF:
|
| 120 |
+
is_forwardref_format = True
|
| 121 |
+
case _:
|
| 122 |
+
raise NotImplementedError(format)
|
| 123 |
+
if isinstance(self.__cell__, types.CellType):
|
| 124 |
+
try:
|
| 125 |
+
return self.__cell__.cell_contents
|
| 126 |
+
except ValueError:
|
| 127 |
+
pass
|
| 128 |
+
if owner is None:
|
| 129 |
+
owner = self.__owner__
|
| 130 |
+
|
| 131 |
+
if globals is None and self.__forward_module__ is not None:
|
| 132 |
+
globals = getattr(
|
| 133 |
+
sys.modules.get(self.__forward_module__, None), "__dict__", None
|
| 134 |
+
)
|
| 135 |
+
if globals is None:
|
| 136 |
+
globals = self.__globals__
|
| 137 |
+
if globals is None:
|
| 138 |
+
if isinstance(owner, type):
|
| 139 |
+
module_name = getattr(owner, "__module__", None)
|
| 140 |
+
if module_name:
|
| 141 |
+
module = sys.modules.get(module_name, None)
|
| 142 |
+
if module:
|
| 143 |
+
globals = getattr(module, "__dict__", None)
|
| 144 |
+
elif isinstance(owner, types.ModuleType):
|
| 145 |
+
globals = getattr(owner, "__dict__", None)
|
| 146 |
+
elif callable(owner):
|
| 147 |
+
globals = getattr(owner, "__globals__", None)
|
| 148 |
+
|
| 149 |
+
# If we pass None to eval() below, the globals of this module are used.
|
| 150 |
+
if globals is None:
|
| 151 |
+
globals = {}
|
| 152 |
+
|
| 153 |
+
if type_params is None and owner is not None:
|
| 154 |
+
type_params = getattr(owner, "__type_params__", None)
|
| 155 |
+
|
| 156 |
+
if locals is None:
|
| 157 |
+
locals = {}
|
| 158 |
+
if isinstance(owner, type):
|
| 159 |
+
locals.update(vars(owner))
|
| 160 |
+
elif (
|
| 161 |
+
type_params is not None
|
| 162 |
+
or isinstance(self.__cell__, dict)
|
| 163 |
+
or self.__extra_names__
|
| 164 |
+
):
|
| 165 |
+
# Create a new locals dict if necessary,
|
| 166 |
+
# to avoid mutating the argument.
|
| 167 |
+
locals = dict(locals)
|
| 168 |
+
|
| 169 |
+
# "Inject" type parameters into the local namespace
|
| 170 |
+
# (unless they are shadowed by assignments *in* the local namespace),
|
| 171 |
+
# as a way of emulating annotation scopes when calling `eval()`
|
| 172 |
+
if type_params is not None:
|
| 173 |
+
for param in type_params:
|
| 174 |
+
locals.setdefault(param.__name__, param)
|
| 175 |
+
|
| 176 |
+
# Similar logic can be used for nonlocals, which should not
|
| 177 |
+
# override locals.
|
| 178 |
+
if isinstance(self.__cell__, dict):
|
| 179 |
+
for cell_name, cell in self.__cell__.items():
|
| 180 |
+
try:
|
| 181 |
+
cell_value = cell.cell_contents
|
| 182 |
+
except ValueError:
|
| 183 |
+
pass
|
| 184 |
+
else:
|
| 185 |
+
locals.setdefault(cell_name, cell_value)
|
| 186 |
+
|
| 187 |
+
if self.__extra_names__:
|
| 188 |
+
locals.update(self.__extra_names__)
|
| 189 |
+
|
| 190 |
+
arg = self.__forward_arg__
|
| 191 |
+
if arg.isidentifier() and not keyword.iskeyword(arg):
|
| 192 |
+
if arg in locals:
|
| 193 |
+
return locals[arg]
|
| 194 |
+
elif arg in globals:
|
| 195 |
+
return globals[arg]
|
| 196 |
+
elif hasattr(builtins, arg):
|
| 197 |
+
return getattr(builtins, arg)
|
| 198 |
+
elif is_forwardref_format:
|
| 199 |
+
return self
|
| 200 |
+
else:
|
| 201 |
+
raise NameError(_NAME_ERROR_MSG.format(name=arg), name=arg)
|
| 202 |
+
else:
|
| 203 |
+
code = self.__forward_code__
|
| 204 |
+
try:
|
| 205 |
+
return eval(code, globals=globals, locals=locals)
|
| 206 |
+
except Exception:
|
| 207 |
+
if not is_forwardref_format:
|
| 208 |
+
raise
|
| 209 |
+
|
| 210 |
+
# All variables, in scoping order, should be checked before
|
| 211 |
+
# triggering __missing__ to create a _Stringifier.
|
| 212 |
+
new_locals = _StringifierDict(
|
| 213 |
+
{**builtins.__dict__, **globals, **locals},
|
| 214 |
+
globals=globals,
|
| 215 |
+
owner=owner,
|
| 216 |
+
is_class=self.__forward_is_class__,
|
| 217 |
+
format=format,
|
| 218 |
+
)
|
| 219 |
+
try:
|
| 220 |
+
result = eval(code, globals=globals, locals=new_locals)
|
| 221 |
+
except Exception:
|
| 222 |
+
return self
|
| 223 |
+
else:
|
| 224 |
+
new_locals.transmogrify(self.__cell__)
|
| 225 |
+
return result
|
| 226 |
+
|
| 227 |
+
def _evaluate(self, globalns, localns, type_params=_sentinel, *, recursive_guard):
|
| 228 |
+
import typing
|
| 229 |
+
import warnings
|
| 230 |
+
|
| 231 |
+
if type_params is _sentinel:
|
| 232 |
+
typing._deprecation_warning_for_no_type_params_passed(
|
| 233 |
+
"typing.ForwardRef._evaluate"
|
| 234 |
+
)
|
| 235 |
+
type_params = ()
|
| 236 |
+
warnings._deprecated(
|
| 237 |
+
"ForwardRef._evaluate",
|
| 238 |
+
"{name} is a private API and is retained for compatibility, but will be removed"
|
| 239 |
+
" in Python 3.16. Use ForwardRef.evaluate() or typing.evaluate_forward_ref() instead.",
|
| 240 |
+
remove=(3, 16),
|
| 241 |
+
)
|
| 242 |
+
return typing.evaluate_forward_ref(
|
| 243 |
+
self,
|
| 244 |
+
globals=globalns,
|
| 245 |
+
locals=localns,
|
| 246 |
+
type_params=type_params,
|
| 247 |
+
_recursive_guard=recursive_guard,
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
@property
|
| 251 |
+
def __forward_arg__(self):
|
| 252 |
+
if self.__arg__ is not None:
|
| 253 |
+
return self.__arg__
|
| 254 |
+
if self.__ast_node__ is not None:
|
| 255 |
+
self.__arg__ = ast.unparse(self.__ast_node__)
|
| 256 |
+
return self.__arg__
|
| 257 |
+
raise AssertionError(
|
| 258 |
+
"Attempted to access '__forward_arg__' on an uninitialized ForwardRef"
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
@property
|
| 262 |
+
def __forward_code__(self):
|
| 263 |
+
if self.__code__ is not None:
|
| 264 |
+
return self.__code__
|
| 265 |
+
arg = self.__forward_arg__
|
| 266 |
+
try:
|
| 267 |
+
self.__code__ = compile(_rewrite_star_unpack(arg), "<string>", "eval")
|
| 268 |
+
except SyntaxError:
|
| 269 |
+
raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
|
| 270 |
+
return self.__code__
|
| 271 |
+
|
| 272 |
+
def __eq__(self, other):
|
| 273 |
+
if not isinstance(other, ForwardRef):
|
| 274 |
+
return NotImplemented
|
| 275 |
+
return (
|
| 276 |
+
self.__forward_arg__ == other.__forward_arg__
|
| 277 |
+
and self.__forward_module__ == other.__forward_module__
|
| 278 |
+
# Use "is" here because we use id() for this in __hash__
|
| 279 |
+
# because dictionaries are not hashable.
|
| 280 |
+
and self.__globals__ is other.__globals__
|
| 281 |
+
and self.__forward_is_class__ == other.__forward_is_class__
|
| 282 |
+
# Two separate cells are always considered unequal in forward refs.
|
| 283 |
+
and (
|
| 284 |
+
{name: id(cell) for name, cell in self.__cell__.items()}
|
| 285 |
+
== {name: id(cell) for name, cell in other.__cell__.items()}
|
| 286 |
+
if isinstance(self.__cell__, dict) and isinstance(other.__cell__, dict)
|
| 287 |
+
else self.__cell__ is other.__cell__
|
| 288 |
+
)
|
| 289 |
+
and self.__owner__ == other.__owner__
|
| 290 |
+
and (
|
| 291 |
+
(tuple(sorted(self.__extra_names__.items())) if self.__extra_names__ else None) ==
|
| 292 |
+
(tuple(sorted(other.__extra_names__.items())) if other.__extra_names__ else None)
|
| 293 |
+
)
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
def __hash__(self):
|
| 297 |
+
return hash((
|
| 298 |
+
self.__forward_arg__,
|
| 299 |
+
self.__forward_module__,
|
| 300 |
+
id(self.__globals__), # dictionaries are not hashable, so hash by identity
|
| 301 |
+
self.__forward_is_class__,
|
| 302 |
+
( # cells are not hashable as well
|
| 303 |
+
tuple(sorted([(name, id(cell)) for name, cell in self.__cell__.items()]))
|
| 304 |
+
if isinstance(self.__cell__, dict) else id(self.__cell__),
|
| 305 |
+
),
|
| 306 |
+
self.__owner__,
|
| 307 |
+
tuple(sorted(self.__extra_names__.items())) if self.__extra_names__ else None,
|
| 308 |
+
))
|
| 309 |
+
|
| 310 |
+
def __or__(self, other):
|
| 311 |
+
return types.UnionType[self, other]
|
| 312 |
+
|
| 313 |
+
def __ror__(self, other):
|
| 314 |
+
return types.UnionType[other, self]
|
| 315 |
+
|
| 316 |
+
def __repr__(self):
|
| 317 |
+
extra = []
|
| 318 |
+
if self.__forward_module__ is not None:
|
| 319 |
+
extra.append(f", module={self.__forward_module__!r}")
|
| 320 |
+
if self.__forward_is_class__:
|
| 321 |
+
extra.append(", is_class=True")
|
| 322 |
+
if self.__owner__ is not None:
|
| 323 |
+
extra.append(f", owner={self.__owner__!r}")
|
| 324 |
+
return f"ForwardRef({self.__forward_arg__!r}{''.join(extra)})"
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
_Template = type(t"")
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class _Stringifier:
|
| 331 |
+
# Must match the slots on ForwardRef, so we can turn an instance of one into an
|
| 332 |
+
# instance of the other in place.
|
| 333 |
+
__slots__ = _SLOTS
|
| 334 |
+
|
| 335 |
+
def __init__(
|
| 336 |
+
self,
|
| 337 |
+
node,
|
| 338 |
+
globals=None,
|
| 339 |
+
owner=None,
|
| 340 |
+
is_class=False,
|
| 341 |
+
cell=None,
|
| 342 |
+
*,
|
| 343 |
+
stringifier_dict,
|
| 344 |
+
extra_names=None,
|
| 345 |
+
):
|
| 346 |
+
# Either an AST node or a simple str (for the common case where a ForwardRef
|
| 347 |
+
# represent a single name).
|
| 348 |
+
assert isinstance(node, (ast.AST, str))
|
| 349 |
+
self.__arg__ = None
|
| 350 |
+
self.__forward_is_argument__ = False
|
| 351 |
+
self.__forward_is_class__ = is_class
|
| 352 |
+
self.__forward_module__ = None
|
| 353 |
+
self.__code__ = None
|
| 354 |
+
self.__ast_node__ = node
|
| 355 |
+
self.__globals__ = globals
|
| 356 |
+
self.__extra_names__ = extra_names
|
| 357 |
+
self.__cell__ = cell
|
| 358 |
+
self.__owner__ = owner
|
| 359 |
+
self.__stringifier_dict__ = stringifier_dict
|
| 360 |
+
|
| 361 |
+
def __convert_to_ast(self, other):
|
| 362 |
+
if isinstance(other, _Stringifier):
|
| 363 |
+
if isinstance(other.__ast_node__, str):
|
| 364 |
+
return ast.Name(id=other.__ast_node__), other.__extra_names__
|
| 365 |
+
return other.__ast_node__, other.__extra_names__
|
| 366 |
+
elif type(other) is _Template:
|
| 367 |
+
return _template_to_ast(other), None
|
| 368 |
+
elif (
|
| 369 |
+
# In STRING format we don't bother with the create_unique_name() dance;
|
| 370 |
+
# it's better to emit the repr() of the object instead of an opaque name.
|
| 371 |
+
self.__stringifier_dict__.format == Format.STRING
|
| 372 |
+
or other is None
|
| 373 |
+
or type(other) in (str, int, float, bool, complex)
|
| 374 |
+
):
|
| 375 |
+
return ast.Constant(value=other), None
|
| 376 |
+
elif type(other) is dict:
|
| 377 |
+
extra_names = {}
|
| 378 |
+
keys = []
|
| 379 |
+
values = []
|
| 380 |
+
for key, value in other.items():
|
| 381 |
+
new_key, new_extra_names = self.__convert_to_ast(key)
|
| 382 |
+
if new_extra_names is not None:
|
| 383 |
+
extra_names.update(new_extra_names)
|
| 384 |
+
keys.append(new_key)
|
| 385 |
+
new_value, new_extra_names = self.__convert_to_ast(value)
|
| 386 |
+
if new_extra_names is not None:
|
| 387 |
+
extra_names.update(new_extra_names)
|
| 388 |
+
values.append(new_value)
|
| 389 |
+
return ast.Dict(keys, values), extra_names
|
| 390 |
+
elif type(other) in (list, tuple, set):
|
| 391 |
+
extra_names = {}
|
| 392 |
+
elts = []
|
| 393 |
+
for elt in other:
|
| 394 |
+
new_elt, new_extra_names = self.__convert_to_ast(elt)
|
| 395 |
+
if new_extra_names is not None:
|
| 396 |
+
extra_names.update(new_extra_names)
|
| 397 |
+
elts.append(new_elt)
|
| 398 |
+
ast_class = {list: ast.List, tuple: ast.Tuple, set: ast.Set}[type(other)]
|
| 399 |
+
return ast_class(elts), extra_names
|
| 400 |
+
else:
|
| 401 |
+
name = self.__stringifier_dict__.create_unique_name()
|
| 402 |
+
return ast.Name(id=name), {name: other}
|
| 403 |
+
|
| 404 |
+
def __convert_to_ast_getitem(self, other):
|
| 405 |
+
if isinstance(other, slice):
|
| 406 |
+
extra_names = {}
|
| 407 |
+
|
| 408 |
+
def conv(obj):
|
| 409 |
+
if obj is None:
|
| 410 |
+
return None
|
| 411 |
+
new_obj, new_extra_names = self.__convert_to_ast(obj)
|
| 412 |
+
if new_extra_names is not None:
|
| 413 |
+
extra_names.update(new_extra_names)
|
| 414 |
+
return new_obj
|
| 415 |
+
|
| 416 |
+
return ast.Slice(
|
| 417 |
+
lower=conv(other.start),
|
| 418 |
+
upper=conv(other.stop),
|
| 419 |
+
step=conv(other.step),
|
| 420 |
+
), extra_names
|
| 421 |
+
else:
|
| 422 |
+
return self.__convert_to_ast(other)
|
| 423 |
+
|
| 424 |
+
def __get_ast(self):
|
| 425 |
+
node = self.__ast_node__
|
| 426 |
+
if isinstance(node, str):
|
| 427 |
+
return ast.Name(id=node)
|
| 428 |
+
return node
|
| 429 |
+
|
| 430 |
+
def __make_new(self, node, extra_names=None):
|
| 431 |
+
new_extra_names = {}
|
| 432 |
+
if self.__extra_names__ is not None:
|
| 433 |
+
new_extra_names.update(self.__extra_names__)
|
| 434 |
+
if extra_names is not None:
|
| 435 |
+
new_extra_names.update(extra_names)
|
| 436 |
+
stringifier = _Stringifier(
|
| 437 |
+
node,
|
| 438 |
+
self.__globals__,
|
| 439 |
+
self.__owner__,
|
| 440 |
+
self.__forward_is_class__,
|
| 441 |
+
stringifier_dict=self.__stringifier_dict__,
|
| 442 |
+
extra_names=new_extra_names or None,
|
| 443 |
+
)
|
| 444 |
+
self.__stringifier_dict__.stringifiers.append(stringifier)
|
| 445 |
+
return stringifier
|
| 446 |
+
|
| 447 |
+
# Must implement this since we set __eq__. We hash by identity so that
|
| 448 |
+
# stringifiers in dict keys are kept separate.
|
| 449 |
+
def __hash__(self):
|
| 450 |
+
return id(self)
|
| 451 |
+
|
| 452 |
+
def __getitem__(self, other):
|
| 453 |
+
# Special case, to avoid stringifying references to class-scoped variables
|
| 454 |
+
# as '__classdict__["x"]'.
|
| 455 |
+
if self.__ast_node__ == "__classdict__":
|
| 456 |
+
raise KeyError
|
| 457 |
+
if isinstance(other, tuple):
|
| 458 |
+
extra_names = {}
|
| 459 |
+
elts = []
|
| 460 |
+
for elt in other:
|
| 461 |
+
new_elt, new_extra_names = self.__convert_to_ast_getitem(elt)
|
| 462 |
+
if new_extra_names is not None:
|
| 463 |
+
extra_names.update(new_extra_names)
|
| 464 |
+
elts.append(new_elt)
|
| 465 |
+
other = ast.Tuple(elts)
|
| 466 |
+
else:
|
| 467 |
+
other, extra_names = self.__convert_to_ast_getitem(other)
|
| 468 |
+
assert isinstance(other, ast.AST), repr(other)
|
| 469 |
+
return self.__make_new(ast.Subscript(self.__get_ast(), other), extra_names)
|
| 470 |
+
|
| 471 |
+
def __getattr__(self, attr):
|
| 472 |
+
return self.__make_new(ast.Attribute(self.__get_ast(), attr))
|
| 473 |
+
|
| 474 |
+
def __call__(self, *args, **kwargs):
|
| 475 |
+
extra_names = {}
|
| 476 |
+
ast_args = []
|
| 477 |
+
for arg in args:
|
| 478 |
+
new_arg, new_extra_names = self.__convert_to_ast(arg)
|
| 479 |
+
if new_extra_names is not None:
|
| 480 |
+
extra_names.update(new_extra_names)
|
| 481 |
+
ast_args.append(new_arg)
|
| 482 |
+
ast_kwargs = []
|
| 483 |
+
for key, value in kwargs.items():
|
| 484 |
+
new_value, new_extra_names = self.__convert_to_ast(value)
|
| 485 |
+
if new_extra_names is not None:
|
| 486 |
+
extra_names.update(new_extra_names)
|
| 487 |
+
ast_kwargs.append(ast.keyword(key, new_value))
|
| 488 |
+
return self.__make_new(ast.Call(self.__get_ast(), ast_args, ast_kwargs), extra_names)
|
| 489 |
+
|
| 490 |
+
def __iter__(self):
|
| 491 |
+
yield self.__make_new(ast.Starred(self.__get_ast()))
|
| 492 |
+
|
| 493 |
+
def __repr__(self):
|
| 494 |
+
if isinstance(self.__ast_node__, str):
|
| 495 |
+
return self.__ast_node__
|
| 496 |
+
return ast.unparse(self.__ast_node__)
|
| 497 |
+
|
| 498 |
+
def __format__(self, format_spec):
|
| 499 |
+
raise TypeError("Cannot stringify annotation containing string formatting")
|
| 500 |
+
|
| 501 |
+
def _make_binop(op: ast.AST):
|
| 502 |
+
def binop(self, other):
|
| 503 |
+
rhs, extra_names = self.__convert_to_ast(other)
|
| 504 |
+
return self.__make_new(
|
| 505 |
+
ast.BinOp(self.__get_ast(), op, rhs), extra_names
|
| 506 |
+
)
|
| 507 |
+
|
| 508 |
+
return binop
|
| 509 |
+
|
| 510 |
+
__add__ = _make_binop(ast.Add())
|
| 511 |
+
__sub__ = _make_binop(ast.Sub())
|
| 512 |
+
__mul__ = _make_binop(ast.Mult())
|
| 513 |
+
__matmul__ = _make_binop(ast.MatMult())
|
| 514 |
+
__truediv__ = _make_binop(ast.Div())
|
| 515 |
+
__mod__ = _make_binop(ast.Mod())
|
| 516 |
+
__lshift__ = _make_binop(ast.LShift())
|
| 517 |
+
__rshift__ = _make_binop(ast.RShift())
|
| 518 |
+
__or__ = _make_binop(ast.BitOr())
|
| 519 |
+
__xor__ = _make_binop(ast.BitXor())
|
| 520 |
+
__and__ = _make_binop(ast.BitAnd())
|
| 521 |
+
__floordiv__ = _make_binop(ast.FloorDiv())
|
| 522 |
+
__pow__ = _make_binop(ast.Pow())
|
| 523 |
+
|
| 524 |
+
del _make_binop
|
| 525 |
+
|
| 526 |
+
def _make_rbinop(op: ast.AST):
|
| 527 |
+
def rbinop(self, other):
|
| 528 |
+
new_other, extra_names = self.__convert_to_ast(other)
|
| 529 |
+
return self.__make_new(
|
| 530 |
+
ast.BinOp(new_other, op, self.__get_ast()), extra_names
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
return rbinop
|
| 534 |
+
|
| 535 |
+
__radd__ = _make_rbinop(ast.Add())
|
| 536 |
+
__rsub__ = _make_rbinop(ast.Sub())
|
| 537 |
+
__rmul__ = _make_rbinop(ast.Mult())
|
| 538 |
+
__rmatmul__ = _make_rbinop(ast.MatMult())
|
| 539 |
+
__rtruediv__ = _make_rbinop(ast.Div())
|
| 540 |
+
__rmod__ = _make_rbinop(ast.Mod())
|
| 541 |
+
__rlshift__ = _make_rbinop(ast.LShift())
|
| 542 |
+
__rrshift__ = _make_rbinop(ast.RShift())
|
| 543 |
+
__ror__ = _make_rbinop(ast.BitOr())
|
| 544 |
+
__rxor__ = _make_rbinop(ast.BitXor())
|
| 545 |
+
__rand__ = _make_rbinop(ast.BitAnd())
|
| 546 |
+
__rfloordiv__ = _make_rbinop(ast.FloorDiv())
|
| 547 |
+
__rpow__ = _make_rbinop(ast.Pow())
|
| 548 |
+
|
| 549 |
+
del _make_rbinop
|
| 550 |
+
|
| 551 |
+
def _make_compare(op):
|
| 552 |
+
def compare(self, other):
|
| 553 |
+
rhs, extra_names = self.__convert_to_ast(other)
|
| 554 |
+
return self.__make_new(
|
| 555 |
+
ast.Compare(
|
| 556 |
+
left=self.__get_ast(),
|
| 557 |
+
ops=[op],
|
| 558 |
+
comparators=[rhs],
|
| 559 |
+
),
|
| 560 |
+
extra_names,
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
return compare
|
| 564 |
+
|
| 565 |
+
__lt__ = _make_compare(ast.Lt())
|
| 566 |
+
__le__ = _make_compare(ast.LtE())
|
| 567 |
+
__eq__ = _make_compare(ast.Eq())
|
| 568 |
+
__ne__ = _make_compare(ast.NotEq())
|
| 569 |
+
__gt__ = _make_compare(ast.Gt())
|
| 570 |
+
__ge__ = _make_compare(ast.GtE())
|
| 571 |
+
|
| 572 |
+
del _make_compare
|
| 573 |
+
|
| 574 |
+
def _make_unary_op(op):
|
| 575 |
+
def unary_op(self):
|
| 576 |
+
return self.__make_new(ast.UnaryOp(op, self.__get_ast()))
|
| 577 |
+
|
| 578 |
+
return unary_op
|
| 579 |
+
|
| 580 |
+
__invert__ = _make_unary_op(ast.Invert())
|
| 581 |
+
__pos__ = _make_unary_op(ast.UAdd())
|
| 582 |
+
__neg__ = _make_unary_op(ast.USub())
|
| 583 |
+
|
| 584 |
+
del _make_unary_op
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
def _template_to_ast_constructor(template):
|
| 588 |
+
"""Convert a `template` instance to a non-literal AST."""
|
| 589 |
+
args = []
|
| 590 |
+
for part in template:
|
| 591 |
+
match part:
|
| 592 |
+
case str():
|
| 593 |
+
args.append(ast.Constant(value=part))
|
| 594 |
+
case _:
|
| 595 |
+
interp = ast.Call(
|
| 596 |
+
func=ast.Name(id="Interpolation"),
|
| 597 |
+
args=[
|
| 598 |
+
ast.Constant(value=part.value),
|
| 599 |
+
ast.Constant(value=part.expression),
|
| 600 |
+
ast.Constant(value=part.conversion),
|
| 601 |
+
ast.Constant(value=part.format_spec),
|
| 602 |
+
]
|
| 603 |
+
)
|
| 604 |
+
args.append(interp)
|
| 605 |
+
return ast.Call(func=ast.Name(id="Template"), args=args, keywords=[])
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
def _template_to_ast_literal(template, parsed):
|
| 609 |
+
"""Convert a `template` instance to a t-string literal AST."""
|
| 610 |
+
values = []
|
| 611 |
+
interp_count = 0
|
| 612 |
+
for part in template:
|
| 613 |
+
match part:
|
| 614 |
+
case str():
|
| 615 |
+
values.append(ast.Constant(value=part))
|
| 616 |
+
case _:
|
| 617 |
+
interp = ast.Interpolation(
|
| 618 |
+
str=part.expression,
|
| 619 |
+
value=parsed[interp_count],
|
| 620 |
+
conversion=ord(part.conversion) if part.conversion else -1,
|
| 621 |
+
format_spec=ast.Constant(value=part.format_spec)
|
| 622 |
+
if part.format_spec
|
| 623 |
+
else None,
|
| 624 |
+
)
|
| 625 |
+
values.append(interp)
|
| 626 |
+
interp_count += 1
|
| 627 |
+
return ast.TemplateStr(values=values)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def _template_to_ast(template):
|
| 631 |
+
"""Make a best-effort conversion of a `template` instance to an AST."""
|
| 632 |
+
# gh-138558: Not all Template instances can be represented as t-string
|
| 633 |
+
# literals. Return the most accurate AST we can. See issue for details.
|
| 634 |
+
|
| 635 |
+
# If any expr is empty or whitespace only, we cannot convert to a literal.
|
| 636 |
+
if any(part.expression.strip() == "" for part in template.interpolations):
|
| 637 |
+
return _template_to_ast_constructor(template)
|
| 638 |
+
|
| 639 |
+
try:
|
| 640 |
+
# Wrap in parens to allow whitespace inside interpolation curly braces
|
| 641 |
+
parsed = tuple(
|
| 642 |
+
ast.parse(f"({part.expression})", mode="eval").body
|
| 643 |
+
for part in template.interpolations
|
| 644 |
+
)
|
| 645 |
+
except SyntaxError:
|
| 646 |
+
return _template_to_ast_constructor(template)
|
| 647 |
+
|
| 648 |
+
return _template_to_ast_literal(template, parsed)
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
class _StringifierDict(dict):
|
| 652 |
+
def __init__(self, namespace, *, globals=None, owner=None, is_class=False, format):
|
| 653 |
+
super().__init__(namespace)
|
| 654 |
+
self.namespace = namespace
|
| 655 |
+
self.globals = globals
|
| 656 |
+
self.owner = owner
|
| 657 |
+
self.is_class = is_class
|
| 658 |
+
self.stringifiers = []
|
| 659 |
+
self.next_id = 1
|
| 660 |
+
self.format = format
|
| 661 |
+
|
| 662 |
+
def __missing__(self, key):
|
| 663 |
+
fwdref = _Stringifier(
|
| 664 |
+
key,
|
| 665 |
+
globals=self.globals,
|
| 666 |
+
owner=self.owner,
|
| 667 |
+
is_class=self.is_class,
|
| 668 |
+
stringifier_dict=self,
|
| 669 |
+
)
|
| 670 |
+
self.stringifiers.append(fwdref)
|
| 671 |
+
return fwdref
|
| 672 |
+
|
| 673 |
+
def transmogrify(self, cell_dict):
|
| 674 |
+
for obj in self.stringifiers:
|
| 675 |
+
obj.__class__ = ForwardRef
|
| 676 |
+
obj.__stringifier_dict__ = None # not needed for ForwardRef
|
| 677 |
+
if isinstance(obj.__ast_node__, str):
|
| 678 |
+
obj.__arg__ = obj.__ast_node__
|
| 679 |
+
obj.__ast_node__ = None
|
| 680 |
+
if cell_dict is not None and obj.__cell__ is None:
|
| 681 |
+
obj.__cell__ = cell_dict
|
| 682 |
+
|
| 683 |
+
def create_unique_name(self):
|
| 684 |
+
name = f"__annotationlib_name_{self.next_id}__"
|
| 685 |
+
self.next_id += 1
|
| 686 |
+
return name
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
def call_evaluate_function(evaluate, format, *, owner=None):
|
| 690 |
+
"""Call an evaluate function. Evaluate functions are normally generated for
|
| 691 |
+
the value of type aliases and the bounds, constraints, and defaults of
|
| 692 |
+
type parameter objects.
|
| 693 |
+
"""
|
| 694 |
+
return call_annotate_function(evaluate, format, owner=owner, _is_evaluate=True)
|
| 695 |
+
|
| 696 |
+
|
| 697 |
+
def call_annotate_function(annotate, format, *, owner=None, _is_evaluate=False):
|
| 698 |
+
"""Call an __annotate__ function. __annotate__ functions are normally
|
| 699 |
+
generated by the compiler to defer the evaluation of annotations. They
|
| 700 |
+
can be called with any of the format arguments in the Format enum, but
|
| 701 |
+
compiler-generated __annotate__ functions only support the VALUE format.
|
| 702 |
+
This function provides additional functionality to call __annotate__
|
| 703 |
+
functions with the FORWARDREF and STRING formats.
|
| 704 |
+
|
| 705 |
+
*annotate* must be an __annotate__ function, which takes a single argument
|
| 706 |
+
and returns a dict of annotations.
|
| 707 |
+
|
| 708 |
+
*format* must be a member of the Format enum or one of the corresponding
|
| 709 |
+
integer values.
|
| 710 |
+
|
| 711 |
+
*owner* can be the object that owns the annotations (i.e., the module,
|
| 712 |
+
class, or function that the __annotate__ function derives from). With the
|
| 713 |
+
FORWARDREF format, it is used to provide better evaluation capabilities
|
| 714 |
+
on the generated ForwardRef objects.
|
| 715 |
+
|
| 716 |
+
"""
|
| 717 |
+
if format == Format.VALUE_WITH_FAKE_GLOBALS:
|
| 718 |
+
raise ValueError("The VALUE_WITH_FAKE_GLOBALS format is for internal use only")
|
| 719 |
+
try:
|
| 720 |
+
return annotate(format)
|
| 721 |
+
except NotImplementedError:
|
| 722 |
+
pass
|
| 723 |
+
if format == Format.STRING:
|
| 724 |
+
# STRING is implemented by calling the annotate function in a special
|
| 725 |
+
# environment where every name lookup results in an instance of _Stringifier.
|
| 726 |
+
# _Stringifier supports every dunder operation and returns a new _Stringifier.
|
| 727 |
+
# At the end, we get a dictionary that mostly contains _Stringifier objects (or
|
| 728 |
+
# possibly constants if the annotate function uses them directly). We then
|
| 729 |
+
# convert each of those into a string to get an approximation of the
|
| 730 |
+
# original source.
|
| 731 |
+
|
| 732 |
+
# Attempt to call with VALUE_WITH_FAKE_GLOBALS to check if it is implemented
|
| 733 |
+
# See: https://github.com/python/cpython/issues/138764
|
| 734 |
+
# Only fail on NotImplementedError
|
| 735 |
+
try:
|
| 736 |
+
annotate(Format.VALUE_WITH_FAKE_GLOBALS)
|
| 737 |
+
except NotImplementedError:
|
| 738 |
+
# Both STRING and VALUE_WITH_FAKE_GLOBALS are not implemented: fallback to VALUE
|
| 739 |
+
return annotations_to_string(annotate(Format.VALUE))
|
| 740 |
+
except Exception:
|
| 741 |
+
pass
|
| 742 |
+
|
| 743 |
+
globals = _StringifierDict({}, format=format)
|
| 744 |
+
is_class = isinstance(owner, type)
|
| 745 |
+
closure, _ = _build_closure(
|
| 746 |
+
annotate, owner, is_class, globals, allow_evaluation=False
|
| 747 |
+
)
|
| 748 |
+
func = types.FunctionType(
|
| 749 |
+
annotate.__code__,
|
| 750 |
+
globals,
|
| 751 |
+
closure=closure,
|
| 752 |
+
argdefs=annotate.__defaults__,
|
| 753 |
+
kwdefaults=annotate.__kwdefaults__,
|
| 754 |
+
)
|
| 755 |
+
annos = func(Format.VALUE_WITH_FAKE_GLOBALS)
|
| 756 |
+
if _is_evaluate:
|
| 757 |
+
return _stringify_single(annos)
|
| 758 |
+
return {
|
| 759 |
+
key: _stringify_single(val)
|
| 760 |
+
for key, val in annos.items()
|
| 761 |
+
}
|
| 762 |
+
elif format == Format.FORWARDREF:
|
| 763 |
+
# FORWARDREF is implemented similarly to STRING, but there are two changes,
|
| 764 |
+
# at the beginning and the end of the process.
|
| 765 |
+
# First, while STRING uses an empty dictionary as the namespace, so that all
|
| 766 |
+
# name lookups result in _Stringifier objects, FORWARDREF uses the globals
|
| 767 |
+
# and builtins, so that defined names map to their real values.
|
| 768 |
+
# Second, instead of returning strings, we want to return either real values
|
| 769 |
+
# or ForwardRef objects. To do this, we keep track of all _Stringifier objects
|
| 770 |
+
# created while the annotation is being evaluated, and at the end we convert
|
| 771 |
+
# them all to ForwardRef objects by assigning to __class__. To make this
|
| 772 |
+
# technique work, we have to ensure that the _Stringifier and ForwardRef
|
| 773 |
+
# classes share the same attributes.
|
| 774 |
+
# We use this technique because while the annotations are being evaluated,
|
| 775 |
+
# we want to support all operations that the language allows, including even
|
| 776 |
+
# __getattr__ and __eq__, and return new _Stringifier objects so we can accurately
|
| 777 |
+
# reconstruct the source. But in the dictionary that we eventually return, we
|
| 778 |
+
# want to return objects with more user-friendly behavior, such as an __eq__
|
| 779 |
+
# that returns a bool and an defined set of attributes.
|
| 780 |
+
namespace = {**annotate.__builtins__, **annotate.__globals__}
|
| 781 |
+
is_class = isinstance(owner, type)
|
| 782 |
+
globals = _StringifierDict(
|
| 783 |
+
namespace,
|
| 784 |
+
globals=annotate.__globals__,
|
| 785 |
+
owner=owner,
|
| 786 |
+
is_class=is_class,
|
| 787 |
+
format=format,
|
| 788 |
+
)
|
| 789 |
+
closure, cell_dict = _build_closure(
|
| 790 |
+
annotate, owner, is_class, globals, allow_evaluation=True
|
| 791 |
+
)
|
| 792 |
+
func = types.FunctionType(
|
| 793 |
+
annotate.__code__,
|
| 794 |
+
globals,
|
| 795 |
+
closure=closure,
|
| 796 |
+
argdefs=annotate.__defaults__,
|
| 797 |
+
kwdefaults=annotate.__kwdefaults__,
|
| 798 |
+
)
|
| 799 |
+
try:
|
| 800 |
+
result = func(Format.VALUE_WITH_FAKE_GLOBALS)
|
| 801 |
+
except NotImplementedError:
|
| 802 |
+
# FORWARDREF and VALUE_WITH_FAKE_GLOBALS not supported, fall back to VALUE
|
| 803 |
+
return annotate(Format.VALUE)
|
| 804 |
+
except Exception:
|
| 805 |
+
pass
|
| 806 |
+
else:
|
| 807 |
+
globals.transmogrify(cell_dict)
|
| 808 |
+
return result
|
| 809 |
+
|
| 810 |
+
# Try again, but do not provide any globals. This allows us to return
|
| 811 |
+
# a value in certain cases where an exception gets raised during evaluation.
|
| 812 |
+
globals = _StringifierDict(
|
| 813 |
+
{},
|
| 814 |
+
globals=annotate.__globals__,
|
| 815 |
+
owner=owner,
|
| 816 |
+
is_class=is_class,
|
| 817 |
+
format=format,
|
| 818 |
+
)
|
| 819 |
+
closure, cell_dict = _build_closure(
|
| 820 |
+
annotate, owner, is_class, globals, allow_evaluation=False
|
| 821 |
+
)
|
| 822 |
+
func = types.FunctionType(
|
| 823 |
+
annotate.__code__,
|
| 824 |
+
globals,
|
| 825 |
+
closure=closure,
|
| 826 |
+
argdefs=annotate.__defaults__,
|
| 827 |
+
kwdefaults=annotate.__kwdefaults__,
|
| 828 |
+
)
|
| 829 |
+
result = func(Format.VALUE_WITH_FAKE_GLOBALS)
|
| 830 |
+
globals.transmogrify(cell_dict)
|
| 831 |
+
if _is_evaluate:
|
| 832 |
+
if isinstance(result, ForwardRef):
|
| 833 |
+
return result.evaluate(format=Format.FORWARDREF)
|
| 834 |
+
else:
|
| 835 |
+
return result
|
| 836 |
+
else:
|
| 837 |
+
return {
|
| 838 |
+
key: (
|
| 839 |
+
val.evaluate(format=Format.FORWARDREF)
|
| 840 |
+
if isinstance(val, ForwardRef)
|
| 841 |
+
else val
|
| 842 |
+
)
|
| 843 |
+
for key, val in result.items()
|
| 844 |
+
}
|
| 845 |
+
elif format == Format.VALUE:
|
| 846 |
+
# Should be impossible because __annotate__ functions must not raise
|
| 847 |
+
# NotImplementedError for this format.
|
| 848 |
+
raise RuntimeError("annotate function does not support VALUE format")
|
| 849 |
+
else:
|
| 850 |
+
raise ValueError(f"Invalid format: {format!r}")
|
| 851 |
+
|
| 852 |
+
|
| 853 |
+
def _build_closure(annotate, owner, is_class, stringifier_dict, *, allow_evaluation):
|
| 854 |
+
if not annotate.__closure__:
|
| 855 |
+
return None, None
|
| 856 |
+
new_closure = []
|
| 857 |
+
cell_dict = {}
|
| 858 |
+
for name, cell in zip(annotate.__code__.co_freevars, annotate.__closure__, strict=True):
|
| 859 |
+
cell_dict[name] = cell
|
| 860 |
+
new_cell = None
|
| 861 |
+
if allow_evaluation:
|
| 862 |
+
try:
|
| 863 |
+
cell.cell_contents
|
| 864 |
+
except ValueError:
|
| 865 |
+
pass
|
| 866 |
+
else:
|
| 867 |
+
new_cell = cell
|
| 868 |
+
if new_cell is None:
|
| 869 |
+
fwdref = _Stringifier(
|
| 870 |
+
name,
|
| 871 |
+
cell=cell,
|
| 872 |
+
owner=owner,
|
| 873 |
+
globals=annotate.__globals__,
|
| 874 |
+
is_class=is_class,
|
| 875 |
+
stringifier_dict=stringifier_dict,
|
| 876 |
+
)
|
| 877 |
+
stringifier_dict.stringifiers.append(fwdref)
|
| 878 |
+
new_cell = types.CellType(fwdref)
|
| 879 |
+
new_closure.append(new_cell)
|
| 880 |
+
return tuple(new_closure), cell_dict
|
| 881 |
+
|
| 882 |
+
|
| 883 |
+
def _stringify_single(anno):
|
| 884 |
+
if anno is ...:
|
| 885 |
+
return "..."
|
| 886 |
+
# We have to handle str specially to support PEP 563 stringified annotations.
|
| 887 |
+
elif isinstance(anno, str):
|
| 888 |
+
return anno
|
| 889 |
+
elif isinstance(anno, _Template):
|
| 890 |
+
return ast.unparse(_template_to_ast(anno))
|
| 891 |
+
else:
|
| 892 |
+
return repr(anno)
|
| 893 |
+
|
| 894 |
+
|
| 895 |
+
def get_annotate_from_class_namespace(obj):
|
| 896 |
+
"""Retrieve the annotate function from a class namespace dictionary.
|
| 897 |
+
|
| 898 |
+
Return None if the namespace does not contain an annotate function.
|
| 899 |
+
This is useful in metaclass ``__new__`` methods to retrieve the annotate function.
|
| 900 |
+
"""
|
| 901 |
+
try:
|
| 902 |
+
return obj["__annotate__"]
|
| 903 |
+
except KeyError:
|
| 904 |
+
return obj.get("__annotate_func__", None)
|
| 905 |
+
|
| 906 |
+
|
| 907 |
+
def get_annotations(
|
| 908 |
+
obj, *, globals=None, locals=None, eval_str=False, format=Format.VALUE
|
| 909 |
+
):
|
| 910 |
+
"""Compute the annotations dict for an object.
|
| 911 |
+
|
| 912 |
+
obj may be a callable, class, module, or other object with
|
| 913 |
+
__annotate__ or __annotations__ attributes.
|
| 914 |
+
Passing any other object raises TypeError.
|
| 915 |
+
|
| 916 |
+
The *format* parameter controls the format in which annotations are returned,
|
| 917 |
+
and must be a member of the Format enum or its integer equivalent.
|
| 918 |
+
For the VALUE format, the __annotations__ is tried first; if it
|
| 919 |
+
does not exist, the __annotate__ function is called. The
|
| 920 |
+
FORWARDREF format uses __annotations__ if it exists and can be
|
| 921 |
+
evaluated, and otherwise falls back to calling the __annotate__ function.
|
| 922 |
+
The STRING format tries __annotate__ first, and falls back to
|
| 923 |
+
using __annotations__, stringified using annotations_to_string().
|
| 924 |
+
|
| 925 |
+
This function handles several details for you:
|
| 926 |
+
|
| 927 |
+
* If eval_str is true, values of type str will
|
| 928 |
+
be un-stringized using eval(). This is intended
|
| 929 |
+
for use with stringized annotations
|
| 930 |
+
("from __future__ import annotations").
|
| 931 |
+
* If obj doesn't have an annotations dict, returns an
|
| 932 |
+
empty dict. (Functions and methods always have an
|
| 933 |
+
annotations dict; classes, modules, and other types of
|
| 934 |
+
callables may not.)
|
| 935 |
+
* Ignores inherited annotations on classes. If a class
|
| 936 |
+
doesn't have its own annotations dict, returns an empty dict.
|
| 937 |
+
* All accesses to object members and dict values are done
|
| 938 |
+
using getattr() and dict.get() for safety.
|
| 939 |
+
* Always, always, always returns a freshly-created dict.
|
| 940 |
+
|
| 941 |
+
eval_str controls whether or not values of type str are replaced
|
| 942 |
+
with the result of calling eval() on those values:
|
| 943 |
+
|
| 944 |
+
* If eval_str is true, eval() is called on values of type str.
|
| 945 |
+
* If eval_str is false (the default), values of type str are unchanged.
|
| 946 |
+
|
| 947 |
+
globals and locals are passed in to eval(); see the documentation
|
| 948 |
+
for eval() for more information. If either globals or locals is
|
| 949 |
+
None, this function may replace that value with a context-specific
|
| 950 |
+
default, contingent on type(obj):
|
| 951 |
+
|
| 952 |
+
* If obj is a module, globals defaults to obj.__dict__.
|
| 953 |
+
* If obj is a class, globals defaults to
|
| 954 |
+
sys.modules[obj.__module__].__dict__ and locals
|
| 955 |
+
defaults to the obj class namespace.
|
| 956 |
+
* If obj is a callable, globals defaults to obj.__globals__,
|
| 957 |
+
although if obj is a wrapped function (using
|
| 958 |
+
functools.update_wrapper()) it is first unwrapped.
|
| 959 |
+
"""
|
| 960 |
+
if eval_str and format != Format.VALUE:
|
| 961 |
+
raise ValueError("eval_str=True is only supported with format=Format.VALUE")
|
| 962 |
+
|
| 963 |
+
match format:
|
| 964 |
+
case Format.VALUE:
|
| 965 |
+
# For VALUE, we first look at __annotations__
|
| 966 |
+
ann = _get_dunder_annotations(obj)
|
| 967 |
+
|
| 968 |
+
# If it's not there, try __annotate__ instead
|
| 969 |
+
if ann is None:
|
| 970 |
+
ann = _get_and_call_annotate(obj, format)
|
| 971 |
+
case Format.FORWARDREF:
|
| 972 |
+
# For FORWARDREF, we use __annotations__ if it exists
|
| 973 |
+
try:
|
| 974 |
+
ann = _get_dunder_annotations(obj)
|
| 975 |
+
except Exception:
|
| 976 |
+
pass
|
| 977 |
+
else:
|
| 978 |
+
if ann is not None:
|
| 979 |
+
return dict(ann)
|
| 980 |
+
|
| 981 |
+
# But if __annotations__ threw a NameError, we try calling __annotate__
|
| 982 |
+
ann = _get_and_call_annotate(obj, format)
|
| 983 |
+
if ann is None:
|
| 984 |
+
# If that didn't work either, we have a very weird object: evaluating
|
| 985 |
+
# __annotations__ threw NameError and there is no __annotate__. In that case,
|
| 986 |
+
# we fall back to trying __annotations__ again.
|
| 987 |
+
ann = _get_dunder_annotations(obj)
|
| 988 |
+
case Format.STRING:
|
| 989 |
+
# For STRING, we try to call __annotate__
|
| 990 |
+
ann = _get_and_call_annotate(obj, format)
|
| 991 |
+
if ann is not None:
|
| 992 |
+
return dict(ann)
|
| 993 |
+
# But if we didn't get it, we use __annotations__ instead.
|
| 994 |
+
ann = _get_dunder_annotations(obj)
|
| 995 |
+
if ann is not None:
|
| 996 |
+
return annotations_to_string(ann)
|
| 997 |
+
case Format.VALUE_WITH_FAKE_GLOBALS:
|
| 998 |
+
raise ValueError("The VALUE_WITH_FAKE_GLOBALS format is for internal use only")
|
| 999 |
+
case _:
|
| 1000 |
+
raise ValueError(f"Unsupported format {format!r}")
|
| 1001 |
+
|
| 1002 |
+
if ann is None:
|
| 1003 |
+
if isinstance(obj, type) or callable(obj):
|
| 1004 |
+
return {}
|
| 1005 |
+
raise TypeError(f"{obj!r} does not have annotations")
|
| 1006 |
+
|
| 1007 |
+
if not ann:
|
| 1008 |
+
return {}
|
| 1009 |
+
|
| 1010 |
+
if not eval_str:
|
| 1011 |
+
return dict(ann)
|
| 1012 |
+
|
| 1013 |
+
if globals is None or locals is None:
|
| 1014 |
+
if isinstance(obj, type):
|
| 1015 |
+
# class
|
| 1016 |
+
obj_globals = None
|
| 1017 |
+
module_name = getattr(obj, "__module__", None)
|
| 1018 |
+
if module_name:
|
| 1019 |
+
module = sys.modules.get(module_name, None)
|
| 1020 |
+
if module:
|
| 1021 |
+
obj_globals = getattr(module, "__dict__", None)
|
| 1022 |
+
obj_locals = dict(vars(obj))
|
| 1023 |
+
unwrap = obj
|
| 1024 |
+
elif isinstance(obj, types.ModuleType):
|
| 1025 |
+
# module
|
| 1026 |
+
obj_globals = getattr(obj, "__dict__")
|
| 1027 |
+
obj_locals = None
|
| 1028 |
+
unwrap = None
|
| 1029 |
+
elif callable(obj):
|
| 1030 |
+
# this includes types.Function, types.BuiltinFunctionType,
|
| 1031 |
+
# types.BuiltinMethodType, functools.partial, functools.singledispatch,
|
| 1032 |
+
# "class funclike" from Lib/test/test_inspect... on and on it goes.
|
| 1033 |
+
obj_globals = getattr(obj, "__globals__", None)
|
| 1034 |
+
obj_locals = None
|
| 1035 |
+
unwrap = obj
|
| 1036 |
+
else:
|
| 1037 |
+
obj_globals = obj_locals = unwrap = None
|
| 1038 |
+
|
| 1039 |
+
if unwrap is not None:
|
| 1040 |
+
# Use an id-based visited set to detect cycles in the __wrapped__
|
| 1041 |
+
# and functools.partial.func chain (e.g. f.__wrapped__ = f).
|
| 1042 |
+
# On cycle detection we stop and use whatever __globals__ we have
|
| 1043 |
+
# found so far, mirroring the approach of inspect.unwrap().
|
| 1044 |
+
_seen_ids = {id(unwrap)}
|
| 1045 |
+
while True:
|
| 1046 |
+
if hasattr(unwrap, "__wrapped__"):
|
| 1047 |
+
candidate = unwrap.__wrapped__
|
| 1048 |
+
if id(candidate) in _seen_ids:
|
| 1049 |
+
break
|
| 1050 |
+
_seen_ids.add(id(candidate))
|
| 1051 |
+
unwrap = candidate
|
| 1052 |
+
continue
|
| 1053 |
+
if functools := sys.modules.get("functools"):
|
| 1054 |
+
if isinstance(unwrap, functools.partial):
|
| 1055 |
+
candidate = unwrap.func
|
| 1056 |
+
if id(candidate) in _seen_ids:
|
| 1057 |
+
break
|
| 1058 |
+
_seen_ids.add(id(candidate))
|
| 1059 |
+
unwrap = candidate
|
| 1060 |
+
continue
|
| 1061 |
+
break
|
| 1062 |
+
if hasattr(unwrap, "__globals__"):
|
| 1063 |
+
obj_globals = unwrap.__globals__
|
| 1064 |
+
|
| 1065 |
+
if globals is None:
|
| 1066 |
+
globals = obj_globals
|
| 1067 |
+
if locals is None:
|
| 1068 |
+
locals = obj_locals
|
| 1069 |
+
|
| 1070 |
+
# "Inject" type parameters into the local namespace
|
| 1071 |
+
# (unless they are shadowed by assignments *in* the local namespace),
|
| 1072 |
+
# as a way of emulating annotation scopes when calling `eval()`
|
| 1073 |
+
if type_params := getattr(obj, "__type_params__", ()):
|
| 1074 |
+
if locals is None:
|
| 1075 |
+
locals = {}
|
| 1076 |
+
locals = {param.__name__: param for param in type_params} | locals
|
| 1077 |
+
|
| 1078 |
+
return_value = {
|
| 1079 |
+
key: value if not isinstance(value, str)
|
| 1080 |
+
else eval(_rewrite_star_unpack(value), globals, locals)
|
| 1081 |
+
for key, value in ann.items()
|
| 1082 |
+
}
|
| 1083 |
+
return return_value
|
| 1084 |
+
|
| 1085 |
+
|
| 1086 |
+
def type_repr(value):
|
| 1087 |
+
"""Convert a Python value to a format suitable for use with the STRING format.
|
| 1088 |
+
|
| 1089 |
+
This is intended as a helper for tools that support the STRING format but do
|
| 1090 |
+
not have access to the code that originally produced the annotations. It uses
|
| 1091 |
+
repr() for most objects.
|
| 1092 |
+
|
| 1093 |
+
"""
|
| 1094 |
+
if isinstance(value, (type, types.FunctionType, types.BuiltinFunctionType)):
|
| 1095 |
+
if value.__module__ == "builtins":
|
| 1096 |
+
return value.__qualname__
|
| 1097 |
+
return f"{value.__module__}.{value.__qualname__}"
|
| 1098 |
+
elif isinstance(value, _Template):
|
| 1099 |
+
tree = _template_to_ast(value)
|
| 1100 |
+
return ast.unparse(tree)
|
| 1101 |
+
if value is ...:
|
| 1102 |
+
return "..."
|
| 1103 |
+
return repr(value)
|
| 1104 |
+
|
| 1105 |
+
|
| 1106 |
+
def annotations_to_string(annotations):
|
| 1107 |
+
"""Convert an annotation dict containing values to approximately the STRING format.
|
| 1108 |
+
|
| 1109 |
+
Always returns a fresh a dictionary.
|
| 1110 |
+
"""
|
| 1111 |
+
return {
|
| 1112 |
+
n: t if isinstance(t, str) else type_repr(t)
|
| 1113 |
+
for n, t in annotations.items()
|
| 1114 |
+
}
|
| 1115 |
+
|
| 1116 |
+
|
| 1117 |
+
def _rewrite_star_unpack(arg):
|
| 1118 |
+
"""If the given argument annotation expression is a star unpack e.g. `'*Ts'`
|
| 1119 |
+
rewrite it to a valid expression.
|
| 1120 |
+
"""
|
| 1121 |
+
if arg.lstrip().startswith("*"):
|
| 1122 |
+
return f"({arg},)[0]" # E.g. (*Ts,)[0] or (*tuple[int, int],)[0]
|
| 1123 |
+
else:
|
| 1124 |
+
return arg
|
| 1125 |
+
|
| 1126 |
+
|
| 1127 |
+
def _get_and_call_annotate(obj, format):
|
| 1128 |
+
"""Get the __annotate__ function and call it.
|
| 1129 |
+
|
| 1130 |
+
May not return a fresh dictionary.
|
| 1131 |
+
"""
|
| 1132 |
+
annotate = getattr(obj, "__annotate__", None)
|
| 1133 |
+
if annotate is not None:
|
| 1134 |
+
ann = call_annotate_function(annotate, format, owner=obj)
|
| 1135 |
+
if not isinstance(ann, dict):
|
| 1136 |
+
raise ValueError(f"{obj!r}.__annotate__ returned a non-dict")
|
| 1137 |
+
return ann
|
| 1138 |
+
return None
|
| 1139 |
+
|
| 1140 |
+
|
| 1141 |
+
_BASE_GET_ANNOTATIONS = type.__dict__["__annotations__"].__get__
|
| 1142 |
+
|
| 1143 |
+
|
| 1144 |
+
def _get_dunder_annotations(obj):
|
| 1145 |
+
"""Return the annotations for an object, checking that it is a dictionary.
|
| 1146 |
+
|
| 1147 |
+
Does not return a fresh dictionary.
|
| 1148 |
+
"""
|
| 1149 |
+
# This special case is needed to support types defined under
|
| 1150 |
+
# from __future__ import annotations, where accessing the __annotations__
|
| 1151 |
+
# attribute directly might return annotations for the wrong class.
|
| 1152 |
+
if isinstance(obj, type):
|
| 1153 |
+
try:
|
| 1154 |
+
ann = _BASE_GET_ANNOTATIONS(obj)
|
| 1155 |
+
except AttributeError:
|
| 1156 |
+
# For static types, the descriptor raises AttributeError.
|
| 1157 |
+
return None
|
| 1158 |
+
else:
|
| 1159 |
+
ann = getattr(obj, "__annotations__", None)
|
| 1160 |
+
if ann is None:
|
| 1161 |
+
return None
|
| 1162 |
+
|
| 1163 |
+
if not isinstance(ann, dict):
|
| 1164 |
+
raise ValueError(f"{obj!r}.__annotations__ is neither a dict nor None")
|
| 1165 |
+
return ann
|
micromamba_root/envs/hf_sync/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/envs/hf_sync/Lib/argparse.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
micromamba_root/envs/hf_sync/Lib/ast.py
ADDED
|
@@ -0,0 +1,680 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
The `ast` module helps Python applications to process trees of the Python
|
| 3 |
+
abstract syntax grammar. The abstract syntax itself might change with
|
| 4 |
+
each Python release; this module helps to find out programmatically what
|
| 5 |
+
the current grammar looks like and allows modifications of it.
|
| 6 |
+
|
| 7 |
+
An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as
|
| 8 |
+
a flag to the `compile()` builtin function or by using the `parse()`
|
| 9 |
+
function from this module. The result will be a tree of objects whose
|
| 10 |
+
classes all inherit from `ast.AST`.
|
| 11 |
+
|
| 12 |
+
A modified abstract syntax tree can be compiled into a Python code object
|
| 13 |
+
using the built-in `compile()` function.
|
| 14 |
+
|
| 15 |
+
Additionally various helper functions are provided that make working with
|
| 16 |
+
the trees simpler. The main intention of the helper functions and this
|
| 17 |
+
module in general is to provide an easy to use interface for libraries
|
| 18 |
+
that work tightly with the python syntax (template engines for example).
|
| 19 |
+
|
| 20 |
+
:copyright: Copyright 2008 by Armin Ronacher.
|
| 21 |
+
:license: Python License.
|
| 22 |
+
"""
|
| 23 |
+
from _ast import *
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def parse(source, filename='<unknown>', mode='exec', *,
|
| 27 |
+
type_comments=False, feature_version=None, optimize=-1):
|
| 28 |
+
"""
|
| 29 |
+
Parse the source into an AST node.
|
| 30 |
+
Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
|
| 31 |
+
Pass type_comments=True to get back type comments where the syntax allows.
|
| 32 |
+
"""
|
| 33 |
+
flags = PyCF_ONLY_AST
|
| 34 |
+
if optimize > 0:
|
| 35 |
+
flags |= PyCF_OPTIMIZED_AST
|
| 36 |
+
if type_comments:
|
| 37 |
+
flags |= PyCF_TYPE_COMMENTS
|
| 38 |
+
if feature_version is None:
|
| 39 |
+
feature_version = -1
|
| 40 |
+
elif isinstance(feature_version, tuple):
|
| 41 |
+
major, minor = feature_version # Should be a 2-tuple.
|
| 42 |
+
if major != 3:
|
| 43 |
+
raise ValueError(f"Unsupported major version: {major}")
|
| 44 |
+
feature_version = minor
|
| 45 |
+
# Else it should be an int giving the minor version for 3.x.
|
| 46 |
+
return compile(source, filename, mode, flags,
|
| 47 |
+
_feature_version=feature_version, optimize=optimize)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def literal_eval(node_or_string):
|
| 51 |
+
"""
|
| 52 |
+
Evaluate an expression node or a string containing only a Python
|
| 53 |
+
expression. The string or node provided may only consist of the following
|
| 54 |
+
Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
|
| 55 |
+
sets, booleans, and None.
|
| 56 |
+
|
| 57 |
+
Caution: A complex expression can overflow the C stack and cause a crash.
|
| 58 |
+
"""
|
| 59 |
+
if isinstance(node_or_string, str):
|
| 60 |
+
node_or_string = parse(node_or_string.lstrip(" \t"), mode='eval')
|
| 61 |
+
if isinstance(node_or_string, Expression):
|
| 62 |
+
node_or_string = node_or_string.body
|
| 63 |
+
def _raise_malformed_node(node):
|
| 64 |
+
msg = "malformed node or string"
|
| 65 |
+
if lno := getattr(node, 'lineno', None):
|
| 66 |
+
msg += f' on line {lno}'
|
| 67 |
+
raise ValueError(msg + f': {node!r}')
|
| 68 |
+
def _convert_num(node):
|
| 69 |
+
if not isinstance(node, Constant) or type(node.value) not in (int, float, complex):
|
| 70 |
+
_raise_malformed_node(node)
|
| 71 |
+
return node.value
|
| 72 |
+
def _convert_signed_num(node):
|
| 73 |
+
if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)):
|
| 74 |
+
operand = _convert_num(node.operand)
|
| 75 |
+
if isinstance(node.op, UAdd):
|
| 76 |
+
return + operand
|
| 77 |
+
else:
|
| 78 |
+
return - operand
|
| 79 |
+
return _convert_num(node)
|
| 80 |
+
def _convert(node):
|
| 81 |
+
if isinstance(node, Constant):
|
| 82 |
+
return node.value
|
| 83 |
+
elif isinstance(node, Tuple):
|
| 84 |
+
return tuple(map(_convert, node.elts))
|
| 85 |
+
elif isinstance(node, List):
|
| 86 |
+
return list(map(_convert, node.elts))
|
| 87 |
+
elif isinstance(node, Set):
|
| 88 |
+
return set(map(_convert, node.elts))
|
| 89 |
+
elif (isinstance(node, Call) and isinstance(node.func, Name) and
|
| 90 |
+
node.func.id == 'set' and node.args == node.keywords == []):
|
| 91 |
+
return set()
|
| 92 |
+
elif isinstance(node, Dict):
|
| 93 |
+
if len(node.keys) != len(node.values):
|
| 94 |
+
_raise_malformed_node(node)
|
| 95 |
+
return dict(zip(map(_convert, node.keys),
|
| 96 |
+
map(_convert, node.values)))
|
| 97 |
+
elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):
|
| 98 |
+
left = _convert_signed_num(node.left)
|
| 99 |
+
right = _convert_num(node.right)
|
| 100 |
+
if isinstance(left, (int, float)) and isinstance(right, complex):
|
| 101 |
+
if isinstance(node.op, Add):
|
| 102 |
+
return left + right
|
| 103 |
+
else:
|
| 104 |
+
return left - right
|
| 105 |
+
return _convert_signed_num(node)
|
| 106 |
+
return _convert(node_or_string)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def dump(
|
| 110 |
+
node, annotate_fields=True, include_attributes=False,
|
| 111 |
+
*,
|
| 112 |
+
indent=None, show_empty=False,
|
| 113 |
+
):
|
| 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 |
+
If show_empty is False, then empty lists and fields that are None
|
| 125 |
+
will be omitted from the output for better readability.
|
| 126 |
+
"""
|
| 127 |
+
def _format(node, level=0):
|
| 128 |
+
if indent is not None:
|
| 129 |
+
level += 1
|
| 130 |
+
prefix = '\n' + indent * level
|
| 131 |
+
sep = ',\n' + indent * level
|
| 132 |
+
else:
|
| 133 |
+
prefix = ''
|
| 134 |
+
sep = ', '
|
| 135 |
+
if isinstance(node, AST):
|
| 136 |
+
cls = type(node)
|
| 137 |
+
args = []
|
| 138 |
+
args_buffer = []
|
| 139 |
+
allsimple = True
|
| 140 |
+
keywords = annotate_fields
|
| 141 |
+
for name in node._fields:
|
| 142 |
+
try:
|
| 143 |
+
value = getattr(node, name)
|
| 144 |
+
except AttributeError:
|
| 145 |
+
keywords = True
|
| 146 |
+
continue
|
| 147 |
+
if value is None and getattr(cls, name, ...) is None:
|
| 148 |
+
keywords = True
|
| 149 |
+
continue
|
| 150 |
+
if not show_empty:
|
| 151 |
+
if value == []:
|
| 152 |
+
field_type = cls._field_types.get(name, object)
|
| 153 |
+
if getattr(field_type, '__origin__', ...) is list:
|
| 154 |
+
if not keywords:
|
| 155 |
+
args_buffer.append(repr(value))
|
| 156 |
+
continue
|
| 157 |
+
if not keywords:
|
| 158 |
+
args.extend(args_buffer)
|
| 159 |
+
args_buffer = []
|
| 160 |
+
value, simple = _format(value, level)
|
| 161 |
+
allsimple = allsimple and simple
|
| 162 |
+
if keywords:
|
| 163 |
+
args.append('%s=%s' % (name, value))
|
| 164 |
+
else:
|
| 165 |
+
args.append(value)
|
| 166 |
+
if include_attributes and node._attributes:
|
| 167 |
+
for name in node._attributes:
|
| 168 |
+
try:
|
| 169 |
+
value = getattr(node, name)
|
| 170 |
+
except AttributeError:
|
| 171 |
+
continue
|
| 172 |
+
if value is None and getattr(cls, name, ...) is None:
|
| 173 |
+
continue
|
| 174 |
+
value, simple = _format(value, level)
|
| 175 |
+
allsimple = allsimple and simple
|
| 176 |
+
args.append('%s=%s' % (name, value))
|
| 177 |
+
if allsimple and len(args) <= 3:
|
| 178 |
+
return '%s(%s)' % (node.__class__.__name__, ', '.join(args)), not args
|
| 179 |
+
return '%s(%s%s)' % (node.__class__.__name__, prefix, sep.join(args)), False
|
| 180 |
+
elif isinstance(node, list):
|
| 181 |
+
if not node:
|
| 182 |
+
return '[]', True
|
| 183 |
+
return '[%s%s]' % (prefix, sep.join(_format(x, level)[0] for x in node)), False
|
| 184 |
+
return repr(node), True
|
| 185 |
+
|
| 186 |
+
if not isinstance(node, AST):
|
| 187 |
+
raise TypeError('expected AST, got %r' % node.__class__.__name__)
|
| 188 |
+
if indent is not None and not isinstance(indent, str):
|
| 189 |
+
indent = ' ' * indent
|
| 190 |
+
return _format(node)[0]
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def copy_location(new_node, old_node):
|
| 194 |
+
"""
|
| 195 |
+
Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset`
|
| 196 |
+
attributes) from *old_node* to *new_node* if possible, and return *new_node*.
|
| 197 |
+
"""
|
| 198 |
+
for attr in 'lineno', 'col_offset', 'end_lineno', 'end_col_offset':
|
| 199 |
+
if attr in old_node._attributes and attr in new_node._attributes:
|
| 200 |
+
value = getattr(old_node, attr, None)
|
| 201 |
+
# end_lineno and end_col_offset are optional attributes, and they
|
| 202 |
+
# should be copied whether the value is None or not.
|
| 203 |
+
if value is not None or (
|
| 204 |
+
hasattr(old_node, attr) and attr.startswith("end_")
|
| 205 |
+
):
|
| 206 |
+
setattr(new_node, attr, value)
|
| 207 |
+
return new_node
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def fix_missing_locations(node):
|
| 211 |
+
"""
|
| 212 |
+
When you compile a node tree with compile(), the compiler expects lineno and
|
| 213 |
+
col_offset attributes for every node that supports them. This is rather
|
| 214 |
+
tedious to fill in for generated nodes, so this helper adds these attributes
|
| 215 |
+
recursively where not already set, by setting them to the values of the
|
| 216 |
+
parent node. It works recursively starting at *node*.
|
| 217 |
+
"""
|
| 218 |
+
def _fix(node, lineno, col_offset, end_lineno, end_col_offset):
|
| 219 |
+
if 'lineno' in node._attributes:
|
| 220 |
+
if not hasattr(node, 'lineno'):
|
| 221 |
+
node.lineno = lineno
|
| 222 |
+
else:
|
| 223 |
+
lineno = node.lineno
|
| 224 |
+
if 'end_lineno' in node._attributes:
|
| 225 |
+
if getattr(node, 'end_lineno', None) is None:
|
| 226 |
+
node.end_lineno = end_lineno
|
| 227 |
+
else:
|
| 228 |
+
end_lineno = node.end_lineno
|
| 229 |
+
if 'col_offset' in node._attributes:
|
| 230 |
+
if not hasattr(node, 'col_offset'):
|
| 231 |
+
node.col_offset = col_offset
|
| 232 |
+
else:
|
| 233 |
+
col_offset = node.col_offset
|
| 234 |
+
if 'end_col_offset' in node._attributes:
|
| 235 |
+
if getattr(node, 'end_col_offset', None) is None:
|
| 236 |
+
node.end_col_offset = end_col_offset
|
| 237 |
+
else:
|
| 238 |
+
end_col_offset = node.end_col_offset
|
| 239 |
+
for child in iter_child_nodes(node):
|
| 240 |
+
_fix(child, lineno, col_offset, end_lineno, end_col_offset)
|
| 241 |
+
_fix(node, 1, 0, 1, 0)
|
| 242 |
+
return node
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def increment_lineno(node, n=1):
|
| 246 |
+
"""
|
| 247 |
+
Increment the line number and end line number of each node in the tree
|
| 248 |
+
starting at *node* by *n*. This is useful to "move code" to a different
|
| 249 |
+
location in a file.
|
| 250 |
+
"""
|
| 251 |
+
for child in walk(node):
|
| 252 |
+
# TypeIgnore is a special case where lineno is not an attribute
|
| 253 |
+
# but rather a field of the node itself.
|
| 254 |
+
if isinstance(child, TypeIgnore):
|
| 255 |
+
child.lineno = getattr(child, 'lineno', 0) + n
|
| 256 |
+
continue
|
| 257 |
+
|
| 258 |
+
if 'lineno' in child._attributes:
|
| 259 |
+
child.lineno = getattr(child, 'lineno', 0) + n
|
| 260 |
+
if (
|
| 261 |
+
"end_lineno" in child._attributes
|
| 262 |
+
and (end_lineno := getattr(child, "end_lineno", 0)) is not None
|
| 263 |
+
):
|
| 264 |
+
child.end_lineno = end_lineno + n
|
| 265 |
+
return node
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def iter_fields(node):
|
| 269 |
+
"""
|
| 270 |
+
Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
|
| 271 |
+
that is present on *node*.
|
| 272 |
+
"""
|
| 273 |
+
for field in node._fields:
|
| 274 |
+
try:
|
| 275 |
+
yield field, getattr(node, field)
|
| 276 |
+
except AttributeError:
|
| 277 |
+
pass
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def iter_child_nodes(node):
|
| 281 |
+
"""
|
| 282 |
+
Yield all direct child nodes of *node*, that is, all fields that are nodes
|
| 283 |
+
and all items of fields that are lists of nodes.
|
| 284 |
+
"""
|
| 285 |
+
for name, field in iter_fields(node):
|
| 286 |
+
if isinstance(field, AST):
|
| 287 |
+
yield field
|
| 288 |
+
elif isinstance(field, list):
|
| 289 |
+
for item in field:
|
| 290 |
+
if isinstance(item, AST):
|
| 291 |
+
yield item
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def get_docstring(node, clean=True):
|
| 295 |
+
"""
|
| 296 |
+
Return the docstring for the given node or None if no docstring can
|
| 297 |
+
be found. If the node provided does not have docstrings a TypeError
|
| 298 |
+
will be raised.
|
| 299 |
+
|
| 300 |
+
If *clean* is `True`, all tabs are expanded to spaces and any whitespace
|
| 301 |
+
that can be uniformly removed from the second line onwards is removed.
|
| 302 |
+
"""
|
| 303 |
+
if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):
|
| 304 |
+
raise TypeError("%r can't have docstrings" % node.__class__.__name__)
|
| 305 |
+
if not(node.body and isinstance(node.body[0], Expr)):
|
| 306 |
+
return None
|
| 307 |
+
node = node.body[0].value
|
| 308 |
+
if isinstance(node, Constant) and isinstance(node.value, str):
|
| 309 |
+
text = node.value
|
| 310 |
+
else:
|
| 311 |
+
return None
|
| 312 |
+
if clean:
|
| 313 |
+
import inspect
|
| 314 |
+
text = inspect.cleandoc(text)
|
| 315 |
+
return text
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
_line_pattern = None
|
| 319 |
+
def _splitlines_no_ff(source, maxlines=None):
|
| 320 |
+
"""Split a string into lines ignoring form feed and other chars.
|
| 321 |
+
|
| 322 |
+
This mimics how the Python parser splits source code.
|
| 323 |
+
"""
|
| 324 |
+
global _line_pattern
|
| 325 |
+
if _line_pattern is None:
|
| 326 |
+
# lazily computed to speedup import time of `ast`
|
| 327 |
+
import re
|
| 328 |
+
_line_pattern = re.compile(r"(.*?(?:\r\n|\n|\r|$))")
|
| 329 |
+
|
| 330 |
+
lines = []
|
| 331 |
+
for lineno, match in enumerate(_line_pattern.finditer(source), 1):
|
| 332 |
+
if maxlines is not None and lineno > maxlines:
|
| 333 |
+
break
|
| 334 |
+
lines.append(match[0])
|
| 335 |
+
return lines
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def _pad_whitespace(source):
|
| 339 |
+
r"""Replace all chars except '\f\t' in a line with spaces."""
|
| 340 |
+
result = ''
|
| 341 |
+
for c in source:
|
| 342 |
+
if c in '\f\t':
|
| 343 |
+
result += c
|
| 344 |
+
else:
|
| 345 |
+
result += ' '
|
| 346 |
+
return result
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def get_source_segment(source, node, *, padded=False):
|
| 350 |
+
"""Get source code segment of the *source* that generated *node*.
|
| 351 |
+
|
| 352 |
+
If some location information (`lineno`, `end_lineno`, `col_offset`,
|
| 353 |
+
or `end_col_offset`) is missing, return None.
|
| 354 |
+
|
| 355 |
+
If *padded* is `True`, the first line of a multi-line statement will
|
| 356 |
+
be padded with spaces to match its original position.
|
| 357 |
+
"""
|
| 358 |
+
try:
|
| 359 |
+
if node.end_lineno is None or node.end_col_offset is None:
|
| 360 |
+
return None
|
| 361 |
+
lineno = node.lineno - 1
|
| 362 |
+
end_lineno = node.end_lineno - 1
|
| 363 |
+
col_offset = node.col_offset
|
| 364 |
+
end_col_offset = node.end_col_offset
|
| 365 |
+
except AttributeError:
|
| 366 |
+
return None
|
| 367 |
+
|
| 368 |
+
lines = _splitlines_no_ff(source, maxlines=end_lineno+1)
|
| 369 |
+
if end_lineno == lineno:
|
| 370 |
+
return lines[lineno].encode()[col_offset:end_col_offset].decode()
|
| 371 |
+
|
| 372 |
+
if padded:
|
| 373 |
+
padding = _pad_whitespace(lines[lineno].encode()[:col_offset].decode())
|
| 374 |
+
else:
|
| 375 |
+
padding = ''
|
| 376 |
+
|
| 377 |
+
first = padding + lines[lineno].encode()[col_offset:].decode()
|
| 378 |
+
last = lines[end_lineno].encode()[:end_col_offset].decode()
|
| 379 |
+
lines = lines[lineno+1:end_lineno]
|
| 380 |
+
|
| 381 |
+
lines.insert(0, first)
|
| 382 |
+
lines.append(last)
|
| 383 |
+
return ''.join(lines)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def walk(node):
|
| 387 |
+
"""
|
| 388 |
+
Recursively yield all descendant nodes in the tree starting at *node*
|
| 389 |
+
(including *node* itself), in no specified order. This is useful if you
|
| 390 |
+
only want to modify nodes in place and don't care about the context.
|
| 391 |
+
"""
|
| 392 |
+
from collections import deque
|
| 393 |
+
todo = deque([node])
|
| 394 |
+
while todo:
|
| 395 |
+
node = todo.popleft()
|
| 396 |
+
todo.extend(iter_child_nodes(node))
|
| 397 |
+
yield node
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def compare(
|
| 401 |
+
a,
|
| 402 |
+
b,
|
| 403 |
+
/,
|
| 404 |
+
*,
|
| 405 |
+
compare_attributes=False,
|
| 406 |
+
):
|
| 407 |
+
"""Recursively compares two ASTs.
|
| 408 |
+
|
| 409 |
+
compare_attributes affects whether AST attributes are considered
|
| 410 |
+
in the comparison. If compare_attributes is False (default), then
|
| 411 |
+
attributes are ignored. Otherwise they must all be equal. This
|
| 412 |
+
option is useful to check whether the ASTs are structurally equal but
|
| 413 |
+
might differ in whitespace or similar details.
|
| 414 |
+
"""
|
| 415 |
+
|
| 416 |
+
sentinel = object() # handle the possibility of a missing attribute/field
|
| 417 |
+
|
| 418 |
+
def _compare(a, b):
|
| 419 |
+
# Compare two fields on an AST object, which may themselves be
|
| 420 |
+
# AST objects, lists of AST objects, or primitive ASDL types
|
| 421 |
+
# like identifiers and constants.
|
| 422 |
+
if isinstance(a, AST):
|
| 423 |
+
return compare(
|
| 424 |
+
a,
|
| 425 |
+
b,
|
| 426 |
+
compare_attributes=compare_attributes,
|
| 427 |
+
)
|
| 428 |
+
elif isinstance(a, list):
|
| 429 |
+
# If a field is repeated, then both objects will represent
|
| 430 |
+
# the value as a list.
|
| 431 |
+
if len(a) != len(b):
|
| 432 |
+
return False
|
| 433 |
+
for a_item, b_item in zip(a, b):
|
| 434 |
+
if not _compare(a_item, b_item):
|
| 435 |
+
return False
|
| 436 |
+
else:
|
| 437 |
+
return True
|
| 438 |
+
else:
|
| 439 |
+
return type(a) is type(b) and a == b
|
| 440 |
+
|
| 441 |
+
def _compare_fields(a, b):
|
| 442 |
+
if a._fields != b._fields:
|
| 443 |
+
return False
|
| 444 |
+
for field in a._fields:
|
| 445 |
+
a_field = getattr(a, field, sentinel)
|
| 446 |
+
b_field = getattr(b, field, sentinel)
|
| 447 |
+
if a_field is sentinel and b_field is sentinel:
|
| 448 |
+
# both nodes are missing a field at runtime
|
| 449 |
+
continue
|
| 450 |
+
if a_field is sentinel or b_field is sentinel:
|
| 451 |
+
# one of the node is missing a field
|
| 452 |
+
return False
|
| 453 |
+
if not _compare(a_field, b_field):
|
| 454 |
+
return False
|
| 455 |
+
else:
|
| 456 |
+
return True
|
| 457 |
+
|
| 458 |
+
def _compare_attributes(a, b):
|
| 459 |
+
if a._attributes != b._attributes:
|
| 460 |
+
return False
|
| 461 |
+
# Attributes are always ints.
|
| 462 |
+
for attr in a._attributes:
|
| 463 |
+
a_attr = getattr(a, attr, sentinel)
|
| 464 |
+
b_attr = getattr(b, attr, sentinel)
|
| 465 |
+
if a_attr is sentinel and b_attr is sentinel:
|
| 466 |
+
# both nodes are missing an attribute at runtime
|
| 467 |
+
continue
|
| 468 |
+
if a_attr != b_attr:
|
| 469 |
+
return False
|
| 470 |
+
else:
|
| 471 |
+
return True
|
| 472 |
+
|
| 473 |
+
if type(a) is not type(b):
|
| 474 |
+
return False
|
| 475 |
+
if not _compare_fields(a, b):
|
| 476 |
+
return False
|
| 477 |
+
if compare_attributes and not _compare_attributes(a, b):
|
| 478 |
+
return False
|
| 479 |
+
return True
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
class NodeVisitor(object):
|
| 483 |
+
"""
|
| 484 |
+
A node visitor base class that walks the abstract syntax tree and calls a
|
| 485 |
+
visitor function for every node found. This function may return a value
|
| 486 |
+
which is forwarded by the `visit` method.
|
| 487 |
+
|
| 488 |
+
This class is meant to be subclassed, with the subclass adding visitor
|
| 489 |
+
methods.
|
| 490 |
+
|
| 491 |
+
Per default the visitor functions for the nodes are ``'visit_'`` +
|
| 492 |
+
class name of the node. So a `TryFinally` node visit function would
|
| 493 |
+
be `visit_TryFinally`. This behavior can be changed by overriding
|
| 494 |
+
the `visit` method. If no visitor function exists for a node
|
| 495 |
+
(return value `None`) the `generic_visit` visitor is used instead.
|
| 496 |
+
|
| 497 |
+
Don't use the `NodeVisitor` if you want to apply changes to nodes during
|
| 498 |
+
traversing. For this a special visitor exists (`NodeTransformer`) that
|
| 499 |
+
allows modifications.
|
| 500 |
+
"""
|
| 501 |
+
|
| 502 |
+
def visit(self, node):
|
| 503 |
+
"""Visit a node."""
|
| 504 |
+
method = 'visit_' + node.__class__.__name__
|
| 505 |
+
visitor = getattr(self, method, self.generic_visit)
|
| 506 |
+
return visitor(node)
|
| 507 |
+
|
| 508 |
+
def generic_visit(self, node):
|
| 509 |
+
"""Called if no explicit visitor function exists for a node."""
|
| 510 |
+
for field, value in iter_fields(node):
|
| 511 |
+
if isinstance(value, list):
|
| 512 |
+
for item in value:
|
| 513 |
+
if isinstance(item, AST):
|
| 514 |
+
self.visit(item)
|
| 515 |
+
elif isinstance(value, AST):
|
| 516 |
+
self.visit(value)
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
class NodeTransformer(NodeVisitor):
|
| 520 |
+
"""
|
| 521 |
+
A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
|
| 522 |
+
allows modification of nodes.
|
| 523 |
+
|
| 524 |
+
The `NodeTransformer` will walk the AST and use the return value of the
|
| 525 |
+
visitor methods to replace or remove the old node. If the return value of
|
| 526 |
+
the visitor method is ``None``, the node will be removed from its location,
|
| 527 |
+
otherwise it is replaced with the return value. The return value may be the
|
| 528 |
+
original node in which case no replacement takes place.
|
| 529 |
+
|
| 530 |
+
Here is an example transformer that rewrites all occurrences of name lookups
|
| 531 |
+
(``foo``) to ``data['foo']``::
|
| 532 |
+
|
| 533 |
+
class RewriteName(NodeTransformer):
|
| 534 |
+
|
| 535 |
+
def visit_Name(self, node):
|
| 536 |
+
return Subscript(
|
| 537 |
+
value=Name(id='data', ctx=Load()),
|
| 538 |
+
slice=Constant(value=node.id),
|
| 539 |
+
ctx=node.ctx
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
Keep in mind that if the node you're operating on has child nodes you must
|
| 543 |
+
either transform the child nodes yourself or call the :meth:`generic_visit`
|
| 544 |
+
method for the node first.
|
| 545 |
+
|
| 546 |
+
For nodes that were part of a collection of statements (that applies to all
|
| 547 |
+
statement nodes), the visitor may also return a list of nodes rather than
|
| 548 |
+
just a single node.
|
| 549 |
+
|
| 550 |
+
Usually you use the transformer like this::
|
| 551 |
+
|
| 552 |
+
node = YourTransformer().visit(node)
|
| 553 |
+
"""
|
| 554 |
+
|
| 555 |
+
def generic_visit(self, node):
|
| 556 |
+
for field, old_value in iter_fields(node):
|
| 557 |
+
if isinstance(old_value, list):
|
| 558 |
+
new_values = []
|
| 559 |
+
for value in old_value:
|
| 560 |
+
if isinstance(value, AST):
|
| 561 |
+
value = self.visit(value)
|
| 562 |
+
if value is None:
|
| 563 |
+
continue
|
| 564 |
+
elif not isinstance(value, AST):
|
| 565 |
+
new_values.extend(value)
|
| 566 |
+
continue
|
| 567 |
+
new_values.append(value)
|
| 568 |
+
old_value[:] = new_values
|
| 569 |
+
elif isinstance(old_value, AST):
|
| 570 |
+
new_node = self.visit(old_value)
|
| 571 |
+
if new_node is None:
|
| 572 |
+
delattr(node, field)
|
| 573 |
+
else:
|
| 574 |
+
setattr(node, field, new_node)
|
| 575 |
+
return node
|
| 576 |
+
|
| 577 |
+
class slice(AST):
|
| 578 |
+
"""Deprecated AST node class."""
|
| 579 |
+
|
| 580 |
+
class Index(slice):
|
| 581 |
+
"""Deprecated AST node class. Use the index value directly instead."""
|
| 582 |
+
def __new__(cls, value, **kwargs):
|
| 583 |
+
return value
|
| 584 |
+
|
| 585 |
+
class ExtSlice(slice):
|
| 586 |
+
"""Deprecated AST node class. Use ast.Tuple instead."""
|
| 587 |
+
def __new__(cls, dims=(), **kwargs):
|
| 588 |
+
return Tuple(list(dims), Load(), **kwargs)
|
| 589 |
+
|
| 590 |
+
# If the ast module is loaded more than once, only add deprecated methods once
|
| 591 |
+
if not hasattr(Tuple, 'dims'):
|
| 592 |
+
# The following code is for backward compatibility.
|
| 593 |
+
# It will be removed in future.
|
| 594 |
+
|
| 595 |
+
def _dims_getter(self):
|
| 596 |
+
"""Deprecated. Use elts instead."""
|
| 597 |
+
return self.elts
|
| 598 |
+
|
| 599 |
+
def _dims_setter(self, value):
|
| 600 |
+
self.elts = value
|
| 601 |
+
|
| 602 |
+
Tuple.dims = property(_dims_getter, _dims_setter)
|
| 603 |
+
|
| 604 |
+
class Suite(mod):
|
| 605 |
+
"""Deprecated AST node class. Unused in Python 3."""
|
| 606 |
+
|
| 607 |
+
class AugLoad(expr_context):
|
| 608 |
+
"""Deprecated AST node class. Unused in Python 3."""
|
| 609 |
+
|
| 610 |
+
class AugStore(expr_context):
|
| 611 |
+
"""Deprecated AST node class. Unused in Python 3."""
|
| 612 |
+
|
| 613 |
+
class Param(expr_context):
|
| 614 |
+
"""Deprecated AST node class. Unused in Python 3."""
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
def unparse(ast_obj):
|
| 618 |
+
global _Unparser
|
| 619 |
+
try:
|
| 620 |
+
unparser = _Unparser()
|
| 621 |
+
except NameError:
|
| 622 |
+
from _ast_unparse import Unparser as _Unparser
|
| 623 |
+
unparser = _Unparser()
|
| 624 |
+
return unparser.visit(ast_obj)
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def main(args=None):
|
| 628 |
+
import argparse
|
| 629 |
+
import sys
|
| 630 |
+
|
| 631 |
+
parser = argparse.ArgumentParser(color=True)
|
| 632 |
+
parser.add_argument('infile', nargs='?', default='-',
|
| 633 |
+
help='the file to parse; defaults to stdin')
|
| 634 |
+
parser.add_argument('-m', '--mode', default='exec',
|
| 635 |
+
choices=('exec', 'single', 'eval', 'func_type'),
|
| 636 |
+
help='specify what kind of code must be parsed')
|
| 637 |
+
parser.add_argument('--no-type-comments', default=True, action='store_false',
|
| 638 |
+
help="don't add information about type comments")
|
| 639 |
+
parser.add_argument('-a', '--include-attributes', action='store_true',
|
| 640 |
+
help='include attributes such as line numbers and '
|
| 641 |
+
'column offsets')
|
| 642 |
+
parser.add_argument('-i', '--indent', type=int, default=3,
|
| 643 |
+
help='indentation of nodes (number of spaces)')
|
| 644 |
+
parser.add_argument('--feature-version',
|
| 645 |
+
type=str, default=None, metavar='VERSION',
|
| 646 |
+
help='Python version in the format 3.x '
|
| 647 |
+
'(for example, 3.10)')
|
| 648 |
+
parser.add_argument('-O', '--optimize',
|
| 649 |
+
type=int, default=-1, metavar='LEVEL',
|
| 650 |
+
help='optimization level for parser (default -1)')
|
| 651 |
+
parser.add_argument('--show-empty', default=False, action='store_true',
|
| 652 |
+
help='show empty lists and fields in dump output')
|
| 653 |
+
args = parser.parse_args(args)
|
| 654 |
+
|
| 655 |
+
if args.infile == '-':
|
| 656 |
+
name = '<stdin>'
|
| 657 |
+
source = sys.stdin.buffer.read()
|
| 658 |
+
else:
|
| 659 |
+
name = args.infile
|
| 660 |
+
with open(args.infile, 'rb') as infile:
|
| 661 |
+
source = infile.read()
|
| 662 |
+
|
| 663 |
+
# Process feature_version
|
| 664 |
+
feature_version = None
|
| 665 |
+
if args.feature_version:
|
| 666 |
+
try:
|
| 667 |
+
major, minor = map(int, args.feature_version.split('.', 1))
|
| 668 |
+
except ValueError:
|
| 669 |
+
parser.error('Invalid format for --feature-version; '
|
| 670 |
+
'expected format 3.x (for example, 3.10)')
|
| 671 |
+
|
| 672 |
+
feature_version = (major, minor)
|
| 673 |
+
|
| 674 |
+
tree = parse(source, name, args.mode, type_comments=args.no_type_comments,
|
| 675 |
+
feature_version=feature_version, optimize=args.optimize)
|
| 676 |
+
print(dump(tree, include_attributes=args.include_attributes,
|
| 677 |
+
indent=args.indent, show_empty=args.show_empty))
|
| 678 |
+
|
| 679 |
+
if __name__ == '__main__':
|
| 680 |
+
main()
|
micromamba_root/envs/hf_sync/Lib/base64.py
ADDED
|
@@ -0,0 +1,618 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Base16, Base32, Base64 (RFC 3548), Base85 and Ascii85 data encodings"""
|
| 2 |
+
|
| 3 |
+
# Modified 04-Oct-1995 by Jack Jansen to use binascii module
|
| 4 |
+
# Modified 30-Dec-2003 by Barry Warsaw to add full RFC 3548 support
|
| 5 |
+
# Modified 22-May-2007 by Guido van Rossum to use bytes everywhere
|
| 6 |
+
|
| 7 |
+
import struct
|
| 8 |
+
import binascii
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
# Legacy interface exports traditional RFC 2045 Base64 encodings
|
| 13 |
+
'encode', 'decode', 'encodebytes', 'decodebytes',
|
| 14 |
+
# Generalized interface for other encodings
|
| 15 |
+
'b64encode', 'b64decode', 'b32encode', 'b32decode',
|
| 16 |
+
'b32hexencode', 'b32hexdecode', 'b16encode', 'b16decode',
|
| 17 |
+
# Base85 and Ascii85 encodings
|
| 18 |
+
'b85encode', 'b85decode', 'a85encode', 'a85decode', 'z85encode', 'z85decode',
|
| 19 |
+
# Standard Base64 encoding
|
| 20 |
+
'standard_b64encode', 'standard_b64decode',
|
| 21 |
+
# Some common Base64 alternatives. As referenced by RFC 3458, see thread
|
| 22 |
+
# starting at:
|
| 23 |
+
#
|
| 24 |
+
# http://zgp.org/pipermail/p2p-hackers/2001-September/000316.html
|
| 25 |
+
'urlsafe_b64encode', 'urlsafe_b64decode',
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
bytes_types = (bytes, bytearray) # Types acceptable as binary data
|
| 30 |
+
|
| 31 |
+
def _bytes_from_decode_data(s):
|
| 32 |
+
if isinstance(s, str):
|
| 33 |
+
try:
|
| 34 |
+
return s.encode('ascii')
|
| 35 |
+
except UnicodeEncodeError:
|
| 36 |
+
raise ValueError('string argument should contain only ASCII characters')
|
| 37 |
+
if isinstance(s, bytes_types):
|
| 38 |
+
return s
|
| 39 |
+
try:
|
| 40 |
+
return memoryview(s).tobytes()
|
| 41 |
+
except TypeError:
|
| 42 |
+
raise TypeError("argument should be a bytes-like object or ASCII "
|
| 43 |
+
"string, not %r" % s.__class__.__name__) from None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# Base64 encoding/decoding uses binascii
|
| 47 |
+
|
| 48 |
+
def b64encode(s, altchars=None):
|
| 49 |
+
"""Encode the bytes-like object s using Base64 and return a bytes object.
|
| 50 |
+
|
| 51 |
+
Optional altchars should be a byte string of length 2 which specifies an
|
| 52 |
+
alternative alphabet for the '+' and '/' characters. This allows an
|
| 53 |
+
application to e.g. generate url or filesystem safe Base64 strings.
|
| 54 |
+
"""
|
| 55 |
+
encoded = binascii.b2a_base64(s, newline=False)
|
| 56 |
+
if altchars is not None:
|
| 57 |
+
assert len(altchars) == 2, repr(altchars)
|
| 58 |
+
return encoded.translate(bytes.maketrans(b'+/', altchars))
|
| 59 |
+
return encoded
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def b64decode(s, altchars=None, validate=False):
|
| 63 |
+
"""Decode the Base64 encoded bytes-like object or ASCII string s.
|
| 64 |
+
|
| 65 |
+
Optional altchars must be a bytes-like object or ASCII string of length 2
|
| 66 |
+
which specifies the alternative alphabet used instead of the '+' and '/'
|
| 67 |
+
characters.
|
| 68 |
+
|
| 69 |
+
The result is returned as a bytes object. A binascii.Error is raised if
|
| 70 |
+
s is incorrectly padded.
|
| 71 |
+
|
| 72 |
+
If validate is False (the default), characters that are neither in the
|
| 73 |
+
normal base-64 alphabet nor the alternative alphabet are discarded prior
|
| 74 |
+
to the padding check. If validate is True, these non-alphabet characters
|
| 75 |
+
in the input result in a binascii.Error.
|
| 76 |
+
For more information about the strict base64 check, see:
|
| 77 |
+
|
| 78 |
+
https://docs.python.org/3.11/library/binascii.html#binascii.a2b_base64
|
| 79 |
+
"""
|
| 80 |
+
s = _bytes_from_decode_data(s)
|
| 81 |
+
if altchars is not None:
|
| 82 |
+
altchars = _bytes_from_decode_data(altchars)
|
| 83 |
+
assert len(altchars) == 2, repr(altchars)
|
| 84 |
+
s = s.translate(bytes.maketrans(altchars, b'+/'))
|
| 85 |
+
return binascii.a2b_base64(s, strict_mode=validate)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def standard_b64encode(s):
|
| 89 |
+
"""Encode bytes-like object s using the standard Base64 alphabet.
|
| 90 |
+
|
| 91 |
+
The result is returned as a bytes object.
|
| 92 |
+
"""
|
| 93 |
+
return b64encode(s)
|
| 94 |
+
|
| 95 |
+
def standard_b64decode(s):
|
| 96 |
+
"""Decode bytes encoded with the standard Base64 alphabet.
|
| 97 |
+
|
| 98 |
+
Argument s is a bytes-like object or ASCII string to decode. The result
|
| 99 |
+
is returned as a bytes object. A binascii.Error is raised if the input
|
| 100 |
+
is incorrectly padded. Characters that are not in the standard alphabet
|
| 101 |
+
are discarded prior to the padding check.
|
| 102 |
+
"""
|
| 103 |
+
return b64decode(s)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
_urlsafe_encode_translation = bytes.maketrans(b'+/', b'-_')
|
| 107 |
+
_urlsafe_decode_translation = bytes.maketrans(b'-_', b'+/')
|
| 108 |
+
|
| 109 |
+
def urlsafe_b64encode(s):
|
| 110 |
+
"""Encode bytes using the URL- and filesystem-safe Base64 alphabet.
|
| 111 |
+
|
| 112 |
+
Argument s is a bytes-like object to encode. The result is returned as a
|
| 113 |
+
bytes object. The alphabet uses '-' instead of '+' and '_' instead of
|
| 114 |
+
'/'.
|
| 115 |
+
"""
|
| 116 |
+
return b64encode(s).translate(_urlsafe_encode_translation)
|
| 117 |
+
|
| 118 |
+
def urlsafe_b64decode(s):
|
| 119 |
+
"""Decode bytes using the URL- and filesystem-safe Base64 alphabet.
|
| 120 |
+
|
| 121 |
+
Argument s is a bytes-like object or ASCII string to decode. The result
|
| 122 |
+
is returned as a bytes object. A binascii.Error is raised if the input
|
| 123 |
+
is incorrectly padded. Characters that are not in the URL-safe base-64
|
| 124 |
+
alphabet, and are not a plus '+' or slash '/', are discarded prior to the
|
| 125 |
+
padding check.
|
| 126 |
+
|
| 127 |
+
The alphabet uses '-' instead of '+' and '_' instead of '/'.
|
| 128 |
+
"""
|
| 129 |
+
s = _bytes_from_decode_data(s)
|
| 130 |
+
s = s.translate(_urlsafe_decode_translation)
|
| 131 |
+
return b64decode(s)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# Base32 encoding/decoding must be done in Python
|
| 136 |
+
_B32_ENCODE_DOCSTRING = '''
|
| 137 |
+
Encode the bytes-like objects using {encoding} and return a bytes object.
|
| 138 |
+
'''
|
| 139 |
+
_B32_DECODE_DOCSTRING = '''
|
| 140 |
+
Decode the {encoding} encoded bytes-like object or ASCII string s.
|
| 141 |
+
|
| 142 |
+
Optional casefold is a flag specifying whether a lowercase alphabet is
|
| 143 |
+
acceptable as input. For security purposes, the default is False.
|
| 144 |
+
{extra_args}
|
| 145 |
+
The result is returned as a bytes object. A binascii.Error is raised if
|
| 146 |
+
the input is incorrectly padded or if there are non-alphabet
|
| 147 |
+
characters present in the input.
|
| 148 |
+
'''
|
| 149 |
+
_B32_DECODE_MAP01_DOCSTRING = '''
|
| 150 |
+
RFC 3548 allows for optional mapping of the digit 0 (zero) to the
|
| 151 |
+
letter O (oh), and for optional mapping of the digit 1 (one) to
|
| 152 |
+
either the letter I (eye) or letter L (el). The optional argument
|
| 153 |
+
map01 when not None, specifies which letter the digit 1 should be
|
| 154 |
+
mapped to (when map01 is not None, the digit 0 is always mapped to
|
| 155 |
+
the letter O). For security purposes the default is None, so that
|
| 156 |
+
0 and 1 are not allowed in the input.
|
| 157 |
+
'''
|
| 158 |
+
_b32alphabet = b'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
|
| 159 |
+
_b32hexalphabet = b'0123456789ABCDEFGHIJKLMNOPQRSTUV'
|
| 160 |
+
_b32tab2 = {}
|
| 161 |
+
_b32rev = {}
|
| 162 |
+
|
| 163 |
+
def _b32encode(alphabet, s):
|
| 164 |
+
# Delay the initialization of the table to not waste memory
|
| 165 |
+
# if the function is never called
|
| 166 |
+
if alphabet not in _b32tab2:
|
| 167 |
+
b32tab = [bytes((i,)) for i in alphabet]
|
| 168 |
+
_b32tab2[alphabet] = [a + b for a in b32tab for b in b32tab]
|
| 169 |
+
b32tab = None
|
| 170 |
+
|
| 171 |
+
if not isinstance(s, bytes_types):
|
| 172 |
+
s = memoryview(s).tobytes()
|
| 173 |
+
leftover = len(s) % 5
|
| 174 |
+
# Pad the last quantum with zero bits if necessary
|
| 175 |
+
if leftover:
|
| 176 |
+
s = s + b'\0' * (5 - leftover) # Don't use += !
|
| 177 |
+
encoded = bytearray()
|
| 178 |
+
from_bytes = int.from_bytes
|
| 179 |
+
b32tab2 = _b32tab2[alphabet]
|
| 180 |
+
for i in range(0, len(s), 5):
|
| 181 |
+
c = from_bytes(s[i: i + 5]) # big endian
|
| 182 |
+
encoded += (b32tab2[c >> 30] + # bits 1 - 10
|
| 183 |
+
b32tab2[(c >> 20) & 0x3ff] + # bits 11 - 20
|
| 184 |
+
b32tab2[(c >> 10) & 0x3ff] + # bits 21 - 30
|
| 185 |
+
b32tab2[c & 0x3ff] # bits 31 - 40
|
| 186 |
+
)
|
| 187 |
+
# Adjust for any leftover partial quanta
|
| 188 |
+
if leftover == 1:
|
| 189 |
+
encoded[-6:] = b'======'
|
| 190 |
+
elif leftover == 2:
|
| 191 |
+
encoded[-4:] = b'===='
|
| 192 |
+
elif leftover == 3:
|
| 193 |
+
encoded[-3:] = b'==='
|
| 194 |
+
elif leftover == 4:
|
| 195 |
+
encoded[-1:] = b'='
|
| 196 |
+
return bytes(encoded)
|
| 197 |
+
|
| 198 |
+
def _b32decode(alphabet, s, casefold=False, map01=None):
|
| 199 |
+
# Delay the initialization of the table to not waste memory
|
| 200 |
+
# if the function is never called
|
| 201 |
+
if alphabet not in _b32rev:
|
| 202 |
+
_b32rev[alphabet] = {v: k for k, v in enumerate(alphabet)}
|
| 203 |
+
s = _bytes_from_decode_data(s)
|
| 204 |
+
if len(s) % 8:
|
| 205 |
+
raise binascii.Error('Incorrect padding')
|
| 206 |
+
# Handle section 2.4 zero and one mapping. The flag map01 will be either
|
| 207 |
+
# False, or the character to map the digit 1 (one) to. It should be
|
| 208 |
+
# either L (el) or I (eye).
|
| 209 |
+
if map01 is not None:
|
| 210 |
+
map01 = _bytes_from_decode_data(map01)
|
| 211 |
+
assert len(map01) == 1, repr(map01)
|
| 212 |
+
s = s.translate(bytes.maketrans(b'01', b'O' + map01))
|
| 213 |
+
if casefold:
|
| 214 |
+
s = s.upper()
|
| 215 |
+
# Strip off pad characters from the right. We need to count the pad
|
| 216 |
+
# characters because this will tell us how many null bytes to remove from
|
| 217 |
+
# the end of the decoded string.
|
| 218 |
+
l = len(s)
|
| 219 |
+
s = s.rstrip(b'=')
|
| 220 |
+
padchars = l - len(s)
|
| 221 |
+
# Now decode the full quanta
|
| 222 |
+
decoded = bytearray()
|
| 223 |
+
b32rev = _b32rev[alphabet]
|
| 224 |
+
for i in range(0, len(s), 8):
|
| 225 |
+
quanta = s[i: i + 8]
|
| 226 |
+
acc = 0
|
| 227 |
+
try:
|
| 228 |
+
for c in quanta:
|
| 229 |
+
acc = (acc << 5) + b32rev[c]
|
| 230 |
+
except KeyError:
|
| 231 |
+
raise binascii.Error('Non-base32 digit found') from None
|
| 232 |
+
decoded += acc.to_bytes(5) # big endian
|
| 233 |
+
# Process the last, partial quanta
|
| 234 |
+
if l % 8 or padchars not in {0, 1, 3, 4, 6}:
|
| 235 |
+
raise binascii.Error('Incorrect padding')
|
| 236 |
+
if padchars and decoded:
|
| 237 |
+
acc <<= 5 * padchars
|
| 238 |
+
last = acc.to_bytes(5) # big endian
|
| 239 |
+
leftover = (43 - 5 * padchars) // 8 # 1: 4, 3: 3, 4: 2, 6: 1
|
| 240 |
+
decoded[-5:] = last[:leftover]
|
| 241 |
+
return bytes(decoded)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def b32encode(s):
|
| 245 |
+
return _b32encode(_b32alphabet, s)
|
| 246 |
+
b32encode.__doc__ = _B32_ENCODE_DOCSTRING.format(encoding='base32')
|
| 247 |
+
|
| 248 |
+
def b32decode(s, casefold=False, map01=None):
|
| 249 |
+
return _b32decode(_b32alphabet, s, casefold, map01)
|
| 250 |
+
b32decode.__doc__ = _B32_DECODE_DOCSTRING.format(encoding='base32',
|
| 251 |
+
extra_args=_B32_DECODE_MAP01_DOCSTRING)
|
| 252 |
+
|
| 253 |
+
def b32hexencode(s):
|
| 254 |
+
return _b32encode(_b32hexalphabet, s)
|
| 255 |
+
b32hexencode.__doc__ = _B32_ENCODE_DOCSTRING.format(encoding='base32hex')
|
| 256 |
+
|
| 257 |
+
def b32hexdecode(s, casefold=False):
|
| 258 |
+
# base32hex does not have the 01 mapping
|
| 259 |
+
return _b32decode(_b32hexalphabet, s, casefold)
|
| 260 |
+
b32hexdecode.__doc__ = _B32_DECODE_DOCSTRING.format(encoding='base32hex',
|
| 261 |
+
extra_args='')
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
# RFC 3548, Base 16 Alphabet specifies uppercase, but hexlify() returns
|
| 265 |
+
# lowercase. The RFC also recommends against accepting input case
|
| 266 |
+
# insensitively.
|
| 267 |
+
def b16encode(s):
|
| 268 |
+
"""Encode the bytes-like object s using Base16 and return a bytes object.
|
| 269 |
+
"""
|
| 270 |
+
return binascii.hexlify(s).upper()
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def b16decode(s, casefold=False):
|
| 274 |
+
"""Decode the Base16 encoded bytes-like object or ASCII string s.
|
| 275 |
+
|
| 276 |
+
Optional casefold is a flag specifying whether a lowercase alphabet is
|
| 277 |
+
acceptable as input. For security purposes, the default is False.
|
| 278 |
+
|
| 279 |
+
The result is returned as a bytes object. A binascii.Error is raised if
|
| 280 |
+
s is incorrectly padded or if there are non-alphabet characters present
|
| 281 |
+
in the input.
|
| 282 |
+
"""
|
| 283 |
+
s = _bytes_from_decode_data(s)
|
| 284 |
+
if casefold:
|
| 285 |
+
s = s.upper()
|
| 286 |
+
if s.translate(None, delete=b'0123456789ABCDEF'):
|
| 287 |
+
raise binascii.Error('Non-base16 digit found')
|
| 288 |
+
return binascii.unhexlify(s)
|
| 289 |
+
|
| 290 |
+
#
|
| 291 |
+
# Ascii85 encoding/decoding
|
| 292 |
+
#
|
| 293 |
+
|
| 294 |
+
_a85chars = None
|
| 295 |
+
_a85chars2 = None
|
| 296 |
+
_A85START = b"<~"
|
| 297 |
+
_A85END = b"~>"
|
| 298 |
+
|
| 299 |
+
def _85encode(b, chars, chars2, pad=False, foldnuls=False, foldspaces=False):
|
| 300 |
+
# Helper function for a85encode and b85encode
|
| 301 |
+
if not isinstance(b, bytes_types):
|
| 302 |
+
b = memoryview(b).tobytes()
|
| 303 |
+
|
| 304 |
+
padding = (-len(b)) % 4
|
| 305 |
+
if padding:
|
| 306 |
+
b = b + b'\0' * padding
|
| 307 |
+
words = struct.Struct('!%dI' % (len(b) // 4)).unpack(b)
|
| 308 |
+
|
| 309 |
+
chunks = [b'z' if foldnuls and not word else
|
| 310 |
+
b'y' if foldspaces and word == 0x20202020 else
|
| 311 |
+
(chars2[word // 614125] +
|
| 312 |
+
chars2[word // 85 % 7225] +
|
| 313 |
+
chars[word % 85])
|
| 314 |
+
for word in words]
|
| 315 |
+
|
| 316 |
+
if padding and not pad:
|
| 317 |
+
if chunks[-1] == b'z':
|
| 318 |
+
chunks[-1] = chars[0] * 5
|
| 319 |
+
chunks[-1] = chunks[-1][:-padding]
|
| 320 |
+
|
| 321 |
+
return b''.join(chunks)
|
| 322 |
+
|
| 323 |
+
def a85encode(b, *, foldspaces=False, wrapcol=0, pad=False, adobe=False):
|
| 324 |
+
"""Encode bytes-like object b using Ascii85 and return a bytes object.
|
| 325 |
+
|
| 326 |
+
foldspaces is an optional flag that uses the special short sequence 'y'
|
| 327 |
+
instead of 4 consecutive spaces (ASCII 0x20) as supported by 'btoa'. This
|
| 328 |
+
feature is not supported by the "standard" Adobe encoding.
|
| 329 |
+
|
| 330 |
+
wrapcol controls whether the output should have newline (b'\\n') characters
|
| 331 |
+
added to it. If this is non-zero, each output line will be at most this
|
| 332 |
+
many characters long, excluding the trailing newline.
|
| 333 |
+
|
| 334 |
+
pad controls whether the input is padded to a multiple of 4 before
|
| 335 |
+
encoding. Note that the btoa implementation always pads.
|
| 336 |
+
|
| 337 |
+
adobe controls whether the encoded byte sequence is framed with <~ and ~>,
|
| 338 |
+
which is used by the Adobe implementation.
|
| 339 |
+
"""
|
| 340 |
+
global _a85chars, _a85chars2
|
| 341 |
+
# Delay the initialization of tables to not waste memory
|
| 342 |
+
# if the function is never called
|
| 343 |
+
if _a85chars2 is None:
|
| 344 |
+
_a85chars = [bytes((i,)) for i in range(33, 118)]
|
| 345 |
+
_a85chars2 = [(a + b) for a in _a85chars for b in _a85chars]
|
| 346 |
+
|
| 347 |
+
result = _85encode(b, _a85chars, _a85chars2, pad, True, foldspaces)
|
| 348 |
+
|
| 349 |
+
if adobe:
|
| 350 |
+
result = _A85START + result
|
| 351 |
+
if wrapcol:
|
| 352 |
+
wrapcol = max(2 if adobe else 1, wrapcol)
|
| 353 |
+
chunks = [result[i: i + wrapcol]
|
| 354 |
+
for i in range(0, len(result), wrapcol)]
|
| 355 |
+
if adobe:
|
| 356 |
+
if len(chunks[-1]) + 2 > wrapcol:
|
| 357 |
+
chunks.append(b'')
|
| 358 |
+
result = b'\n'.join(chunks)
|
| 359 |
+
if adobe:
|
| 360 |
+
result += _A85END
|
| 361 |
+
|
| 362 |
+
return result
|
| 363 |
+
|
| 364 |
+
def a85decode(b, *, foldspaces=False, adobe=False, ignorechars=b' \t\n\r\v'):
|
| 365 |
+
"""Decode the Ascii85 encoded bytes-like object or ASCII string b.
|
| 366 |
+
|
| 367 |
+
foldspaces is a flag that specifies whether the 'y' short sequence should be
|
| 368 |
+
accepted as shorthand for 4 consecutive spaces (ASCII 0x20). This feature is
|
| 369 |
+
not supported by the "standard" Adobe encoding.
|
| 370 |
+
|
| 371 |
+
adobe controls whether the input sequence is in Adobe Ascii85 format (i.e.
|
| 372 |
+
is framed with <~ and ~>).
|
| 373 |
+
|
| 374 |
+
ignorechars should be a byte string containing characters to ignore from the
|
| 375 |
+
input. This should only contain whitespace characters, and by default
|
| 376 |
+
contains all whitespace characters in ASCII.
|
| 377 |
+
|
| 378 |
+
The result is returned as a bytes object.
|
| 379 |
+
"""
|
| 380 |
+
b = _bytes_from_decode_data(b)
|
| 381 |
+
if adobe:
|
| 382 |
+
if not b.endswith(_A85END):
|
| 383 |
+
raise ValueError(
|
| 384 |
+
"Ascii85 encoded byte sequences must end "
|
| 385 |
+
"with {!r}".format(_A85END)
|
| 386 |
+
)
|
| 387 |
+
if b.startswith(_A85START):
|
| 388 |
+
b = b[2:-2] # Strip off start/end markers
|
| 389 |
+
else:
|
| 390 |
+
b = b[:-2]
|
| 391 |
+
#
|
| 392 |
+
# We have to go through this stepwise, so as to ignore spaces and handle
|
| 393 |
+
# special short sequences
|
| 394 |
+
#
|
| 395 |
+
packI = struct.Struct('!I').pack
|
| 396 |
+
decoded = []
|
| 397 |
+
decoded_append = decoded.append
|
| 398 |
+
curr = []
|
| 399 |
+
curr_append = curr.append
|
| 400 |
+
curr_clear = curr.clear
|
| 401 |
+
for x in b + b'u' * 4:
|
| 402 |
+
if b'!'[0] <= x <= b'u'[0]:
|
| 403 |
+
curr_append(x)
|
| 404 |
+
if len(curr) == 5:
|
| 405 |
+
acc = 0
|
| 406 |
+
for x in curr:
|
| 407 |
+
acc = 85 * acc + (x - 33)
|
| 408 |
+
try:
|
| 409 |
+
decoded_append(packI(acc))
|
| 410 |
+
except struct.error:
|
| 411 |
+
raise ValueError('Ascii85 overflow') from None
|
| 412 |
+
curr_clear()
|
| 413 |
+
elif x == b'z'[0]:
|
| 414 |
+
if curr:
|
| 415 |
+
raise ValueError('z inside Ascii85 5-tuple')
|
| 416 |
+
decoded_append(b'\0\0\0\0')
|
| 417 |
+
elif foldspaces and x == b'y'[0]:
|
| 418 |
+
if curr:
|
| 419 |
+
raise ValueError('y inside Ascii85 5-tuple')
|
| 420 |
+
decoded_append(b'\x20\x20\x20\x20')
|
| 421 |
+
elif x in ignorechars:
|
| 422 |
+
# Skip whitespace
|
| 423 |
+
continue
|
| 424 |
+
else:
|
| 425 |
+
raise ValueError('Non-Ascii85 digit found: %c' % x)
|
| 426 |
+
|
| 427 |
+
result = b''.join(decoded)
|
| 428 |
+
padding = 4 - len(curr)
|
| 429 |
+
if padding:
|
| 430 |
+
# Throw away the extra padding
|
| 431 |
+
result = result[:-padding]
|
| 432 |
+
return result
|
| 433 |
+
|
| 434 |
+
# The following code is originally taken (with permission) from Mercurial
|
| 435 |
+
|
| 436 |
+
_b85alphabet = (b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
| 437 |
+
b"abcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~")
|
| 438 |
+
_b85chars = None
|
| 439 |
+
_b85chars2 = None
|
| 440 |
+
_b85dec = None
|
| 441 |
+
|
| 442 |
+
def b85encode(b, pad=False):
|
| 443 |
+
"""Encode bytes-like object b in base85 format and return a bytes object.
|
| 444 |
+
|
| 445 |
+
If pad is true, the input is padded with b'\\0' so its length is a multiple of
|
| 446 |
+
4 bytes before encoding.
|
| 447 |
+
"""
|
| 448 |
+
global _b85chars, _b85chars2
|
| 449 |
+
# Delay the initialization of tables to not waste memory
|
| 450 |
+
# if the function is never called
|
| 451 |
+
if _b85chars2 is None:
|
| 452 |
+
_b85chars = [bytes((i,)) for i in _b85alphabet]
|
| 453 |
+
_b85chars2 = [(a + b) for a in _b85chars for b in _b85chars]
|
| 454 |
+
return _85encode(b, _b85chars, _b85chars2, pad)
|
| 455 |
+
|
| 456 |
+
def b85decode(b):
|
| 457 |
+
"""Decode the base85-encoded bytes-like object or ASCII string b
|
| 458 |
+
|
| 459 |
+
The result is returned as a bytes object.
|
| 460 |
+
"""
|
| 461 |
+
global _b85dec
|
| 462 |
+
# Delay the initialization of tables to not waste memory
|
| 463 |
+
# if the function is never called
|
| 464 |
+
if _b85dec is None:
|
| 465 |
+
# we don't assign to _b85dec directly to avoid issues when
|
| 466 |
+
# multiple threads call this function simultaneously
|
| 467 |
+
b85dec_tmp = [None] * 256
|
| 468 |
+
for i, c in enumerate(_b85alphabet):
|
| 469 |
+
b85dec_tmp[c] = i
|
| 470 |
+
_b85dec = b85dec_tmp
|
| 471 |
+
|
| 472 |
+
b = _bytes_from_decode_data(b)
|
| 473 |
+
padding = (-len(b)) % 5
|
| 474 |
+
b = b + b'~' * padding
|
| 475 |
+
out = []
|
| 476 |
+
packI = struct.Struct('!I').pack
|
| 477 |
+
for i in range(0, len(b), 5):
|
| 478 |
+
chunk = b[i:i + 5]
|
| 479 |
+
acc = 0
|
| 480 |
+
try:
|
| 481 |
+
for c in chunk:
|
| 482 |
+
acc = acc * 85 + _b85dec[c]
|
| 483 |
+
except TypeError:
|
| 484 |
+
for j, c in enumerate(chunk):
|
| 485 |
+
if _b85dec[c] is None:
|
| 486 |
+
raise ValueError('bad base85 character at position %d'
|
| 487 |
+
% (i + j)) from None
|
| 488 |
+
raise
|
| 489 |
+
try:
|
| 490 |
+
out.append(packI(acc))
|
| 491 |
+
except struct.error:
|
| 492 |
+
raise ValueError('base85 overflow in hunk starting at byte %d'
|
| 493 |
+
% i) from None
|
| 494 |
+
|
| 495 |
+
result = b''.join(out)
|
| 496 |
+
if padding:
|
| 497 |
+
result = result[:-padding]
|
| 498 |
+
return result
|
| 499 |
+
|
| 500 |
+
_z85alphabet = (b'0123456789abcdefghijklmnopqrstuvwxyz'
|
| 501 |
+
b'ABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#')
|
| 502 |
+
# Translating b85 valid but z85 invalid chars to b'\x00' is required
|
| 503 |
+
# to prevent them from being decoded as b85 valid chars.
|
| 504 |
+
_z85_b85_decode_diff = b';_`|~'
|
| 505 |
+
_z85_decode_translation = bytes.maketrans(
|
| 506 |
+
_z85alphabet + _z85_b85_decode_diff,
|
| 507 |
+
_b85alphabet + b'\x00' * len(_z85_b85_decode_diff)
|
| 508 |
+
)
|
| 509 |
+
_z85_encode_translation = bytes.maketrans(_b85alphabet, _z85alphabet)
|
| 510 |
+
|
| 511 |
+
def z85encode(s):
|
| 512 |
+
"""Encode bytes-like object b in z85 format and return a bytes object."""
|
| 513 |
+
return b85encode(s).translate(_z85_encode_translation)
|
| 514 |
+
|
| 515 |
+
def z85decode(s):
|
| 516 |
+
"""Decode the z85-encoded bytes-like object or ASCII string b
|
| 517 |
+
|
| 518 |
+
The result is returned as a bytes object.
|
| 519 |
+
"""
|
| 520 |
+
s = _bytes_from_decode_data(s)
|
| 521 |
+
s = s.translate(_z85_decode_translation)
|
| 522 |
+
try:
|
| 523 |
+
return b85decode(s)
|
| 524 |
+
except ValueError as e:
|
| 525 |
+
raise ValueError(e.args[0].replace('base85', 'z85')) from None
|
| 526 |
+
|
| 527 |
+
# Legacy interface. This code could be cleaned up since I don't believe
|
| 528 |
+
# binascii has any line length limitations. It just doesn't seem worth it
|
| 529 |
+
# though. The files should be opened in binary mode.
|
| 530 |
+
|
| 531 |
+
MAXLINESIZE = 76 # Excluding the CRLF
|
| 532 |
+
MAXBINSIZE = (MAXLINESIZE//4)*3
|
| 533 |
+
|
| 534 |
+
def encode(input, output):
|
| 535 |
+
"""Encode a file; input and output are binary files."""
|
| 536 |
+
while s := input.read(MAXBINSIZE):
|
| 537 |
+
while len(s) < MAXBINSIZE and (ns := input.read(MAXBINSIZE-len(s))):
|
| 538 |
+
s += ns
|
| 539 |
+
line = binascii.b2a_base64(s)
|
| 540 |
+
output.write(line)
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def decode(input, output):
|
| 544 |
+
"""Decode a file; input and output are binary files."""
|
| 545 |
+
while line := input.readline():
|
| 546 |
+
s = binascii.a2b_base64(line)
|
| 547 |
+
output.write(s)
|
| 548 |
+
|
| 549 |
+
def _input_type_check(s):
|
| 550 |
+
try:
|
| 551 |
+
m = memoryview(s)
|
| 552 |
+
except TypeError as err:
|
| 553 |
+
msg = "expected bytes-like object, not %s" % s.__class__.__name__
|
| 554 |
+
raise TypeError(msg) from err
|
| 555 |
+
if m.format not in ('c', 'b', 'B'):
|
| 556 |
+
msg = ("expected single byte elements, not %r from %s" %
|
| 557 |
+
(m.format, s.__class__.__name__))
|
| 558 |
+
raise TypeError(msg)
|
| 559 |
+
if m.ndim != 1:
|
| 560 |
+
msg = ("expected 1-D data, not %d-D data from %s" %
|
| 561 |
+
(m.ndim, s.__class__.__name__))
|
| 562 |
+
raise TypeError(msg)
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def encodebytes(s):
|
| 566 |
+
"""Encode a bytestring into a bytes object containing multiple lines
|
| 567 |
+
of base-64 data."""
|
| 568 |
+
_input_type_check(s)
|
| 569 |
+
pieces = []
|
| 570 |
+
for i in range(0, len(s), MAXBINSIZE):
|
| 571 |
+
chunk = s[i : i + MAXBINSIZE]
|
| 572 |
+
pieces.append(binascii.b2a_base64(chunk))
|
| 573 |
+
return b"".join(pieces)
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def decodebytes(s):
|
| 577 |
+
"""Decode a bytestring of base-64 data into a bytes object."""
|
| 578 |
+
_input_type_check(s)
|
| 579 |
+
return binascii.a2b_base64(s)
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
# Usable as a script...
|
| 583 |
+
def main():
|
| 584 |
+
"""Small main program"""
|
| 585 |
+
import sys, getopt
|
| 586 |
+
usage = f"""usage: {sys.argv[0]} [-h|-d|-e|-u] [file|-]
|
| 587 |
+
-h: print this help message and exit
|
| 588 |
+
-d, -u: decode
|
| 589 |
+
-e: encode (default)"""
|
| 590 |
+
try:
|
| 591 |
+
opts, args = getopt.getopt(sys.argv[1:], 'hdeu')
|
| 592 |
+
except getopt.error as msg:
|
| 593 |
+
sys.stdout = sys.stderr
|
| 594 |
+
print(msg)
|
| 595 |
+
print(usage)
|
| 596 |
+
sys.exit(2)
|
| 597 |
+
func = encode
|
| 598 |
+
for o, a in opts:
|
| 599 |
+
if o == '-e': func = encode
|
| 600 |
+
if o == '-d': func = decode
|
| 601 |
+
if o == '-u': func = decode
|
| 602 |
+
if o == '-h': print(usage); return
|
| 603 |
+
if args and args[0] != '-':
|
| 604 |
+
with open(args[0], 'rb') as f:
|
| 605 |
+
func(f, sys.stdout.buffer)
|
| 606 |
+
else:
|
| 607 |
+
if sys.stdin.isatty():
|
| 608 |
+
# gh-138775: read terminal input data all at once to detect EOF
|
| 609 |
+
import io
|
| 610 |
+
data = sys.stdin.buffer.read()
|
| 611 |
+
buffer = io.BytesIO(data)
|
| 612 |
+
else:
|
| 613 |
+
buffer = sys.stdin.buffer
|
| 614 |
+
func(buffer, sys.stdout.buffer)
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
if __name__ == '__main__':
|
| 618 |
+
main()
|
micromamba_root/envs/hf_sync/Lib/bdb.py
ADDED
|
@@ -0,0 +1,1206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Debugger basics"""
|
| 2 |
+
|
| 3 |
+
import fnmatch
|
| 4 |
+
import sys
|
| 5 |
+
import threading
|
| 6 |
+
import os
|
| 7 |
+
import weakref
|
| 8 |
+
from contextlib import contextmanager
|
| 9 |
+
from inspect import CO_GENERATOR, CO_COROUTINE, CO_ASYNC_GENERATOR
|
| 10 |
+
|
| 11 |
+
__all__ = ["BdbQuit", "Bdb", "Breakpoint"]
|
| 12 |
+
|
| 13 |
+
GENERATOR_AND_COROUTINE_FLAGS = CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class BdbQuit(Exception):
|
| 17 |
+
"""Exception to give up completely."""
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
E = sys.monitoring.events
|
| 21 |
+
|
| 22 |
+
class _MonitoringTracer:
|
| 23 |
+
EVENT_CALLBACK_MAP = {
|
| 24 |
+
E.PY_START: 'call',
|
| 25 |
+
E.PY_RESUME: 'call',
|
| 26 |
+
E.PY_THROW: 'call',
|
| 27 |
+
E.LINE: 'line',
|
| 28 |
+
E.JUMP: 'jump',
|
| 29 |
+
E.PY_RETURN: 'return',
|
| 30 |
+
E.PY_YIELD: 'return',
|
| 31 |
+
E.PY_UNWIND: 'unwind',
|
| 32 |
+
E.RAISE: 'exception',
|
| 33 |
+
E.STOP_ITERATION: 'exception',
|
| 34 |
+
E.INSTRUCTION: 'opcode',
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
GLOBAL_EVENTS = E.PY_START | E.PY_RESUME | E.PY_THROW | E.PY_UNWIND | E.RAISE
|
| 38 |
+
LOCAL_EVENTS = E.LINE | E.JUMP | E.PY_RETURN | E.PY_YIELD | E.STOP_ITERATION
|
| 39 |
+
|
| 40 |
+
def __init__(self):
|
| 41 |
+
self._tool_id = sys.monitoring.DEBUGGER_ID
|
| 42 |
+
self._name = 'bdbtracer'
|
| 43 |
+
self._tracefunc = None
|
| 44 |
+
self._disable_current_event = False
|
| 45 |
+
self._tracing_thread = None
|
| 46 |
+
self._enabled = False
|
| 47 |
+
|
| 48 |
+
def start_trace(self, tracefunc):
|
| 49 |
+
self._tracefunc = tracefunc
|
| 50 |
+
self._tracing_thread = threading.current_thread()
|
| 51 |
+
curr_tool = sys.monitoring.get_tool(self._tool_id)
|
| 52 |
+
if curr_tool is None:
|
| 53 |
+
sys.monitoring.use_tool_id(self._tool_id, self._name)
|
| 54 |
+
elif curr_tool == self._name:
|
| 55 |
+
sys.monitoring.clear_tool_id(self._tool_id)
|
| 56 |
+
else:
|
| 57 |
+
raise ValueError('Another debugger is using the monitoring tool')
|
| 58 |
+
E = sys.monitoring.events
|
| 59 |
+
all_events = 0
|
| 60 |
+
for event, cb_name in self.EVENT_CALLBACK_MAP.items():
|
| 61 |
+
callback = self.callback_wrapper(getattr(self, f'{cb_name}_callback'), event)
|
| 62 |
+
sys.monitoring.register_callback(self._tool_id, event, callback)
|
| 63 |
+
if event != E.INSTRUCTION:
|
| 64 |
+
all_events |= event
|
| 65 |
+
self.update_local_events()
|
| 66 |
+
sys.monitoring.set_events(self._tool_id, self.GLOBAL_EVENTS)
|
| 67 |
+
self._enabled = True
|
| 68 |
+
|
| 69 |
+
def stop_trace(self):
|
| 70 |
+
self._enabled = False
|
| 71 |
+
self._tracing_thread = None
|
| 72 |
+
curr_tool = sys.monitoring.get_tool(self._tool_id)
|
| 73 |
+
if curr_tool != self._name:
|
| 74 |
+
return
|
| 75 |
+
sys.monitoring.clear_tool_id(self._tool_id)
|
| 76 |
+
sys.monitoring.free_tool_id(self._tool_id)
|
| 77 |
+
|
| 78 |
+
def disable_current_event(self):
|
| 79 |
+
self._disable_current_event = True
|
| 80 |
+
|
| 81 |
+
def restart_events(self):
|
| 82 |
+
if sys.monitoring.get_tool(self._tool_id) == self._name:
|
| 83 |
+
sys.monitoring.restart_events()
|
| 84 |
+
|
| 85 |
+
def callback_wrapper(self, func, event):
|
| 86 |
+
import functools
|
| 87 |
+
|
| 88 |
+
@functools.wraps(func)
|
| 89 |
+
def wrapper(*args):
|
| 90 |
+
if self._tracing_thread != threading.current_thread():
|
| 91 |
+
return
|
| 92 |
+
try:
|
| 93 |
+
frame = sys._getframe().f_back
|
| 94 |
+
ret = func(frame, *args)
|
| 95 |
+
if self._enabled and frame.f_trace:
|
| 96 |
+
self.update_local_events()
|
| 97 |
+
if (
|
| 98 |
+
self._disable_current_event
|
| 99 |
+
and event not in (E.PY_THROW, E.PY_UNWIND, E.RAISE)
|
| 100 |
+
):
|
| 101 |
+
return sys.monitoring.DISABLE
|
| 102 |
+
else:
|
| 103 |
+
return ret
|
| 104 |
+
except BaseException:
|
| 105 |
+
self.stop_trace()
|
| 106 |
+
sys._getframe().f_back.f_trace = None
|
| 107 |
+
raise
|
| 108 |
+
finally:
|
| 109 |
+
self._disable_current_event = False
|
| 110 |
+
|
| 111 |
+
return wrapper
|
| 112 |
+
|
| 113 |
+
def call_callback(self, frame, code, *args):
|
| 114 |
+
local_tracefunc = self._tracefunc(frame, 'call', None)
|
| 115 |
+
if local_tracefunc is not None:
|
| 116 |
+
frame.f_trace = local_tracefunc
|
| 117 |
+
if self._enabled:
|
| 118 |
+
sys.monitoring.set_local_events(self._tool_id, code, self.LOCAL_EVENTS)
|
| 119 |
+
|
| 120 |
+
def return_callback(self, frame, code, offset, retval):
|
| 121 |
+
if frame.f_trace:
|
| 122 |
+
frame.f_trace(frame, 'return', retval)
|
| 123 |
+
|
| 124 |
+
def unwind_callback(self, frame, code, *args):
|
| 125 |
+
if frame.f_trace:
|
| 126 |
+
frame.f_trace(frame, 'return', None)
|
| 127 |
+
|
| 128 |
+
def line_callback(self, frame, code, *args):
|
| 129 |
+
if frame.f_trace and frame.f_trace_lines:
|
| 130 |
+
frame.f_trace(frame, 'line', None)
|
| 131 |
+
|
| 132 |
+
def jump_callback(self, frame, code, inst_offset, dest_offset):
|
| 133 |
+
if dest_offset > inst_offset:
|
| 134 |
+
return sys.monitoring.DISABLE
|
| 135 |
+
inst_lineno = self._get_lineno(code, inst_offset)
|
| 136 |
+
dest_lineno = self._get_lineno(code, dest_offset)
|
| 137 |
+
if inst_lineno != dest_lineno:
|
| 138 |
+
return sys.monitoring.DISABLE
|
| 139 |
+
if frame.f_trace and frame.f_trace_lines:
|
| 140 |
+
frame.f_trace(frame, 'line', None)
|
| 141 |
+
|
| 142 |
+
def exception_callback(self, frame, code, offset, exc):
|
| 143 |
+
if frame.f_trace:
|
| 144 |
+
if exc.__traceback__ and hasattr(exc.__traceback__, 'tb_frame'):
|
| 145 |
+
tb = exc.__traceback__
|
| 146 |
+
while tb:
|
| 147 |
+
if tb.tb_frame.f_locals.get('self') is self:
|
| 148 |
+
return
|
| 149 |
+
tb = tb.tb_next
|
| 150 |
+
frame.f_trace(frame, 'exception', (type(exc), exc, exc.__traceback__))
|
| 151 |
+
|
| 152 |
+
def opcode_callback(self, frame, code, offset):
|
| 153 |
+
if frame.f_trace and frame.f_trace_opcodes:
|
| 154 |
+
frame.f_trace(frame, 'opcode', None)
|
| 155 |
+
|
| 156 |
+
def update_local_events(self, frame=None):
|
| 157 |
+
if sys.monitoring.get_tool(self._tool_id) != self._name:
|
| 158 |
+
return
|
| 159 |
+
if frame is None:
|
| 160 |
+
frame = sys._getframe().f_back
|
| 161 |
+
while frame is not None:
|
| 162 |
+
if frame.f_trace is not None:
|
| 163 |
+
if frame.f_trace_opcodes:
|
| 164 |
+
events = self.LOCAL_EVENTS | E.INSTRUCTION
|
| 165 |
+
else:
|
| 166 |
+
events = self.LOCAL_EVENTS
|
| 167 |
+
sys.monitoring.set_local_events(self._tool_id, frame.f_code, events)
|
| 168 |
+
frame = frame.f_back
|
| 169 |
+
|
| 170 |
+
def _get_lineno(self, code, offset):
|
| 171 |
+
import dis
|
| 172 |
+
last_lineno = None
|
| 173 |
+
for start, lineno in dis.findlinestarts(code):
|
| 174 |
+
if offset < start:
|
| 175 |
+
return last_lineno
|
| 176 |
+
last_lineno = lineno
|
| 177 |
+
return last_lineno
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class Bdb:
|
| 181 |
+
"""Generic Python debugger base class.
|
| 182 |
+
|
| 183 |
+
This class takes care of details of the trace facility;
|
| 184 |
+
a derived class should implement user interaction.
|
| 185 |
+
The standard debugger class (pdb.Pdb) is an example.
|
| 186 |
+
|
| 187 |
+
The optional skip argument must be an iterable of glob-style
|
| 188 |
+
module name patterns. The debugger will not step into frames
|
| 189 |
+
that originate in a module that matches one of these patterns.
|
| 190 |
+
Whether a frame is considered to originate in a certain module
|
| 191 |
+
is determined by the __name__ in the frame globals.
|
| 192 |
+
"""
|
| 193 |
+
|
| 194 |
+
def __init__(self, skip=None, backend='settrace'):
|
| 195 |
+
self.skip = set(skip) if skip else None
|
| 196 |
+
self.breaks = {}
|
| 197 |
+
self.fncache = {}
|
| 198 |
+
self.frame_trace_lines_opcodes = {}
|
| 199 |
+
self.frame_returning = None
|
| 200 |
+
self.trace_opcodes = False
|
| 201 |
+
self.enterframe = None
|
| 202 |
+
self.cmdframe = None
|
| 203 |
+
self.cmdlineno = None
|
| 204 |
+
self.code_linenos = weakref.WeakKeyDictionary()
|
| 205 |
+
self.backend = backend
|
| 206 |
+
if backend == 'monitoring':
|
| 207 |
+
self.monitoring_tracer = _MonitoringTracer()
|
| 208 |
+
elif backend == 'settrace':
|
| 209 |
+
self.monitoring_tracer = None
|
| 210 |
+
else:
|
| 211 |
+
raise ValueError(f"Invalid backend '{backend}'")
|
| 212 |
+
|
| 213 |
+
self._load_breaks()
|
| 214 |
+
|
| 215 |
+
def canonic(self, filename):
|
| 216 |
+
"""Return canonical form of filename.
|
| 217 |
+
|
| 218 |
+
For real filenames, the canonical form is a case-normalized (on
|
| 219 |
+
case insensitive filesystems) absolute path. 'Filenames' with
|
| 220 |
+
angle brackets, such as "<stdin>", generated in interactive
|
| 221 |
+
mode, are returned unchanged.
|
| 222 |
+
"""
|
| 223 |
+
if filename == "<" + filename[1:-1] + ">":
|
| 224 |
+
return filename
|
| 225 |
+
canonic = self.fncache.get(filename)
|
| 226 |
+
if not canonic:
|
| 227 |
+
canonic = os.path.abspath(filename)
|
| 228 |
+
canonic = os.path.normcase(canonic)
|
| 229 |
+
self.fncache[filename] = canonic
|
| 230 |
+
return canonic
|
| 231 |
+
|
| 232 |
+
def start_trace(self):
|
| 233 |
+
if self.monitoring_tracer:
|
| 234 |
+
self.monitoring_tracer.start_trace(self.trace_dispatch)
|
| 235 |
+
else:
|
| 236 |
+
sys.settrace(self.trace_dispatch)
|
| 237 |
+
|
| 238 |
+
def stop_trace(self):
|
| 239 |
+
if self.monitoring_tracer:
|
| 240 |
+
self.monitoring_tracer.stop_trace()
|
| 241 |
+
else:
|
| 242 |
+
sys.settrace(None)
|
| 243 |
+
|
| 244 |
+
def reset(self):
|
| 245 |
+
"""Set values of attributes as ready to start debugging."""
|
| 246 |
+
import linecache
|
| 247 |
+
linecache.checkcache()
|
| 248 |
+
self.botframe = None
|
| 249 |
+
self._set_stopinfo(None, None)
|
| 250 |
+
|
| 251 |
+
@contextmanager
|
| 252 |
+
def set_enterframe(self, frame):
|
| 253 |
+
self.enterframe = frame
|
| 254 |
+
yield
|
| 255 |
+
self.enterframe = None
|
| 256 |
+
|
| 257 |
+
def trace_dispatch(self, frame, event, arg):
|
| 258 |
+
"""Dispatch a trace function for debugged frames based on the event.
|
| 259 |
+
|
| 260 |
+
This function is installed as the trace function for debugged
|
| 261 |
+
frames. Its return value is the new trace function, which is
|
| 262 |
+
usually itself. The default implementation decides how to
|
| 263 |
+
dispatch a frame, depending on the type of event (passed in as a
|
| 264 |
+
string) that is about to be executed.
|
| 265 |
+
|
| 266 |
+
The event can be one of the following:
|
| 267 |
+
line: A new line of code is going to be executed.
|
| 268 |
+
call: A function is about to be called or another code block
|
| 269 |
+
is entered.
|
| 270 |
+
return: A function or other code block is about to return.
|
| 271 |
+
exception: An exception has occurred.
|
| 272 |
+
c_call: A C function is about to be called.
|
| 273 |
+
c_return: A C function has returned.
|
| 274 |
+
c_exception: A C function has raised an exception.
|
| 275 |
+
|
| 276 |
+
For the Python events, specialized functions (see the dispatch_*()
|
| 277 |
+
methods) are called. For the C events, no action is taken.
|
| 278 |
+
|
| 279 |
+
The arg parameter depends on the previous event.
|
| 280 |
+
"""
|
| 281 |
+
|
| 282 |
+
with self.set_enterframe(frame):
|
| 283 |
+
if self.quitting:
|
| 284 |
+
return # None
|
| 285 |
+
if event == 'line':
|
| 286 |
+
return self.dispatch_line(frame)
|
| 287 |
+
if event == 'call':
|
| 288 |
+
return self.dispatch_call(frame, arg)
|
| 289 |
+
if event == 'return':
|
| 290 |
+
return self.dispatch_return(frame, arg)
|
| 291 |
+
if event == 'exception':
|
| 292 |
+
return self.dispatch_exception(frame, arg)
|
| 293 |
+
if event == 'c_call':
|
| 294 |
+
return self.trace_dispatch
|
| 295 |
+
if event == 'c_exception':
|
| 296 |
+
return self.trace_dispatch
|
| 297 |
+
if event == 'c_return':
|
| 298 |
+
return self.trace_dispatch
|
| 299 |
+
if event == 'opcode':
|
| 300 |
+
return self.dispatch_opcode(frame, arg)
|
| 301 |
+
print('bdb.Bdb.dispatch: unknown debugging event:', repr(event))
|
| 302 |
+
return self.trace_dispatch
|
| 303 |
+
|
| 304 |
+
def dispatch_line(self, frame):
|
| 305 |
+
"""Invoke user function and return trace function for line event.
|
| 306 |
+
|
| 307 |
+
If the debugger stops on the current line, invoke
|
| 308 |
+
self.user_line(). Raise BdbQuit if self.quitting is set.
|
| 309 |
+
Return self.trace_dispatch to continue tracing in this scope.
|
| 310 |
+
"""
|
| 311 |
+
# GH-136057
|
| 312 |
+
# For line events, we don't want to stop at the same line where
|
| 313 |
+
# the latest next/step command was issued.
|
| 314 |
+
if (self.stop_here(frame) or self.break_here(frame)) and not (
|
| 315 |
+
self.cmdframe == frame and self.cmdlineno == frame.f_lineno
|
| 316 |
+
):
|
| 317 |
+
self.user_line(frame)
|
| 318 |
+
self.restart_events()
|
| 319 |
+
if self.quitting: raise BdbQuit
|
| 320 |
+
elif not self.get_break(frame.f_code.co_filename, frame.f_lineno):
|
| 321 |
+
self.disable_current_event()
|
| 322 |
+
return self.trace_dispatch
|
| 323 |
+
|
| 324 |
+
def dispatch_call(self, frame, arg):
|
| 325 |
+
"""Invoke user function and return trace function for call event.
|
| 326 |
+
|
| 327 |
+
If the debugger stops on this function call, invoke
|
| 328 |
+
self.user_call(). Raise BdbQuit if self.quitting is set.
|
| 329 |
+
Return self.trace_dispatch to continue tracing in this scope.
|
| 330 |
+
"""
|
| 331 |
+
# XXX 'arg' is no longer used
|
| 332 |
+
if self.botframe is None:
|
| 333 |
+
# First call of dispatch since reset()
|
| 334 |
+
self.botframe = frame.f_back # (CT) Note that this may also be None!
|
| 335 |
+
return self.trace_dispatch
|
| 336 |
+
if not (self.stop_here(frame) or self.break_anywhere(frame)):
|
| 337 |
+
# We already know there's no breakpoint in this function
|
| 338 |
+
# If it's a next/until/return command, we don't need any CALL event
|
| 339 |
+
# and we don't need to set the f_trace on any new frame.
|
| 340 |
+
# If it's a step command, it must either hit stop_here, or skip the
|
| 341 |
+
# whole module. Either way, we don't need the CALL event here.
|
| 342 |
+
self.disable_current_event()
|
| 343 |
+
return # None
|
| 344 |
+
# Ignore call events in generator except when stepping.
|
| 345 |
+
if self.stopframe and frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS:
|
| 346 |
+
return self.trace_dispatch
|
| 347 |
+
self.user_call(frame, arg)
|
| 348 |
+
self.restart_events()
|
| 349 |
+
if self.quitting: raise BdbQuit
|
| 350 |
+
return self.trace_dispatch
|
| 351 |
+
|
| 352 |
+
def dispatch_return(self, frame, arg):
|
| 353 |
+
"""Invoke user function and return trace function for return event.
|
| 354 |
+
|
| 355 |
+
If the debugger stops on this function return, invoke
|
| 356 |
+
self.user_return(). Raise BdbQuit if self.quitting is set.
|
| 357 |
+
Return self.trace_dispatch to continue tracing in this scope.
|
| 358 |
+
"""
|
| 359 |
+
if self.stop_here(frame) or frame == self.returnframe:
|
| 360 |
+
# Ignore return events in generator except when stepping.
|
| 361 |
+
if self.stopframe and frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS:
|
| 362 |
+
# It's possible to trigger a StopIteration exception in
|
| 363 |
+
# the caller so we must set the trace function in the caller
|
| 364 |
+
self._set_caller_tracefunc(frame)
|
| 365 |
+
return self.trace_dispatch
|
| 366 |
+
try:
|
| 367 |
+
self.frame_returning = frame
|
| 368 |
+
self.user_return(frame, arg)
|
| 369 |
+
self.restart_events()
|
| 370 |
+
finally:
|
| 371 |
+
self.frame_returning = None
|
| 372 |
+
if self.quitting: raise BdbQuit
|
| 373 |
+
# The user issued a 'next' or 'until' command.
|
| 374 |
+
if self.stopframe is frame and self.stoplineno != -1:
|
| 375 |
+
self._set_stopinfo(None, None)
|
| 376 |
+
# The previous frame might not have f_trace set, unless we are
|
| 377 |
+
# issuing a command that does not expect to stop, we should set
|
| 378 |
+
# f_trace
|
| 379 |
+
if self.stoplineno != -1:
|
| 380 |
+
self._set_caller_tracefunc(frame)
|
| 381 |
+
return self.trace_dispatch
|
| 382 |
+
|
| 383 |
+
def dispatch_exception(self, frame, arg):
|
| 384 |
+
"""Invoke user function and return trace function for exception event.
|
| 385 |
+
|
| 386 |
+
If the debugger stops on this exception, invoke
|
| 387 |
+
self.user_exception(). Raise BdbQuit if self.quitting is set.
|
| 388 |
+
Return self.trace_dispatch to continue tracing in this scope.
|
| 389 |
+
"""
|
| 390 |
+
if self.stop_here(frame):
|
| 391 |
+
# When stepping with next/until/return in a generator frame, skip
|
| 392 |
+
# the internal StopIteration exception (with no traceback)
|
| 393 |
+
# triggered by a subiterator run with the 'yield from' statement.
|
| 394 |
+
if not (frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS
|
| 395 |
+
and arg[0] is StopIteration and arg[2] is None):
|
| 396 |
+
self.user_exception(frame, arg)
|
| 397 |
+
self.restart_events()
|
| 398 |
+
if self.quitting: raise BdbQuit
|
| 399 |
+
# Stop at the StopIteration or GeneratorExit exception when the user
|
| 400 |
+
# has set stopframe in a generator by issuing a return command, or a
|
| 401 |
+
# next/until command at the last statement in the generator before the
|
| 402 |
+
# exception.
|
| 403 |
+
elif (self.stopframe and frame is not self.stopframe
|
| 404 |
+
and self.stopframe.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS
|
| 405 |
+
and arg[0] in (StopIteration, GeneratorExit)):
|
| 406 |
+
self.user_exception(frame, arg)
|
| 407 |
+
self.restart_events()
|
| 408 |
+
if self.quitting: raise BdbQuit
|
| 409 |
+
|
| 410 |
+
return self.trace_dispatch
|
| 411 |
+
|
| 412 |
+
def dispatch_opcode(self, frame, arg):
|
| 413 |
+
"""Invoke user function and return trace function for opcode event.
|
| 414 |
+
If the debugger stops on the current opcode, invoke
|
| 415 |
+
self.user_opcode(). Raise BdbQuit if self.quitting is set.
|
| 416 |
+
Return self.trace_dispatch to continue tracing in this scope.
|
| 417 |
+
|
| 418 |
+
Opcode event will always trigger the user callback. For now the only
|
| 419 |
+
opcode event is from an inline set_trace() and we want to stop there
|
| 420 |
+
unconditionally.
|
| 421 |
+
"""
|
| 422 |
+
self.user_opcode(frame)
|
| 423 |
+
self.restart_events()
|
| 424 |
+
if self.quitting: raise BdbQuit
|
| 425 |
+
return self.trace_dispatch
|
| 426 |
+
|
| 427 |
+
# Normally derived classes don't override the following
|
| 428 |
+
# methods, but they may if they want to redefine the
|
| 429 |
+
# definition of stopping and breakpoints.
|
| 430 |
+
|
| 431 |
+
def is_skipped_module(self, module_name):
|
| 432 |
+
"Return True if module_name matches any skip pattern."
|
| 433 |
+
if module_name is None: # some modules do not have names
|
| 434 |
+
return False
|
| 435 |
+
for pattern in self.skip:
|
| 436 |
+
if fnmatch.fnmatch(module_name, pattern):
|
| 437 |
+
return True
|
| 438 |
+
return False
|
| 439 |
+
|
| 440 |
+
def stop_here(self, frame):
|
| 441 |
+
"Return True if frame is below the starting frame in the stack."
|
| 442 |
+
# (CT) stopframe may now also be None, see dispatch_call.
|
| 443 |
+
# (CT) the former test for None is therefore removed from here.
|
| 444 |
+
if self.skip and \
|
| 445 |
+
self.is_skipped_module(frame.f_globals.get('__name__')):
|
| 446 |
+
return False
|
| 447 |
+
if frame is self.stopframe:
|
| 448 |
+
if self.stoplineno == -1:
|
| 449 |
+
return False
|
| 450 |
+
return frame.f_lineno >= self.stoplineno
|
| 451 |
+
if not self.stopframe:
|
| 452 |
+
return True
|
| 453 |
+
return False
|
| 454 |
+
|
| 455 |
+
def break_here(self, frame):
|
| 456 |
+
"""Return True if there is an effective breakpoint for this line.
|
| 457 |
+
|
| 458 |
+
Check for line or function breakpoint and if in effect.
|
| 459 |
+
Delete temporary breakpoints if effective() says to.
|
| 460 |
+
"""
|
| 461 |
+
filename = self.canonic(frame.f_code.co_filename)
|
| 462 |
+
if filename not in self.breaks:
|
| 463 |
+
return False
|
| 464 |
+
lineno = frame.f_lineno
|
| 465 |
+
if lineno not in self.breaks[filename]:
|
| 466 |
+
# The line itself has no breakpoint, but maybe the line is the
|
| 467 |
+
# first line of a function with breakpoint set by function name.
|
| 468 |
+
lineno = frame.f_code.co_firstlineno
|
| 469 |
+
if lineno not in self.breaks[filename]:
|
| 470 |
+
return False
|
| 471 |
+
|
| 472 |
+
# flag says ok to delete temp. bp
|
| 473 |
+
(bp, flag) = effective(filename, lineno, frame)
|
| 474 |
+
if bp:
|
| 475 |
+
self.currentbp = bp.number
|
| 476 |
+
if (flag and bp.temporary):
|
| 477 |
+
self.do_clear(str(bp.number))
|
| 478 |
+
return True
|
| 479 |
+
else:
|
| 480 |
+
return False
|
| 481 |
+
|
| 482 |
+
def do_clear(self, arg):
|
| 483 |
+
"""Remove temporary breakpoint.
|
| 484 |
+
|
| 485 |
+
Must implement in derived classes or get NotImplementedError.
|
| 486 |
+
"""
|
| 487 |
+
raise NotImplementedError("subclass of bdb must implement do_clear()")
|
| 488 |
+
|
| 489 |
+
def break_anywhere(self, frame):
|
| 490 |
+
"""Return True if there is any breakpoint in that frame
|
| 491 |
+
"""
|
| 492 |
+
filename = self.canonic(frame.f_code.co_filename)
|
| 493 |
+
if filename not in self.breaks:
|
| 494 |
+
return False
|
| 495 |
+
for lineno in self.breaks[filename]:
|
| 496 |
+
if self._lineno_in_frame(lineno, frame):
|
| 497 |
+
return True
|
| 498 |
+
return False
|
| 499 |
+
|
| 500 |
+
def _lineno_in_frame(self, lineno, frame):
|
| 501 |
+
"""Return True if the line number is in the frame's code object.
|
| 502 |
+
"""
|
| 503 |
+
code = frame.f_code
|
| 504 |
+
if lineno < code.co_firstlineno:
|
| 505 |
+
return False
|
| 506 |
+
if code not in self.code_linenos:
|
| 507 |
+
self.code_linenos[code] = set(lineno for _, _, lineno in code.co_lines())
|
| 508 |
+
return lineno in self.code_linenos[code]
|
| 509 |
+
|
| 510 |
+
# Derived classes should override the user_* methods
|
| 511 |
+
# to gain control.
|
| 512 |
+
|
| 513 |
+
def user_call(self, frame, argument_list):
|
| 514 |
+
"""Called if we might stop in a function."""
|
| 515 |
+
pass
|
| 516 |
+
|
| 517 |
+
def user_line(self, frame):
|
| 518 |
+
"""Called when we stop or break at a line."""
|
| 519 |
+
pass
|
| 520 |
+
|
| 521 |
+
def user_return(self, frame, return_value):
|
| 522 |
+
"""Called when a return trap is set here."""
|
| 523 |
+
pass
|
| 524 |
+
|
| 525 |
+
def user_exception(self, frame, exc_info):
|
| 526 |
+
"""Called when we stop on an exception."""
|
| 527 |
+
pass
|
| 528 |
+
|
| 529 |
+
def user_opcode(self, frame):
|
| 530 |
+
"""Called when we are about to execute an opcode."""
|
| 531 |
+
pass
|
| 532 |
+
|
| 533 |
+
def _set_trace_opcodes(self, trace_opcodes):
|
| 534 |
+
if trace_opcodes != self.trace_opcodes:
|
| 535 |
+
self.trace_opcodes = trace_opcodes
|
| 536 |
+
frame = self.enterframe
|
| 537 |
+
while frame is not None:
|
| 538 |
+
frame.f_trace_opcodes = trace_opcodes
|
| 539 |
+
if frame is self.botframe:
|
| 540 |
+
break
|
| 541 |
+
frame = frame.f_back
|
| 542 |
+
if self.monitoring_tracer:
|
| 543 |
+
self.monitoring_tracer.update_local_events()
|
| 544 |
+
|
| 545 |
+
def _set_stopinfo(self, stopframe, returnframe, stoplineno=0, opcode=False,
|
| 546 |
+
cmdframe=None, cmdlineno=None):
|
| 547 |
+
"""Set the attributes for stopping.
|
| 548 |
+
|
| 549 |
+
If stoplineno is greater than or equal to 0, then stop at line
|
| 550 |
+
greater than or equal to the stopline. If stoplineno is -1, then
|
| 551 |
+
don't stop at all.
|
| 552 |
+
"""
|
| 553 |
+
self.stopframe = stopframe
|
| 554 |
+
self.returnframe = returnframe
|
| 555 |
+
self.quitting = False
|
| 556 |
+
# stoplineno >= 0 means: stop at line >= the stoplineno
|
| 557 |
+
# stoplineno -1 means: don't stop at all
|
| 558 |
+
self.stoplineno = stoplineno
|
| 559 |
+
# cmdframe/cmdlineno is the frame/line number when the user issued
|
| 560 |
+
# step/next commands.
|
| 561 |
+
self.cmdframe = cmdframe
|
| 562 |
+
self.cmdlineno = cmdlineno
|
| 563 |
+
self._set_trace_opcodes(opcode)
|
| 564 |
+
|
| 565 |
+
def _set_caller_tracefunc(self, current_frame):
|
| 566 |
+
# Issue #13183: pdb skips frames after hitting a breakpoint and running
|
| 567 |
+
# step commands.
|
| 568 |
+
# Restore the trace function in the caller (that may not have been set
|
| 569 |
+
# for performance reasons) when returning from the current frame, unless
|
| 570 |
+
# the caller is the botframe.
|
| 571 |
+
caller_frame = current_frame.f_back
|
| 572 |
+
if caller_frame and not caller_frame.f_trace and caller_frame is not self.botframe:
|
| 573 |
+
caller_frame.f_trace = self.trace_dispatch
|
| 574 |
+
|
| 575 |
+
# Derived classes and clients can call the following methods
|
| 576 |
+
# to affect the stepping state.
|
| 577 |
+
|
| 578 |
+
def set_until(self, frame, lineno=None):
|
| 579 |
+
"""Stop when the line with the lineno greater than the current one is
|
| 580 |
+
reached or when returning from current frame."""
|
| 581 |
+
# the name "until" is borrowed from gdb
|
| 582 |
+
if lineno is None:
|
| 583 |
+
lineno = frame.f_lineno + 1
|
| 584 |
+
self._set_stopinfo(frame, frame, lineno)
|
| 585 |
+
|
| 586 |
+
def set_step(self):
|
| 587 |
+
"""Stop after one line of code."""
|
| 588 |
+
# set_step() could be called from signal handler so enterframe might be None
|
| 589 |
+
self._set_stopinfo(None, None, cmdframe=self.enterframe,
|
| 590 |
+
cmdlineno=getattr(self.enterframe, 'f_lineno', None))
|
| 591 |
+
|
| 592 |
+
def set_stepinstr(self):
|
| 593 |
+
"""Stop before the next instruction."""
|
| 594 |
+
self._set_stopinfo(None, None, opcode=True)
|
| 595 |
+
|
| 596 |
+
def set_next(self, frame):
|
| 597 |
+
"""Stop on the next line in or below the given frame."""
|
| 598 |
+
self._set_stopinfo(frame, None, cmdframe=frame, cmdlineno=frame.f_lineno)
|
| 599 |
+
|
| 600 |
+
def set_return(self, frame):
|
| 601 |
+
"""Stop when returning from the given frame."""
|
| 602 |
+
if frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS:
|
| 603 |
+
self._set_stopinfo(frame, frame, -1)
|
| 604 |
+
else:
|
| 605 |
+
self._set_stopinfo(frame.f_back, frame)
|
| 606 |
+
|
| 607 |
+
def set_trace(self, frame=None):
|
| 608 |
+
"""Start debugging from frame.
|
| 609 |
+
|
| 610 |
+
If frame is not specified, debugging starts from caller's frame.
|
| 611 |
+
"""
|
| 612 |
+
self.stop_trace()
|
| 613 |
+
if frame is None:
|
| 614 |
+
frame = sys._getframe().f_back
|
| 615 |
+
self.reset()
|
| 616 |
+
with self.set_enterframe(frame):
|
| 617 |
+
while frame:
|
| 618 |
+
frame.f_trace = self.trace_dispatch
|
| 619 |
+
self.botframe = frame
|
| 620 |
+
self.frame_trace_lines_opcodes[frame] = (frame.f_trace_lines, frame.f_trace_opcodes)
|
| 621 |
+
# We need f_trace_lines == True for the debugger to work
|
| 622 |
+
frame.f_trace_lines = True
|
| 623 |
+
frame = frame.f_back
|
| 624 |
+
self.set_stepinstr()
|
| 625 |
+
self.enterframe = None
|
| 626 |
+
self.start_trace()
|
| 627 |
+
|
| 628 |
+
def set_continue(self):
|
| 629 |
+
"""Stop only at breakpoints or when finished.
|
| 630 |
+
|
| 631 |
+
If there are no breakpoints, set the system trace function to None.
|
| 632 |
+
"""
|
| 633 |
+
# Don't stop except at breakpoints or when finished
|
| 634 |
+
self._set_stopinfo(self.botframe, None, -1)
|
| 635 |
+
if not self.breaks:
|
| 636 |
+
# no breakpoints; run without debugger overhead
|
| 637 |
+
self.stop_trace()
|
| 638 |
+
frame = sys._getframe().f_back
|
| 639 |
+
while frame and frame is not self.botframe:
|
| 640 |
+
del frame.f_trace
|
| 641 |
+
frame = frame.f_back
|
| 642 |
+
for frame, (trace_lines, trace_opcodes) in self.frame_trace_lines_opcodes.items():
|
| 643 |
+
frame.f_trace_lines, frame.f_trace_opcodes = trace_lines, trace_opcodes
|
| 644 |
+
if self.backend == 'monitoring':
|
| 645 |
+
self.monitoring_tracer.update_local_events()
|
| 646 |
+
self.frame_trace_lines_opcodes = {}
|
| 647 |
+
|
| 648 |
+
def set_quit(self):
|
| 649 |
+
"""Set quitting attribute to True.
|
| 650 |
+
|
| 651 |
+
Raises BdbQuit exception in the next call to a dispatch_*() method.
|
| 652 |
+
"""
|
| 653 |
+
self.stopframe = self.botframe
|
| 654 |
+
self.returnframe = None
|
| 655 |
+
self.quitting = True
|
| 656 |
+
self.stop_trace()
|
| 657 |
+
|
| 658 |
+
# Derived classes and clients can call the following methods
|
| 659 |
+
# to manipulate breakpoints. These methods return an
|
| 660 |
+
# error message if something went wrong, None if all is well.
|
| 661 |
+
# Set_break prints out the breakpoint line and file:lineno.
|
| 662 |
+
# Call self.get_*break*() to see the breakpoints or better
|
| 663 |
+
# for bp in Breakpoint.bpbynumber: if bp: bp.bpprint().
|
| 664 |
+
|
| 665 |
+
def _add_to_breaks(self, filename, lineno):
|
| 666 |
+
"""Add breakpoint to breaks, if not already there."""
|
| 667 |
+
bp_linenos = self.breaks.setdefault(filename, [])
|
| 668 |
+
if lineno not in bp_linenos:
|
| 669 |
+
bp_linenos.append(lineno)
|
| 670 |
+
|
| 671 |
+
def set_break(self, filename, lineno, temporary=False, cond=None,
|
| 672 |
+
funcname=None):
|
| 673 |
+
"""Set a new breakpoint for filename:lineno.
|
| 674 |
+
|
| 675 |
+
If lineno doesn't exist for the filename, return an error message.
|
| 676 |
+
The filename should be in canonical form.
|
| 677 |
+
"""
|
| 678 |
+
filename = self.canonic(filename)
|
| 679 |
+
import linecache # Import as late as possible
|
| 680 |
+
line = linecache.getline(filename, lineno)
|
| 681 |
+
if not line:
|
| 682 |
+
return 'Line %s:%d does not exist' % (filename, lineno)
|
| 683 |
+
self._add_to_breaks(filename, lineno)
|
| 684 |
+
bp = Breakpoint(filename, lineno, temporary, cond, funcname)
|
| 685 |
+
# After we set a new breakpoint, we need to search through all frames
|
| 686 |
+
# and set f_trace to trace_dispatch if there could be a breakpoint in
|
| 687 |
+
# that frame.
|
| 688 |
+
frame = self.enterframe
|
| 689 |
+
while frame:
|
| 690 |
+
if self.break_anywhere(frame):
|
| 691 |
+
frame.f_trace = self.trace_dispatch
|
| 692 |
+
frame = frame.f_back
|
| 693 |
+
return None
|
| 694 |
+
|
| 695 |
+
def _load_breaks(self):
|
| 696 |
+
"""Apply all breakpoints (set in other instances) to this one.
|
| 697 |
+
|
| 698 |
+
Populates this instance's breaks list from the Breakpoint class's
|
| 699 |
+
list, which can have breakpoints set by another Bdb instance. This
|
| 700 |
+
is necessary for interactive sessions to keep the breakpoints
|
| 701 |
+
active across multiple calls to run().
|
| 702 |
+
"""
|
| 703 |
+
for (filename, lineno) in Breakpoint.bplist.keys():
|
| 704 |
+
self._add_to_breaks(filename, lineno)
|
| 705 |
+
|
| 706 |
+
def _prune_breaks(self, filename, lineno):
|
| 707 |
+
"""Prune breakpoints for filename:lineno.
|
| 708 |
+
|
| 709 |
+
A list of breakpoints is maintained in the Bdb instance and in
|
| 710 |
+
the Breakpoint class. If a breakpoint in the Bdb instance no
|
| 711 |
+
longer exists in the Breakpoint class, then it's removed from the
|
| 712 |
+
Bdb instance.
|
| 713 |
+
"""
|
| 714 |
+
if (filename, lineno) not in Breakpoint.bplist:
|
| 715 |
+
self.breaks[filename].remove(lineno)
|
| 716 |
+
if not self.breaks[filename]:
|
| 717 |
+
del self.breaks[filename]
|
| 718 |
+
|
| 719 |
+
def clear_break(self, filename, lineno):
|
| 720 |
+
"""Delete breakpoints for filename:lineno.
|
| 721 |
+
|
| 722 |
+
If no breakpoints were set, return an error message.
|
| 723 |
+
"""
|
| 724 |
+
filename = self.canonic(filename)
|
| 725 |
+
if filename not in self.breaks:
|
| 726 |
+
return 'There are no breakpoints in %s' % filename
|
| 727 |
+
if lineno not in self.breaks[filename]:
|
| 728 |
+
return 'There is no breakpoint at %s:%d' % (filename, lineno)
|
| 729 |
+
# If there's only one bp in the list for that file,line
|
| 730 |
+
# pair, then remove the breaks entry
|
| 731 |
+
for bp in Breakpoint.bplist[filename, lineno][:]:
|
| 732 |
+
bp.deleteMe()
|
| 733 |
+
self._prune_breaks(filename, lineno)
|
| 734 |
+
return None
|
| 735 |
+
|
| 736 |
+
def clear_bpbynumber(self, arg):
|
| 737 |
+
"""Delete a breakpoint by its index in Breakpoint.bpbynumber.
|
| 738 |
+
|
| 739 |
+
If arg is invalid, return an error message.
|
| 740 |
+
"""
|
| 741 |
+
try:
|
| 742 |
+
bp = self.get_bpbynumber(arg)
|
| 743 |
+
except ValueError as err:
|
| 744 |
+
return str(err)
|
| 745 |
+
bp.deleteMe()
|
| 746 |
+
self._prune_breaks(bp.file, bp.line)
|
| 747 |
+
return None
|
| 748 |
+
|
| 749 |
+
def clear_all_file_breaks(self, filename):
|
| 750 |
+
"""Delete all breakpoints in filename.
|
| 751 |
+
|
| 752 |
+
If none were set, return an error message.
|
| 753 |
+
"""
|
| 754 |
+
filename = self.canonic(filename)
|
| 755 |
+
if filename not in self.breaks:
|
| 756 |
+
return 'There are no breakpoints in %s' % filename
|
| 757 |
+
for line in self.breaks[filename]:
|
| 758 |
+
blist = Breakpoint.bplist[filename, line]
|
| 759 |
+
for bp in blist:
|
| 760 |
+
bp.deleteMe()
|
| 761 |
+
del self.breaks[filename]
|
| 762 |
+
return None
|
| 763 |
+
|
| 764 |
+
def clear_all_breaks(self):
|
| 765 |
+
"""Delete all existing breakpoints.
|
| 766 |
+
|
| 767 |
+
If none were set, return an error message.
|
| 768 |
+
"""
|
| 769 |
+
if not self.breaks:
|
| 770 |
+
return 'There are no breakpoints'
|
| 771 |
+
for bp in Breakpoint.bpbynumber:
|
| 772 |
+
if bp:
|
| 773 |
+
bp.deleteMe()
|
| 774 |
+
self.breaks = {}
|
| 775 |
+
return None
|
| 776 |
+
|
| 777 |
+
def get_bpbynumber(self, arg):
|
| 778 |
+
"""Return a breakpoint by its index in Breakpoint.bybpnumber.
|
| 779 |
+
|
| 780 |
+
For invalid arg values or if the breakpoint doesn't exist,
|
| 781 |
+
raise a ValueError.
|
| 782 |
+
"""
|
| 783 |
+
if not arg:
|
| 784 |
+
raise ValueError('Breakpoint number expected')
|
| 785 |
+
try:
|
| 786 |
+
number = int(arg)
|
| 787 |
+
except ValueError:
|
| 788 |
+
raise ValueError('Non-numeric breakpoint number %s' % arg) from None
|
| 789 |
+
try:
|
| 790 |
+
bp = Breakpoint.bpbynumber[number]
|
| 791 |
+
except IndexError:
|
| 792 |
+
raise ValueError('Breakpoint number %d out of range' % number) from None
|
| 793 |
+
if bp is None:
|
| 794 |
+
raise ValueError('Breakpoint %d already deleted' % number)
|
| 795 |
+
return bp
|
| 796 |
+
|
| 797 |
+
def get_break(self, filename, lineno):
|
| 798 |
+
"""Return True if there is a breakpoint for filename:lineno."""
|
| 799 |
+
filename = self.canonic(filename)
|
| 800 |
+
return filename in self.breaks and \
|
| 801 |
+
lineno in self.breaks[filename]
|
| 802 |
+
|
| 803 |
+
def get_breaks(self, filename, lineno):
|
| 804 |
+
"""Return all breakpoints for filename:lineno.
|
| 805 |
+
|
| 806 |
+
If no breakpoints are set, return an empty list.
|
| 807 |
+
"""
|
| 808 |
+
filename = self.canonic(filename)
|
| 809 |
+
return filename in self.breaks and \
|
| 810 |
+
lineno in self.breaks[filename] and \
|
| 811 |
+
Breakpoint.bplist[filename, lineno] or []
|
| 812 |
+
|
| 813 |
+
def get_file_breaks(self, filename):
|
| 814 |
+
"""Return all lines with breakpoints for filename.
|
| 815 |
+
|
| 816 |
+
If no breakpoints are set, return an empty list.
|
| 817 |
+
"""
|
| 818 |
+
filename = self.canonic(filename)
|
| 819 |
+
if filename in self.breaks:
|
| 820 |
+
return self.breaks[filename]
|
| 821 |
+
else:
|
| 822 |
+
return []
|
| 823 |
+
|
| 824 |
+
def get_all_breaks(self):
|
| 825 |
+
"""Return all breakpoints that are set."""
|
| 826 |
+
return self.breaks
|
| 827 |
+
|
| 828 |
+
# Derived classes and clients can call the following method
|
| 829 |
+
# to get a data structure representing a stack trace.
|
| 830 |
+
|
| 831 |
+
def get_stack(self, f, t):
|
| 832 |
+
"""Return a list of (frame, lineno) in a stack trace and a size.
|
| 833 |
+
|
| 834 |
+
List starts with original calling frame, if there is one.
|
| 835 |
+
Size may be number of frames above or below f.
|
| 836 |
+
"""
|
| 837 |
+
stack = []
|
| 838 |
+
if t and t.tb_frame is f:
|
| 839 |
+
t = t.tb_next
|
| 840 |
+
while f is not None:
|
| 841 |
+
stack.append((f, f.f_lineno))
|
| 842 |
+
if f is self.botframe:
|
| 843 |
+
break
|
| 844 |
+
f = f.f_back
|
| 845 |
+
stack.reverse()
|
| 846 |
+
i = max(0, len(stack) - 1)
|
| 847 |
+
while t is not None:
|
| 848 |
+
stack.append((t.tb_frame, t.tb_lineno))
|
| 849 |
+
t = t.tb_next
|
| 850 |
+
if f is None:
|
| 851 |
+
i = max(0, len(stack) - 1)
|
| 852 |
+
return stack, i
|
| 853 |
+
|
| 854 |
+
def format_stack_entry(self, frame_lineno, lprefix=': '):
|
| 855 |
+
"""Return a string with information about a stack entry.
|
| 856 |
+
|
| 857 |
+
The stack entry frame_lineno is a (frame, lineno) tuple. The
|
| 858 |
+
return string contains the canonical filename, the function name
|
| 859 |
+
or '<lambda>', the input arguments, the return value, and the
|
| 860 |
+
line of code (if it exists).
|
| 861 |
+
|
| 862 |
+
"""
|
| 863 |
+
import linecache, reprlib
|
| 864 |
+
frame, lineno = frame_lineno
|
| 865 |
+
filename = self.canonic(frame.f_code.co_filename)
|
| 866 |
+
s = '%s(%r)' % (filename, lineno)
|
| 867 |
+
if frame.f_code.co_name:
|
| 868 |
+
s += frame.f_code.co_name
|
| 869 |
+
else:
|
| 870 |
+
s += "<lambda>"
|
| 871 |
+
s += '()'
|
| 872 |
+
if '__return__' in frame.f_locals:
|
| 873 |
+
rv = frame.f_locals['__return__']
|
| 874 |
+
s += '->'
|
| 875 |
+
s += reprlib.repr(rv)
|
| 876 |
+
if lineno is not None:
|
| 877 |
+
line = linecache.getline(filename, lineno, frame.f_globals)
|
| 878 |
+
if line:
|
| 879 |
+
s += lprefix + line.strip()
|
| 880 |
+
else:
|
| 881 |
+
s += f'{lprefix}Warning: lineno is None'
|
| 882 |
+
return s
|
| 883 |
+
|
| 884 |
+
def disable_current_event(self):
|
| 885 |
+
"""Disable the current event."""
|
| 886 |
+
if self.backend == 'monitoring':
|
| 887 |
+
self.monitoring_tracer.disable_current_event()
|
| 888 |
+
|
| 889 |
+
def restart_events(self):
|
| 890 |
+
"""Restart all events."""
|
| 891 |
+
if self.backend == 'monitoring':
|
| 892 |
+
self.monitoring_tracer.restart_events()
|
| 893 |
+
|
| 894 |
+
# The following methods can be called by clients to use
|
| 895 |
+
# a debugger to debug a statement or an expression.
|
| 896 |
+
# Both can be given as a string, or a code object.
|
| 897 |
+
|
| 898 |
+
def run(self, cmd, globals=None, locals=None):
|
| 899 |
+
"""Debug a statement executed via the exec() function.
|
| 900 |
+
|
| 901 |
+
globals defaults to __main__.dict; locals defaults to globals.
|
| 902 |
+
"""
|
| 903 |
+
if globals is None:
|
| 904 |
+
import __main__
|
| 905 |
+
globals = __main__.__dict__
|
| 906 |
+
if locals is None:
|
| 907 |
+
locals = globals
|
| 908 |
+
self.reset()
|
| 909 |
+
if isinstance(cmd, str):
|
| 910 |
+
cmd = compile(cmd, "<string>", "exec")
|
| 911 |
+
self.start_trace()
|
| 912 |
+
try:
|
| 913 |
+
exec(cmd, globals, locals)
|
| 914 |
+
except BdbQuit:
|
| 915 |
+
pass
|
| 916 |
+
finally:
|
| 917 |
+
self.quitting = True
|
| 918 |
+
self.stop_trace()
|
| 919 |
+
|
| 920 |
+
def runeval(self, expr, globals=None, locals=None):
|
| 921 |
+
"""Debug an expression executed via the eval() function.
|
| 922 |
+
|
| 923 |
+
globals defaults to __main__.dict; locals defaults to globals.
|
| 924 |
+
"""
|
| 925 |
+
if globals is None:
|
| 926 |
+
import __main__
|
| 927 |
+
globals = __main__.__dict__
|
| 928 |
+
if locals is None:
|
| 929 |
+
locals = globals
|
| 930 |
+
self.reset()
|
| 931 |
+
self.start_trace()
|
| 932 |
+
try:
|
| 933 |
+
return eval(expr, globals, locals)
|
| 934 |
+
except BdbQuit:
|
| 935 |
+
pass
|
| 936 |
+
finally:
|
| 937 |
+
self.quitting = True
|
| 938 |
+
self.stop_trace()
|
| 939 |
+
|
| 940 |
+
def runctx(self, cmd, globals, locals):
|
| 941 |
+
"""For backwards-compatibility. Defers to run()."""
|
| 942 |
+
# B/W compatibility
|
| 943 |
+
self.run(cmd, globals, locals)
|
| 944 |
+
|
| 945 |
+
# This method is more useful to debug a single function call.
|
| 946 |
+
|
| 947 |
+
def runcall(self, func, /, *args, **kwds):
|
| 948 |
+
"""Debug a single function call.
|
| 949 |
+
|
| 950 |
+
Return the result of the function call.
|
| 951 |
+
"""
|
| 952 |
+
self.reset()
|
| 953 |
+
self.start_trace()
|
| 954 |
+
res = None
|
| 955 |
+
try:
|
| 956 |
+
res = func(*args, **kwds)
|
| 957 |
+
except BdbQuit:
|
| 958 |
+
pass
|
| 959 |
+
finally:
|
| 960 |
+
self.quitting = True
|
| 961 |
+
self.stop_trace()
|
| 962 |
+
return res
|
| 963 |
+
|
| 964 |
+
|
| 965 |
+
def set_trace():
|
| 966 |
+
"""Start debugging with a Bdb instance from the caller's frame."""
|
| 967 |
+
Bdb().set_trace()
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
class Breakpoint:
|
| 971 |
+
"""Breakpoint class.
|
| 972 |
+
|
| 973 |
+
Implements temporary breakpoints, ignore counts, disabling and
|
| 974 |
+
(re)-enabling, and conditionals.
|
| 975 |
+
|
| 976 |
+
Breakpoints are indexed by number through bpbynumber and by
|
| 977 |
+
the (file, line) tuple using bplist. The former points to a
|
| 978 |
+
single instance of class Breakpoint. The latter points to a
|
| 979 |
+
list of such instances since there may be more than one
|
| 980 |
+
breakpoint per line.
|
| 981 |
+
|
| 982 |
+
When creating a breakpoint, its associated filename should be
|
| 983 |
+
in canonical form. If funcname is defined, a breakpoint hit will be
|
| 984 |
+
counted when the first line of that function is executed. A
|
| 985 |
+
conditional breakpoint always counts a hit.
|
| 986 |
+
"""
|
| 987 |
+
|
| 988 |
+
# XXX Keeping state in the class is a mistake -- this means
|
| 989 |
+
# you cannot have more than one active Bdb instance.
|
| 990 |
+
|
| 991 |
+
next = 1 # Next bp to be assigned
|
| 992 |
+
bplist = {} # indexed by (file, lineno) tuple
|
| 993 |
+
bpbynumber = [None] # Each entry is None or an instance of Bpt
|
| 994 |
+
# index 0 is unused, except for marking an
|
| 995 |
+
# effective break .... see effective()
|
| 996 |
+
|
| 997 |
+
def __init__(self, file, line, temporary=False, cond=None, funcname=None):
|
| 998 |
+
self.funcname = funcname
|
| 999 |
+
# Needed if funcname is not None.
|
| 1000 |
+
self.func_first_executable_line = None
|
| 1001 |
+
self.file = file # This better be in canonical form!
|
| 1002 |
+
self.line = line
|
| 1003 |
+
self.temporary = temporary
|
| 1004 |
+
self.cond = cond
|
| 1005 |
+
self.enabled = True
|
| 1006 |
+
self.ignore = 0
|
| 1007 |
+
self.hits = 0
|
| 1008 |
+
self.number = Breakpoint.next
|
| 1009 |
+
Breakpoint.next += 1
|
| 1010 |
+
# Build the two lists
|
| 1011 |
+
self.bpbynumber.append(self)
|
| 1012 |
+
if (file, line) in self.bplist:
|
| 1013 |
+
self.bplist[file, line].append(self)
|
| 1014 |
+
else:
|
| 1015 |
+
self.bplist[file, line] = [self]
|
| 1016 |
+
|
| 1017 |
+
@staticmethod
|
| 1018 |
+
def clearBreakpoints():
|
| 1019 |
+
Breakpoint.next = 1
|
| 1020 |
+
Breakpoint.bplist = {}
|
| 1021 |
+
Breakpoint.bpbynumber = [None]
|
| 1022 |
+
|
| 1023 |
+
def deleteMe(self):
|
| 1024 |
+
"""Delete the breakpoint from the list associated to a file:line.
|
| 1025 |
+
|
| 1026 |
+
If it is the last breakpoint in that position, it also deletes
|
| 1027 |
+
the entry for the file:line.
|
| 1028 |
+
"""
|
| 1029 |
+
|
| 1030 |
+
index = (self.file, self.line)
|
| 1031 |
+
self.bpbynumber[self.number] = None # No longer in list
|
| 1032 |
+
self.bplist[index].remove(self)
|
| 1033 |
+
if not self.bplist[index]:
|
| 1034 |
+
# No more bp for this f:l combo
|
| 1035 |
+
del self.bplist[index]
|
| 1036 |
+
|
| 1037 |
+
def enable(self):
|
| 1038 |
+
"""Mark the breakpoint as enabled."""
|
| 1039 |
+
self.enabled = True
|
| 1040 |
+
|
| 1041 |
+
def disable(self):
|
| 1042 |
+
"""Mark the breakpoint as disabled."""
|
| 1043 |
+
self.enabled = False
|
| 1044 |
+
|
| 1045 |
+
def bpprint(self, out=None):
|
| 1046 |
+
"""Print the output of bpformat().
|
| 1047 |
+
|
| 1048 |
+
The optional out argument directs where the output is sent
|
| 1049 |
+
and defaults to standard output.
|
| 1050 |
+
"""
|
| 1051 |
+
if out is None:
|
| 1052 |
+
out = sys.stdout
|
| 1053 |
+
print(self.bpformat(), file=out)
|
| 1054 |
+
|
| 1055 |
+
def bpformat(self):
|
| 1056 |
+
"""Return a string with information about the breakpoint.
|
| 1057 |
+
|
| 1058 |
+
The information includes the breakpoint number, temporary
|
| 1059 |
+
status, file:line position, break condition, number of times to
|
| 1060 |
+
ignore, and number of times hit.
|
| 1061 |
+
|
| 1062 |
+
"""
|
| 1063 |
+
if self.temporary:
|
| 1064 |
+
disp = 'del '
|
| 1065 |
+
else:
|
| 1066 |
+
disp = 'keep '
|
| 1067 |
+
if self.enabled:
|
| 1068 |
+
disp = disp + 'yes '
|
| 1069 |
+
else:
|
| 1070 |
+
disp = disp + 'no '
|
| 1071 |
+
ret = '%-4dbreakpoint %s at %s:%d' % (self.number, disp,
|
| 1072 |
+
self.file, self.line)
|
| 1073 |
+
if self.cond:
|
| 1074 |
+
ret += '\n\tstop only if %s' % (self.cond,)
|
| 1075 |
+
if self.ignore:
|
| 1076 |
+
ret += '\n\tignore next %d hits' % (self.ignore,)
|
| 1077 |
+
if self.hits:
|
| 1078 |
+
if self.hits > 1:
|
| 1079 |
+
ss = 's'
|
| 1080 |
+
else:
|
| 1081 |
+
ss = ''
|
| 1082 |
+
ret += '\n\tbreakpoint already hit %d time%s' % (self.hits, ss)
|
| 1083 |
+
return ret
|
| 1084 |
+
|
| 1085 |
+
def __str__(self):
|
| 1086 |
+
"Return a condensed description of the breakpoint."
|
| 1087 |
+
return 'breakpoint %s at %s:%s' % (self.number, self.file, self.line)
|
| 1088 |
+
|
| 1089 |
+
# -----------end of Breakpoint class----------
|
| 1090 |
+
|
| 1091 |
+
|
| 1092 |
+
def checkfuncname(b, frame):
|
| 1093 |
+
"""Return True if break should happen here.
|
| 1094 |
+
|
| 1095 |
+
Whether a break should happen depends on the way that b (the breakpoint)
|
| 1096 |
+
was set. If it was set via line number, check if b.line is the same as
|
| 1097 |
+
the one in the frame. If it was set via function name, check if this is
|
| 1098 |
+
the right function and if it is on the first executable line.
|
| 1099 |
+
"""
|
| 1100 |
+
if not b.funcname:
|
| 1101 |
+
# Breakpoint was set via line number.
|
| 1102 |
+
if b.line != frame.f_lineno:
|
| 1103 |
+
# Breakpoint was set at a line with a def statement and the function
|
| 1104 |
+
# defined is called: don't break.
|
| 1105 |
+
return False
|
| 1106 |
+
return True
|
| 1107 |
+
|
| 1108 |
+
# Breakpoint set via function name.
|
| 1109 |
+
if frame.f_code.co_name != b.funcname:
|
| 1110 |
+
# It's not a function call, but rather execution of def statement.
|
| 1111 |
+
return False
|
| 1112 |
+
|
| 1113 |
+
# We are in the right frame.
|
| 1114 |
+
if not b.func_first_executable_line:
|
| 1115 |
+
# The function is entered for the 1st time.
|
| 1116 |
+
b.func_first_executable_line = frame.f_lineno
|
| 1117 |
+
|
| 1118 |
+
if b.func_first_executable_line != frame.f_lineno:
|
| 1119 |
+
# But we are not at the first line number: don't break.
|
| 1120 |
+
return False
|
| 1121 |
+
return True
|
| 1122 |
+
|
| 1123 |
+
|
| 1124 |
+
def effective(file, line, frame):
|
| 1125 |
+
"""Return (active breakpoint, delete temporary flag) or (None, None) as
|
| 1126 |
+
breakpoint to act upon.
|
| 1127 |
+
|
| 1128 |
+
The "active breakpoint" is the first entry in bplist[line, file] (which
|
| 1129 |
+
must exist) that is enabled, for which checkfuncname is True, and that
|
| 1130 |
+
has neither a False condition nor a positive ignore count. The flag,
|
| 1131 |
+
meaning that a temporary breakpoint should be deleted, is False only
|
| 1132 |
+
when the condiion cannot be evaluated (in which case, ignore count is
|
| 1133 |
+
ignored).
|
| 1134 |
+
|
| 1135 |
+
If no such entry exists, then (None, None) is returned.
|
| 1136 |
+
"""
|
| 1137 |
+
possibles = Breakpoint.bplist[file, line]
|
| 1138 |
+
for b in possibles:
|
| 1139 |
+
if not b.enabled:
|
| 1140 |
+
continue
|
| 1141 |
+
if not checkfuncname(b, frame):
|
| 1142 |
+
continue
|
| 1143 |
+
# Count every hit when bp is enabled
|
| 1144 |
+
b.hits += 1
|
| 1145 |
+
if not b.cond:
|
| 1146 |
+
# If unconditional, and ignoring go on to next, else break
|
| 1147 |
+
if b.ignore > 0:
|
| 1148 |
+
b.ignore -= 1
|
| 1149 |
+
continue
|
| 1150 |
+
else:
|
| 1151 |
+
# breakpoint and marker that it's ok to delete if temporary
|
| 1152 |
+
return (b, True)
|
| 1153 |
+
else:
|
| 1154 |
+
# Conditional bp.
|
| 1155 |
+
# Ignore count applies only to those bpt hits where the
|
| 1156 |
+
# condition evaluates to true.
|
| 1157 |
+
try:
|
| 1158 |
+
val = eval(b.cond, frame.f_globals, frame.f_locals)
|
| 1159 |
+
if val:
|
| 1160 |
+
if b.ignore > 0:
|
| 1161 |
+
b.ignore -= 1
|
| 1162 |
+
# continue
|
| 1163 |
+
else:
|
| 1164 |
+
return (b, True)
|
| 1165 |
+
# else:
|
| 1166 |
+
# continue
|
| 1167 |
+
except:
|
| 1168 |
+
# if eval fails, most conservative thing is to stop on
|
| 1169 |
+
# breakpoint regardless of ignore count. Don't delete
|
| 1170 |
+
# temporary, as another hint to user.
|
| 1171 |
+
return (b, False)
|
| 1172 |
+
return (None, None)
|
| 1173 |
+
|
| 1174 |
+
|
| 1175 |
+
# -------------------- testing --------------------
|
| 1176 |
+
|
| 1177 |
+
class Tdb(Bdb):
|
| 1178 |
+
def user_call(self, frame, args):
|
| 1179 |
+
name = frame.f_code.co_name
|
| 1180 |
+
if not name: name = '???'
|
| 1181 |
+
print('+++ call', name, args)
|
| 1182 |
+
def user_line(self, frame):
|
| 1183 |
+
import linecache
|
| 1184 |
+
name = frame.f_code.co_name
|
| 1185 |
+
if not name: name = '???'
|
| 1186 |
+
fn = self.canonic(frame.f_code.co_filename)
|
| 1187 |
+
line = linecache.getline(fn, frame.f_lineno, frame.f_globals)
|
| 1188 |
+
print('+++', fn, frame.f_lineno, name, ':', line.strip())
|
| 1189 |
+
def user_return(self, frame, retval):
|
| 1190 |
+
print('+++ return', retval)
|
| 1191 |
+
def user_exception(self, frame, exc_stuff):
|
| 1192 |
+
print('+++ exception', exc_stuff)
|
| 1193 |
+
self.set_continue()
|
| 1194 |
+
|
| 1195 |
+
def foo(n):
|
| 1196 |
+
print('foo(', n, ')')
|
| 1197 |
+
x = bar(n*10)
|
| 1198 |
+
print('bar returned', x)
|
| 1199 |
+
|
| 1200 |
+
def bar(a):
|
| 1201 |
+
print('bar(', a, ')')
|
| 1202 |
+
return a/2
|
| 1203 |
+
|
| 1204 |
+
def test():
|
| 1205 |
+
t = Tdb()
|
| 1206 |
+
t.run('import bdb; bdb.foo(10)')
|
micromamba_root/envs/hf_sync/Lib/bisect.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bisection algorithms."""
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def insort_right(a, x, lo=0, hi=None, *, key=None):
|
| 5 |
+
"""Insert item x in list a, and keep it sorted assuming a is sorted.
|
| 6 |
+
|
| 7 |
+
If x is already in a, insert it to the right of the rightmost x.
|
| 8 |
+
|
| 9 |
+
Optional args lo (default 0) and hi (default len(a)) bound the
|
| 10 |
+
slice of a to be searched.
|
| 11 |
+
|
| 12 |
+
A custom key function can be supplied to customize the sort order.
|
| 13 |
+
"""
|
| 14 |
+
if key is None:
|
| 15 |
+
lo = bisect_right(a, x, lo, hi)
|
| 16 |
+
else:
|
| 17 |
+
lo = bisect_right(a, key(x), lo, hi, key=key)
|
| 18 |
+
a.insert(lo, x)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def bisect_right(a, x, lo=0, hi=None, *, key=None):
|
| 22 |
+
"""Return the index where to insert item x in list a, assuming a is sorted.
|
| 23 |
+
|
| 24 |
+
The return value i is such that all e in a[:i] have e <= x, and all e in
|
| 25 |
+
a[i:] have e > x. So if x already appears in the list, a.insert(i, x) will
|
| 26 |
+
insert just after the rightmost x already there.
|
| 27 |
+
|
| 28 |
+
Optional args lo (default 0) and hi (default len(a)) bound the
|
| 29 |
+
slice of a to be searched.
|
| 30 |
+
|
| 31 |
+
A custom key function can be supplied to customize the sort order.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
if lo < 0:
|
| 35 |
+
raise ValueError('lo must be non-negative')
|
| 36 |
+
if hi is None:
|
| 37 |
+
hi = len(a)
|
| 38 |
+
# Note, the comparison uses "<" to match the
|
| 39 |
+
# __lt__() logic in list.sort() and in heapq.
|
| 40 |
+
if key is None:
|
| 41 |
+
while lo < hi:
|
| 42 |
+
mid = (lo + hi) // 2
|
| 43 |
+
if x < a[mid]:
|
| 44 |
+
hi = mid
|
| 45 |
+
else:
|
| 46 |
+
lo = mid + 1
|
| 47 |
+
else:
|
| 48 |
+
while lo < hi:
|
| 49 |
+
mid = (lo + hi) // 2
|
| 50 |
+
if x < key(a[mid]):
|
| 51 |
+
hi = mid
|
| 52 |
+
else:
|
| 53 |
+
lo = mid + 1
|
| 54 |
+
return lo
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def insort_left(a, x, lo=0, hi=None, *, key=None):
|
| 58 |
+
"""Insert item x in list a, and keep it sorted assuming a is sorted.
|
| 59 |
+
|
| 60 |
+
If x is already in a, insert it to the left of the leftmost x.
|
| 61 |
+
|
| 62 |
+
Optional args lo (default 0) and hi (default len(a)) bound the
|
| 63 |
+
slice of a to be searched.
|
| 64 |
+
|
| 65 |
+
A custom key function can be supplied to customize the sort order.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
if key is None:
|
| 69 |
+
lo = bisect_left(a, x, lo, hi)
|
| 70 |
+
else:
|
| 71 |
+
lo = bisect_left(a, key(x), lo, hi, key=key)
|
| 72 |
+
a.insert(lo, x)
|
| 73 |
+
|
| 74 |
+
def bisect_left(a, x, lo=0, hi=None, *, key=None):
|
| 75 |
+
"""Return the index where to insert item x in list a, assuming a is sorted.
|
| 76 |
+
|
| 77 |
+
The return value i is such that all e in a[:i] have e < x, and all e in
|
| 78 |
+
a[i:] have e >= x. So if x already appears in the list, a.insert(i, x) will
|
| 79 |
+
insert just before the leftmost x already there.
|
| 80 |
+
|
| 81 |
+
Optional args lo (default 0) and hi (default len(a)) bound the
|
| 82 |
+
slice of a to be searched.
|
| 83 |
+
|
| 84 |
+
A custom key function can be supplied to customize the sort order.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
if lo < 0:
|
| 88 |
+
raise ValueError('lo must be non-negative')
|
| 89 |
+
if hi is None:
|
| 90 |
+
hi = len(a)
|
| 91 |
+
# Note, the comparison uses "<" to match the
|
| 92 |
+
# __lt__() logic in list.sort() and in heapq.
|
| 93 |
+
if key is None:
|
| 94 |
+
while lo < hi:
|
| 95 |
+
mid = (lo + hi) // 2
|
| 96 |
+
if a[mid] < x:
|
| 97 |
+
lo = mid + 1
|
| 98 |
+
else:
|
| 99 |
+
hi = mid
|
| 100 |
+
else:
|
| 101 |
+
while lo < hi:
|
| 102 |
+
mid = (lo + hi) // 2
|
| 103 |
+
if key(a[mid]) < x:
|
| 104 |
+
lo = mid + 1
|
| 105 |
+
else:
|
| 106 |
+
hi = mid
|
| 107 |
+
return lo
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# Overwrite above definitions with a fast C implementation
|
| 111 |
+
try:
|
| 112 |
+
from _bisect import *
|
| 113 |
+
except ImportError:
|
| 114 |
+
pass
|
| 115 |
+
|
| 116 |
+
# Create aliases
|
| 117 |
+
bisect = bisect_right
|
| 118 |
+
insort = insort_right
|
micromamba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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Interface to the libbzip2 compression library.
|
| 2 |
+
|
| 3 |
+
This module provides a file interface, classes for incremental
|
| 4 |
+
(de)compression, and functions for one-shot (de)compression.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
__all__ = ["BZ2File", "BZ2Compressor", "BZ2Decompressor",
|
| 8 |
+
"open", "compress", "decompress"]
|
| 9 |
+
|
| 10 |
+
__author__ = "Nadeem Vawda <nadeem.vawda@gmail.com>"
|
| 11 |
+
|
| 12 |
+
from builtins import open as _builtin_open
|
| 13 |
+
from compression._common import _streams
|
| 14 |
+
import io
|
| 15 |
+
import os
|
| 16 |
+
|
| 17 |
+
from _bz2 import BZ2Compressor, BZ2Decompressor
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# Value 0 no longer used
|
| 21 |
+
_MODE_READ = 1
|
| 22 |
+
# Value 2 no longer used
|
| 23 |
+
_MODE_WRITE = 3
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class BZ2File(_streams.BaseStream):
|
| 27 |
+
|
| 28 |
+
"""A file object providing transparent bzip2 (de)compression.
|
| 29 |
+
|
| 30 |
+
A BZ2File can act as a wrapper for an existing file object, or refer
|
| 31 |
+
directly to a named file on disk.
|
| 32 |
+
|
| 33 |
+
Note that BZ2File provides a *binary* file interface - data read is
|
| 34 |
+
returned as bytes, and data to be written should be given as bytes.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(self, filename, mode="r", *, compresslevel=9):
|
| 38 |
+
"""Open a bzip2-compressed file.
|
| 39 |
+
|
| 40 |
+
If filename is a str, bytes, or PathLike object, it gives the
|
| 41 |
+
name of the file to be opened. Otherwise, it should be a file
|
| 42 |
+
object, which will be used to read or write the compressed data.
|
| 43 |
+
|
| 44 |
+
mode can be 'r' for reading (default), 'w' for (over)writing,
|
| 45 |
+
'x' for creating exclusively, or 'a' for appending. These can
|
| 46 |
+
equivalently be given as 'rb', 'wb', 'xb', and 'ab'.
|
| 47 |
+
|
| 48 |
+
If mode is 'w', 'x' or 'a', compresslevel can be a number between 1
|
| 49 |
+
and 9 specifying the level of compression: 1 produces the least
|
| 50 |
+
compression, and 9 (default) produces the most compression.
|
| 51 |
+
|
| 52 |
+
If mode is 'r', the input file may be the concatenation of
|
| 53 |
+
multiple compressed streams.
|
| 54 |
+
"""
|
| 55 |
+
self._fp = None
|
| 56 |
+
self._closefp = False
|
| 57 |
+
self._mode = None
|
| 58 |
+
|
| 59 |
+
if not (1 <= compresslevel <= 9):
|
| 60 |
+
raise ValueError("compresslevel must be between 1 and 9")
|
| 61 |
+
|
| 62 |
+
if mode in ("", "r", "rb"):
|
| 63 |
+
mode = "rb"
|
| 64 |
+
mode_code = _MODE_READ
|
| 65 |
+
elif mode in ("w", "wb"):
|
| 66 |
+
mode = "wb"
|
| 67 |
+
mode_code = _MODE_WRITE
|
| 68 |
+
self._compressor = BZ2Compressor(compresslevel)
|
| 69 |
+
elif mode in ("x", "xb"):
|
| 70 |
+
mode = "xb"
|
| 71 |
+
mode_code = _MODE_WRITE
|
| 72 |
+
self._compressor = BZ2Compressor(compresslevel)
|
| 73 |
+
elif mode in ("a", "ab"):
|
| 74 |
+
mode = "ab"
|
| 75 |
+
mode_code = _MODE_WRITE
|
| 76 |
+
self._compressor = BZ2Compressor(compresslevel)
|
| 77 |
+
else:
|
| 78 |
+
raise ValueError("Invalid mode: %r" % (mode,))
|
| 79 |
+
|
| 80 |
+
if isinstance(filename, (str, bytes, os.PathLike)):
|
| 81 |
+
self._fp = _builtin_open(filename, mode)
|
| 82 |
+
self._closefp = True
|
| 83 |
+
self._mode = mode_code
|
| 84 |
+
elif hasattr(filename, "read") or hasattr(filename, "write"):
|
| 85 |
+
self._fp = filename
|
| 86 |
+
self._mode = mode_code
|
| 87 |
+
else:
|
| 88 |
+
raise TypeError("filename must be a str, bytes, file or PathLike object")
|
| 89 |
+
|
| 90 |
+
if self._mode == _MODE_READ:
|
| 91 |
+
raw = _streams.DecompressReader(self._fp,
|
| 92 |
+
BZ2Decompressor, trailing_error=OSError)
|
| 93 |
+
self._buffer = io.BufferedReader(raw)
|
| 94 |
+
else:
|
| 95 |
+
self._pos = 0
|
| 96 |
+
|
| 97 |
+
def close(self):
|
| 98 |
+
"""Flush and close the file.
|
| 99 |
+
|
| 100 |
+
May be called more than once without error. Once the file is
|
| 101 |
+
closed, any other operation on it will raise a ValueError.
|
| 102 |
+
"""
|
| 103 |
+
if self.closed:
|
| 104 |
+
return
|
| 105 |
+
try:
|
| 106 |
+
if self._mode == _MODE_READ:
|
| 107 |
+
self._buffer.close()
|
| 108 |
+
elif self._mode == _MODE_WRITE:
|
| 109 |
+
self._fp.write(self._compressor.flush())
|
| 110 |
+
self._compressor = None
|
| 111 |
+
finally:
|
| 112 |
+
try:
|
| 113 |
+
if self._closefp:
|
| 114 |
+
self._fp.close()
|
| 115 |
+
finally:
|
| 116 |
+
self._fp = None
|
| 117 |
+
self._closefp = False
|
| 118 |
+
self._buffer = None
|
| 119 |
+
|
| 120 |
+
@property
|
| 121 |
+
def closed(self):
|
| 122 |
+
"""True if this file is closed."""
|
| 123 |
+
return self._fp is None
|
| 124 |
+
|
| 125 |
+
@property
|
| 126 |
+
def name(self):
|
| 127 |
+
self._check_not_closed()
|
| 128 |
+
return self._fp.name
|
| 129 |
+
|
| 130 |
+
@property
|
| 131 |
+
def mode(self):
|
| 132 |
+
return 'wb' if self._mode == _MODE_WRITE else 'rb'
|
| 133 |
+
|
| 134 |
+
def fileno(self):
|
| 135 |
+
"""Return the file descriptor for the underlying file."""
|
| 136 |
+
self._check_not_closed()
|
| 137 |
+
return self._fp.fileno()
|
| 138 |
+
|
| 139 |
+
def seekable(self):
|
| 140 |
+
"""Return whether the file supports seeking."""
|
| 141 |
+
return self.readable() and self._buffer.seekable()
|
| 142 |
+
|
| 143 |
+
def readable(self):
|
| 144 |
+
"""Return whether the file was opened for reading."""
|
| 145 |
+
self._check_not_closed()
|
| 146 |
+
return self._mode == _MODE_READ
|
| 147 |
+
|
| 148 |
+
def writable(self):
|
| 149 |
+
"""Return whether the file was opened for writing."""
|
| 150 |
+
self._check_not_closed()
|
| 151 |
+
return self._mode == _MODE_WRITE
|
| 152 |
+
|
| 153 |
+
def peek(self, n=0):
|
| 154 |
+
"""Return buffered data without advancing the file position.
|
| 155 |
+
|
| 156 |
+
Always returns at least one byte of data, unless at EOF.
|
| 157 |
+
The exact number of bytes returned is unspecified.
|
| 158 |
+
"""
|
| 159 |
+
self._check_can_read()
|
| 160 |
+
# Relies on the undocumented fact that BufferedReader.peek()
|
| 161 |
+
# always returns at least one byte (except at EOF), independent
|
| 162 |
+
# of the value of n
|
| 163 |
+
return self._buffer.peek(n)
|
| 164 |
+
|
| 165 |
+
def read(self, size=-1):
|
| 166 |
+
"""Read up to size uncompressed bytes from the file.
|
| 167 |
+
|
| 168 |
+
If size is negative or omitted, read until EOF is reached.
|
| 169 |
+
Returns b'' if the file is already at EOF.
|
| 170 |
+
"""
|
| 171 |
+
self._check_can_read()
|
| 172 |
+
return self._buffer.read(size)
|
| 173 |
+
|
| 174 |
+
def read1(self, size=-1):
|
| 175 |
+
"""Read up to size uncompressed bytes, while trying to avoid
|
| 176 |
+
making multiple reads from the underlying stream. Reads up to a
|
| 177 |
+
buffer's worth of data if size is negative.
|
| 178 |
+
|
| 179 |
+
Returns b'' if the file is at EOF.
|
| 180 |
+
"""
|
| 181 |
+
self._check_can_read()
|
| 182 |
+
if size < 0:
|
| 183 |
+
size = io.DEFAULT_BUFFER_SIZE
|
| 184 |
+
return self._buffer.read1(size)
|
| 185 |
+
|
| 186 |
+
def readinto(self, b):
|
| 187 |
+
"""Read bytes into b.
|
| 188 |
+
|
| 189 |
+
Returns the number of bytes read (0 for EOF).
|
| 190 |
+
"""
|
| 191 |
+
self._check_can_read()
|
| 192 |
+
return self._buffer.readinto(b)
|
| 193 |
+
|
| 194 |
+
def readline(self, size=-1):
|
| 195 |
+
"""Read a line of uncompressed bytes from the file.
|
| 196 |
+
|
| 197 |
+
The terminating newline (if present) is retained. If size is
|
| 198 |
+
non-negative, no more than size bytes will be read (in which
|
| 199 |
+
case the line may be incomplete). Returns b'' if already at EOF.
|
| 200 |
+
"""
|
| 201 |
+
if not isinstance(size, int):
|
| 202 |
+
if not hasattr(size, "__index__"):
|
| 203 |
+
raise TypeError("Integer argument expected")
|
| 204 |
+
size = size.__index__()
|
| 205 |
+
self._check_can_read()
|
| 206 |
+
return self._buffer.readline(size)
|
| 207 |
+
|
| 208 |
+
def readlines(self, size=-1):
|
| 209 |
+
"""Read a list of lines of uncompressed bytes from the file.
|
| 210 |
+
|
| 211 |
+
size can be specified to control the number of lines read: no
|
| 212 |
+
further lines will be read once the total size of the lines read
|
| 213 |
+
so far equals or exceeds size.
|
| 214 |
+
"""
|
| 215 |
+
if not isinstance(size, int):
|
| 216 |
+
if not hasattr(size, "__index__"):
|
| 217 |
+
raise TypeError("Integer argument expected")
|
| 218 |
+
size = size.__index__()
|
| 219 |
+
self._check_can_read()
|
| 220 |
+
return self._buffer.readlines(size)
|
| 221 |
+
|
| 222 |
+
def write(self, data):
|
| 223 |
+
"""Write a byte string to the file.
|
| 224 |
+
|
| 225 |
+
Returns the number of uncompressed bytes written, which is
|
| 226 |
+
always the length of data in bytes. Note that due to buffering,
|
| 227 |
+
the file on disk may not reflect the data written until close()
|
| 228 |
+
is called.
|
| 229 |
+
"""
|
| 230 |
+
self._check_can_write()
|
| 231 |
+
if isinstance(data, (bytes, bytearray)):
|
| 232 |
+
length = len(data)
|
| 233 |
+
else:
|
| 234 |
+
# accept any data that supports the buffer protocol
|
| 235 |
+
data = memoryview(data)
|
| 236 |
+
length = data.nbytes
|
| 237 |
+
|
| 238 |
+
compressed = self._compressor.compress(data)
|
| 239 |
+
self._fp.write(compressed)
|
| 240 |
+
self._pos += length
|
| 241 |
+
return length
|
| 242 |
+
|
| 243 |
+
def writelines(self, seq):
|
| 244 |
+
"""Write a sequence of byte strings to the file.
|
| 245 |
+
|
| 246 |
+
Returns the number of uncompressed bytes written.
|
| 247 |
+
seq can be any iterable yielding byte strings.
|
| 248 |
+
|
| 249 |
+
Line separators are not added between the written byte strings.
|
| 250 |
+
"""
|
| 251 |
+
return _streams.BaseStream.writelines(self, seq)
|
| 252 |
+
|
| 253 |
+
def seek(self, offset, whence=io.SEEK_SET):
|
| 254 |
+
"""Change the file position.
|
| 255 |
+
|
| 256 |
+
The new position is specified by offset, relative to the
|
| 257 |
+
position indicated by whence. Values for whence are:
|
| 258 |
+
|
| 259 |
+
0: start of stream (default); offset must not be negative
|
| 260 |
+
1: current stream position
|
| 261 |
+
2: end of stream; offset must not be positive
|
| 262 |
+
|
| 263 |
+
Returns the new file position.
|
| 264 |
+
|
| 265 |
+
Note that seeking is emulated, so depending on the parameters,
|
| 266 |
+
this operation may be extremely slow.
|
| 267 |
+
"""
|
| 268 |
+
self._check_can_seek()
|
| 269 |
+
return self._buffer.seek(offset, whence)
|
| 270 |
+
|
| 271 |
+
def tell(self):
|
| 272 |
+
"""Return the current file position."""
|
| 273 |
+
self._check_not_closed()
|
| 274 |
+
if self._mode == _MODE_READ:
|
| 275 |
+
return self._buffer.tell()
|
| 276 |
+
return self._pos
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def open(filename, mode="rb", compresslevel=9,
|
| 280 |
+
encoding=None, errors=None, newline=None):
|
| 281 |
+
"""Open a bzip2-compressed file in binary or text mode.
|
| 282 |
+
|
| 283 |
+
The filename argument can be an actual filename (a str, bytes, or
|
| 284 |
+
PathLike object), or an existing file object to read from or write
|
| 285 |
+
to.
|
| 286 |
+
|
| 287 |
+
The mode argument can be "r", "rb", "w", "wb", "x", "xb", "a" or
|
| 288 |
+
"ab" for binary mode, or "rt", "wt", "xt" or "at" for text mode.
|
| 289 |
+
The default mode is "rb", and the default compresslevel is 9.
|
| 290 |
+
|
| 291 |
+
For binary mode, this function is equivalent to the BZ2File
|
| 292 |
+
constructor: BZ2File(filename, mode, compresslevel). In this case,
|
| 293 |
+
the encoding, errors and newline arguments must not be provided.
|
| 294 |
+
|
| 295 |
+
For text mode, a BZ2File object is created, and wrapped in an
|
| 296 |
+
io.TextIOWrapper instance with the specified encoding, error
|
| 297 |
+
handling behavior, and line ending(s).
|
| 298 |
+
|
| 299 |
+
"""
|
| 300 |
+
if "t" in mode:
|
| 301 |
+
if "b" in mode:
|
| 302 |
+
raise ValueError("Invalid mode: %r" % (mode,))
|
| 303 |
+
else:
|
| 304 |
+
if encoding is not None:
|
| 305 |
+
raise ValueError("Argument 'encoding' not supported in binary mode")
|
| 306 |
+
if errors is not None:
|
| 307 |
+
raise ValueError("Argument 'errors' not supported in binary mode")
|
| 308 |
+
if newline is not None:
|
| 309 |
+
raise ValueError("Argument 'newline' not supported in binary mode")
|
| 310 |
+
|
| 311 |
+
bz_mode = mode.replace("t", "")
|
| 312 |
+
binary_file = BZ2File(filename, bz_mode, compresslevel=compresslevel)
|
| 313 |
+
|
| 314 |
+
if "t" in mode:
|
| 315 |
+
encoding = io.text_encoding(encoding)
|
| 316 |
+
return io.TextIOWrapper(binary_file, encoding, errors, newline)
|
| 317 |
+
else:
|
| 318 |
+
return binary_file
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def compress(data, compresslevel=9):
|
| 322 |
+
"""Compress a block of data.
|
| 323 |
+
|
| 324 |
+
compresslevel, if given, must be a number between 1 and 9.
|
| 325 |
+
|
| 326 |
+
For incremental compression, use a BZ2Compressor object instead.
|
| 327 |
+
"""
|
| 328 |
+
comp = BZ2Compressor(compresslevel)
|
| 329 |
+
return comp.compress(data) + comp.flush()
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def decompress(data):
|
| 333 |
+
"""Decompress a block of data.
|
| 334 |
+
|
| 335 |
+
For incremental decompression, use a BZ2Decompressor object instead.
|
| 336 |
+
"""
|
| 337 |
+
results = []
|
| 338 |
+
while data:
|
| 339 |
+
decomp = BZ2Decompressor()
|
| 340 |
+
try:
|
| 341 |
+
res = decomp.decompress(data)
|
| 342 |
+
except OSError:
|
| 343 |
+
if results:
|
| 344 |
+
break # Leftover data is not a valid bzip2 stream; ignore it.
|
| 345 |
+
else:
|
| 346 |
+
raise # Error on the first iteration; bail out.
|
| 347 |
+
results.append(res)
|
| 348 |
+
if not decomp.eof:
|
| 349 |
+
raise ValueError("Compressed data ended before the "
|
| 350 |
+
"end-of-stream marker was reached")
|
| 351 |
+
data = decomp.unused_data
|
| 352 |
+
return b"".join(results)
|
micromamba_root/envs/hf_sync/Lib/cProfile.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Python interface for the 'lsprof' profiler.
|
| 2 |
+
Compatible with the 'profile' module.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
__all__ = ["run", "runctx", "Profile"]
|
| 6 |
+
|
| 7 |
+
import _lsprof
|
| 8 |
+
import importlib.machinery
|
| 9 |
+
import importlib.util
|
| 10 |
+
import io
|
| 11 |
+
import profile as _pyprofile
|
| 12 |
+
|
| 13 |
+
# ____________________________________________________________
|
| 14 |
+
# Simple interface
|
| 15 |
+
|
| 16 |
+
def run(statement, filename=None, sort=-1):
|
| 17 |
+
return _pyprofile._Utils(Profile).run(statement, filename, sort)
|
| 18 |
+
|
| 19 |
+
def runctx(statement, globals, locals, filename=None, sort=-1):
|
| 20 |
+
return _pyprofile._Utils(Profile).runctx(statement, globals, locals,
|
| 21 |
+
filename, sort)
|
| 22 |
+
|
| 23 |
+
run.__doc__ = _pyprofile.run.__doc__
|
| 24 |
+
runctx.__doc__ = _pyprofile.runctx.__doc__
|
| 25 |
+
|
| 26 |
+
# ____________________________________________________________
|
| 27 |
+
|
| 28 |
+
class Profile(_lsprof.Profiler):
|
| 29 |
+
"""Profile(timer=None, timeunit=None, subcalls=True, builtins=True)
|
| 30 |
+
|
| 31 |
+
Builds a profiler object using the specified timer function.
|
| 32 |
+
The default timer is a fast built-in one based on real time.
|
| 33 |
+
For custom timer functions returning integers, timeunit can
|
| 34 |
+
be a float specifying a scale (i.e. how long each integer unit
|
| 35 |
+
is, in seconds).
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
# Most of the functionality is in the base class.
|
| 39 |
+
# This subclass only adds convenient and backward-compatible methods.
|
| 40 |
+
|
| 41 |
+
def print_stats(self, sort=-1):
|
| 42 |
+
import pstats
|
| 43 |
+
if not isinstance(sort, tuple):
|
| 44 |
+
sort = (sort,)
|
| 45 |
+
pstats.Stats(self).strip_dirs().sort_stats(*sort).print_stats()
|
| 46 |
+
|
| 47 |
+
def dump_stats(self, file):
|
| 48 |
+
import marshal
|
| 49 |
+
with open(file, 'wb') as f:
|
| 50 |
+
self.create_stats()
|
| 51 |
+
marshal.dump(self.stats, f)
|
| 52 |
+
|
| 53 |
+
def create_stats(self):
|
| 54 |
+
self.disable()
|
| 55 |
+
self.snapshot_stats()
|
| 56 |
+
|
| 57 |
+
def snapshot_stats(self):
|
| 58 |
+
entries = self.getstats()
|
| 59 |
+
self.stats = {}
|
| 60 |
+
callersdicts = {}
|
| 61 |
+
# call information
|
| 62 |
+
for entry in entries:
|
| 63 |
+
func = label(entry.code)
|
| 64 |
+
nc = entry.callcount # ncalls column of pstats (before '/')
|
| 65 |
+
cc = nc - entry.reccallcount # ncalls column of pstats (after '/')
|
| 66 |
+
tt = entry.inlinetime # tottime column of pstats
|
| 67 |
+
ct = entry.totaltime # cumtime column of pstats
|
| 68 |
+
callers = {}
|
| 69 |
+
callersdicts[id(entry.code)] = callers
|
| 70 |
+
self.stats[func] = cc, nc, tt, ct, callers
|
| 71 |
+
# subcall information
|
| 72 |
+
for entry in entries:
|
| 73 |
+
if entry.calls:
|
| 74 |
+
func = label(entry.code)
|
| 75 |
+
for subentry in entry.calls:
|
| 76 |
+
try:
|
| 77 |
+
callers = callersdicts[id(subentry.code)]
|
| 78 |
+
except KeyError:
|
| 79 |
+
continue
|
| 80 |
+
nc = subentry.callcount
|
| 81 |
+
cc = nc - subentry.reccallcount
|
| 82 |
+
tt = subentry.inlinetime
|
| 83 |
+
ct = subentry.totaltime
|
| 84 |
+
if func in callers:
|
| 85 |
+
prev = callers[func]
|
| 86 |
+
nc += prev[0]
|
| 87 |
+
cc += prev[1]
|
| 88 |
+
tt += prev[2]
|
| 89 |
+
ct += prev[3]
|
| 90 |
+
callers[func] = nc, cc, tt, ct
|
| 91 |
+
|
| 92 |
+
# The following two methods can be called by clients to use
|
| 93 |
+
# a profiler to profile a statement, given as a string.
|
| 94 |
+
|
| 95 |
+
def run(self, cmd):
|
| 96 |
+
import __main__
|
| 97 |
+
dict = __main__.__dict__
|
| 98 |
+
return self.runctx(cmd, dict, dict)
|
| 99 |
+
|
| 100 |
+
def runctx(self, cmd, globals, locals):
|
| 101 |
+
self.enable()
|
| 102 |
+
try:
|
| 103 |
+
exec(cmd, globals, locals)
|
| 104 |
+
finally:
|
| 105 |
+
self.disable()
|
| 106 |
+
return self
|
| 107 |
+
|
| 108 |
+
# This method is more useful to profile a single function call.
|
| 109 |
+
def runcall(self, func, /, *args, **kw):
|
| 110 |
+
self.enable()
|
| 111 |
+
try:
|
| 112 |
+
return func(*args, **kw)
|
| 113 |
+
finally:
|
| 114 |
+
self.disable()
|
| 115 |
+
|
| 116 |
+
def __enter__(self):
|
| 117 |
+
self.enable()
|
| 118 |
+
return self
|
| 119 |
+
|
| 120 |
+
def __exit__(self, *exc_info):
|
| 121 |
+
self.disable()
|
| 122 |
+
|
| 123 |
+
# ____________________________________________________________
|
| 124 |
+
|
| 125 |
+
def label(code):
|
| 126 |
+
if isinstance(code, str):
|
| 127 |
+
return ('~', 0, code) # built-in functions ('~' sorts at the end)
|
| 128 |
+
else:
|
| 129 |
+
return (code.co_filename, code.co_firstlineno, code.co_name)
|
| 130 |
+
|
| 131 |
+
# ____________________________________________________________
|
| 132 |
+
|
| 133 |
+
def main():
|
| 134 |
+
import os
|
| 135 |
+
import sys
|
| 136 |
+
import runpy
|
| 137 |
+
import pstats
|
| 138 |
+
from optparse import OptionParser
|
| 139 |
+
usage = "cProfile.py [-o output_file_path] [-s sort] [-m module | scriptfile] [arg] ..."
|
| 140 |
+
parser = OptionParser(usage=usage)
|
| 141 |
+
parser.allow_interspersed_args = False
|
| 142 |
+
parser.add_option('-o', '--outfile', dest="outfile",
|
| 143 |
+
help="Save stats to <outfile>", default=None)
|
| 144 |
+
parser.add_option('-s', '--sort', dest="sort",
|
| 145 |
+
help="Sort order when printing to stdout, based on pstats.Stats class",
|
| 146 |
+
default=2,
|
| 147 |
+
choices=sorted(pstats.Stats.sort_arg_dict_default))
|
| 148 |
+
parser.add_option('-m', dest="module", action="store_true",
|
| 149 |
+
help="Profile a library module", default=False)
|
| 150 |
+
|
| 151 |
+
if not sys.argv[1:]:
|
| 152 |
+
parser.print_usage()
|
| 153 |
+
sys.exit(2)
|
| 154 |
+
|
| 155 |
+
(options, args) = parser.parse_args()
|
| 156 |
+
sys.argv[:] = args
|
| 157 |
+
|
| 158 |
+
# The script that we're profiling may chdir, so capture the absolute path
|
| 159 |
+
# to the output file at startup.
|
| 160 |
+
if options.outfile is not None:
|
| 161 |
+
options.outfile = os.path.abspath(options.outfile)
|
| 162 |
+
|
| 163 |
+
if len(args) > 0:
|
| 164 |
+
if options.module:
|
| 165 |
+
code = "run_module(modname, run_name='__main__')"
|
| 166 |
+
globs = {
|
| 167 |
+
'run_module': runpy.run_module,
|
| 168 |
+
'modname': args[0]
|
| 169 |
+
}
|
| 170 |
+
else:
|
| 171 |
+
progname = args[0]
|
| 172 |
+
sys.path.insert(0, os.path.dirname(progname))
|
| 173 |
+
with io.open_code(progname) as fp:
|
| 174 |
+
code = compile(fp.read(), progname, 'exec')
|
| 175 |
+
spec = importlib.machinery.ModuleSpec(name='__main__', loader=None,
|
| 176 |
+
origin=progname)
|
| 177 |
+
module = importlib.util.module_from_spec(spec)
|
| 178 |
+
# Set __main__ so that importing __main__ in the profiled code will
|
| 179 |
+
# return the same namespace that the code is executing under.
|
| 180 |
+
sys.modules['__main__'] = module
|
| 181 |
+
# Ensure that we're using the same __dict__ instance as the module
|
| 182 |
+
# for the global variables so that updates to globals are reflected
|
| 183 |
+
# in the module's namespace.
|
| 184 |
+
globs = module.__dict__
|
| 185 |
+
globs.update({
|
| 186 |
+
'__spec__': spec,
|
| 187 |
+
'__file__': spec.origin,
|
| 188 |
+
'__name__': spec.name,
|
| 189 |
+
'__package__': None,
|
| 190 |
+
'__cached__': None,
|
| 191 |
+
})
|
| 192 |
+
|
| 193 |
+
try:
|
| 194 |
+
runctx(code, globs, None, options.outfile, options.sort)
|
| 195 |
+
except BrokenPipeError as exc:
|
| 196 |
+
# Prevent "Exception ignored" during interpreter shutdown.
|
| 197 |
+
sys.stdout = None
|
| 198 |
+
sys.exit(exc.errno)
|
| 199 |
+
else:
|
| 200 |
+
parser.print_usage()
|
| 201 |
+
return parser
|
| 202 |
+
|
| 203 |
+
# When invoked as main program, invoke the profiler on a script
|
| 204 |
+
if __name__ == '__main__':
|
| 205 |
+
main()
|
micromamba_root/envs/hf_sync/Lib/calendar.py
ADDED
|
@@ -0,0 +1,926 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Calendar printing functions
|
| 2 |
+
|
| 3 |
+
Note when comparing these calendars to the ones printed by cal(1): By
|
| 4 |
+
default, these calendars have Monday as the first day of the week, and
|
| 5 |
+
Sunday as the last (the European convention). Use setfirstweekday() to
|
| 6 |
+
set the first day of the week (0=Monday, 6=Sunday)."""
|
| 7 |
+
|
| 8 |
+
import sys
|
| 9 |
+
import datetime
|
| 10 |
+
from enum import IntEnum, global_enum
|
| 11 |
+
import locale as _locale
|
| 12 |
+
from itertools import repeat
|
| 13 |
+
|
| 14 |
+
__all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday",
|
| 15 |
+
"firstweekday", "isleap", "leapdays", "weekday", "monthrange",
|
| 16 |
+
"monthcalendar", "prmonth", "month", "prcal", "calendar",
|
| 17 |
+
"timegm", "month_name", "month_abbr", "day_name", "day_abbr",
|
| 18 |
+
"Calendar", "TextCalendar", "HTMLCalendar", "LocaleTextCalendar",
|
| 19 |
+
"LocaleHTMLCalendar", "weekheader",
|
| 20 |
+
"Day", "Month", "JANUARY", "FEBRUARY", "MARCH",
|
| 21 |
+
"APRIL", "MAY", "JUNE", "JULY",
|
| 22 |
+
"AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER",
|
| 23 |
+
"MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY",
|
| 24 |
+
"SATURDAY", "SUNDAY"]
|
| 25 |
+
|
| 26 |
+
# Exception raised for bad input (with string parameter for details)
|
| 27 |
+
error = ValueError
|
| 28 |
+
|
| 29 |
+
# Exceptions raised for bad input
|
| 30 |
+
# This is trick for backward compatibility. Since 3.13, we will raise IllegalMonthError instead of
|
| 31 |
+
# IndexError for bad month number(out of 1-12). But we can't remove IndexError for backward compatibility.
|
| 32 |
+
class IllegalMonthError(ValueError, IndexError):
|
| 33 |
+
def __init__(self, month):
|
| 34 |
+
self.month = month
|
| 35 |
+
def __str__(self):
|
| 36 |
+
return "bad month number %r; must be 1-12" % self.month
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class IllegalWeekdayError(ValueError):
|
| 40 |
+
def __init__(self, weekday):
|
| 41 |
+
self.weekday = weekday
|
| 42 |
+
def __str__(self):
|
| 43 |
+
return "bad weekday number %r; must be 0 (Monday) to 6 (Sunday)" % self.weekday
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def __getattr__(name):
|
| 47 |
+
if name in ('January', 'February'):
|
| 48 |
+
import warnings
|
| 49 |
+
warnings.warn(f"The '{name}' attribute is deprecated, use '{name.upper()}' instead",
|
| 50 |
+
DeprecationWarning, stacklevel=2)
|
| 51 |
+
if name == 'January':
|
| 52 |
+
return 1
|
| 53 |
+
else:
|
| 54 |
+
return 2
|
| 55 |
+
|
| 56 |
+
raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# Constants for months
|
| 60 |
+
@global_enum
|
| 61 |
+
class Month(IntEnum):
|
| 62 |
+
JANUARY = 1
|
| 63 |
+
FEBRUARY = 2
|
| 64 |
+
MARCH = 3
|
| 65 |
+
APRIL = 4
|
| 66 |
+
MAY = 5
|
| 67 |
+
JUNE = 6
|
| 68 |
+
JULY = 7
|
| 69 |
+
AUGUST = 8
|
| 70 |
+
SEPTEMBER = 9
|
| 71 |
+
OCTOBER = 10
|
| 72 |
+
NOVEMBER = 11
|
| 73 |
+
DECEMBER = 12
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# Constants for days
|
| 77 |
+
@global_enum
|
| 78 |
+
class Day(IntEnum):
|
| 79 |
+
MONDAY = 0
|
| 80 |
+
TUESDAY = 1
|
| 81 |
+
WEDNESDAY = 2
|
| 82 |
+
THURSDAY = 3
|
| 83 |
+
FRIDAY = 4
|
| 84 |
+
SATURDAY = 5
|
| 85 |
+
SUNDAY = 6
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# Number of days per month (except for February in leap years)
|
| 89 |
+
mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
|
| 90 |
+
|
| 91 |
+
# This module used to have hard-coded lists of day and month names, as
|
| 92 |
+
# English strings. The classes following emulate a read-only version of
|
| 93 |
+
# that, but supply localized names. Note that the values are computed
|
| 94 |
+
# fresh on each call, in case the user changes locale between calls.
|
| 95 |
+
|
| 96 |
+
class _localized_month:
|
| 97 |
+
|
| 98 |
+
_months = [datetime.date(2001, i+1, 1).strftime for i in range(12)]
|
| 99 |
+
_months.insert(0, lambda x: "")
|
| 100 |
+
|
| 101 |
+
def __init__(self, format):
|
| 102 |
+
self.format = format
|
| 103 |
+
|
| 104 |
+
def __getitem__(self, i):
|
| 105 |
+
funcs = self._months[i]
|
| 106 |
+
if isinstance(i, slice):
|
| 107 |
+
return [f(self.format) for f in funcs]
|
| 108 |
+
else:
|
| 109 |
+
return funcs(self.format)
|
| 110 |
+
|
| 111 |
+
def __len__(self):
|
| 112 |
+
return 13
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class _localized_day:
|
| 116 |
+
|
| 117 |
+
# January 1, 2001, was a Monday.
|
| 118 |
+
_days = [datetime.date(2001, 1, i+1).strftime for i in range(7)]
|
| 119 |
+
|
| 120 |
+
def __init__(self, format):
|
| 121 |
+
self.format = format
|
| 122 |
+
|
| 123 |
+
def __getitem__(self, i):
|
| 124 |
+
funcs = self._days[i]
|
| 125 |
+
if isinstance(i, slice):
|
| 126 |
+
return [f(self.format) for f in funcs]
|
| 127 |
+
else:
|
| 128 |
+
return funcs(self.format)
|
| 129 |
+
|
| 130 |
+
def __len__(self):
|
| 131 |
+
return 7
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# Full and abbreviated names of weekdays
|
| 135 |
+
day_name = _localized_day('%A')
|
| 136 |
+
day_abbr = _localized_day('%a')
|
| 137 |
+
|
| 138 |
+
# Full and abbreviated names of months (1-based arrays!!!)
|
| 139 |
+
month_name = _localized_month('%B')
|
| 140 |
+
month_abbr = _localized_month('%b')
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def isleap(year):
|
| 144 |
+
"""Return True for leap years, False for non-leap years."""
|
| 145 |
+
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def leapdays(y1, y2):
|
| 149 |
+
"""Return number of leap years in range [y1, y2).
|
| 150 |
+
Assume y1 <= y2."""
|
| 151 |
+
y1 -= 1
|
| 152 |
+
y2 -= 1
|
| 153 |
+
return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def weekday(year, month, day):
|
| 157 |
+
"""Return weekday (0-6 ~ Mon-Sun) for year, month (1-12), day (1-31)."""
|
| 158 |
+
if not datetime.MINYEAR <= year <= datetime.MAXYEAR:
|
| 159 |
+
year = 2000 + year % 400
|
| 160 |
+
return Day(datetime.date(year, month, day).weekday())
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _validate_month(month):
|
| 164 |
+
if not 1 <= month <= 12:
|
| 165 |
+
raise IllegalMonthError(month)
|
| 166 |
+
|
| 167 |
+
def monthrange(year, month):
|
| 168 |
+
"""Return weekday of first day of month (0-6 ~ Mon-Sun)
|
| 169 |
+
and number of days (28-31) for year, month."""
|
| 170 |
+
_validate_month(month)
|
| 171 |
+
day1 = weekday(year, month, 1)
|
| 172 |
+
ndays = mdays[month] + (month == FEBRUARY and isleap(year))
|
| 173 |
+
return day1, ndays
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _monthlen(year, month):
|
| 177 |
+
return mdays[month] + (month == FEBRUARY and isleap(year))
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _prevmonth(year, month):
|
| 181 |
+
if month == 1:
|
| 182 |
+
return year-1, 12
|
| 183 |
+
else:
|
| 184 |
+
return year, month-1
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _nextmonth(year, month):
|
| 188 |
+
if month == 12:
|
| 189 |
+
return year+1, 1
|
| 190 |
+
else:
|
| 191 |
+
return year, month+1
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class Calendar(object):
|
| 195 |
+
"""
|
| 196 |
+
Base calendar class. This class doesn't do any formatting. It simply
|
| 197 |
+
provides data to subclasses.
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
def __init__(self, firstweekday=0):
|
| 201 |
+
self.firstweekday = firstweekday # 0 = Monday, 6 = Sunday
|
| 202 |
+
|
| 203 |
+
def getfirstweekday(self):
|
| 204 |
+
return self._firstweekday % 7
|
| 205 |
+
|
| 206 |
+
def setfirstweekday(self, firstweekday):
|
| 207 |
+
self._firstweekday = firstweekday
|
| 208 |
+
|
| 209 |
+
firstweekday = property(getfirstweekday, setfirstweekday)
|
| 210 |
+
|
| 211 |
+
def iterweekdays(self):
|
| 212 |
+
"""
|
| 213 |
+
Return an iterator for one week of weekday numbers starting with the
|
| 214 |
+
configured first one.
|
| 215 |
+
"""
|
| 216 |
+
for i in range(self.firstweekday, self.firstweekday + 7):
|
| 217 |
+
yield i%7
|
| 218 |
+
|
| 219 |
+
def itermonthdates(self, year, month):
|
| 220 |
+
"""
|
| 221 |
+
Return an iterator for one month. The iterator will yield datetime.date
|
| 222 |
+
values and will always iterate through complete weeks, so it will yield
|
| 223 |
+
dates outside the specified month.
|
| 224 |
+
"""
|
| 225 |
+
for y, m, d in self.itermonthdays3(year, month):
|
| 226 |
+
yield datetime.date(y, m, d)
|
| 227 |
+
|
| 228 |
+
def itermonthdays(self, year, month):
|
| 229 |
+
"""
|
| 230 |
+
Like itermonthdates(), but will yield day numbers. For days outside
|
| 231 |
+
the specified month the day number is 0.
|
| 232 |
+
"""
|
| 233 |
+
day1, ndays = monthrange(year, month)
|
| 234 |
+
days_before = (day1 - self.firstweekday) % 7
|
| 235 |
+
yield from repeat(0, days_before)
|
| 236 |
+
yield from range(1, ndays + 1)
|
| 237 |
+
days_after = (self.firstweekday - day1 - ndays) % 7
|
| 238 |
+
yield from repeat(0, days_after)
|
| 239 |
+
|
| 240 |
+
def itermonthdays2(self, year, month):
|
| 241 |
+
"""
|
| 242 |
+
Like itermonthdates(), but will yield (day number, weekday number)
|
| 243 |
+
tuples. For days outside the specified month the day number is 0.
|
| 244 |
+
"""
|
| 245 |
+
for i, d in enumerate(self.itermonthdays(year, month), self.firstweekday):
|
| 246 |
+
yield d, i % 7
|
| 247 |
+
|
| 248 |
+
def itermonthdays3(self, year, month):
|
| 249 |
+
"""
|
| 250 |
+
Like itermonthdates(), but will yield (year, month, day) tuples. Can be
|
| 251 |
+
used for dates outside of datetime.date range.
|
| 252 |
+
"""
|
| 253 |
+
day1, ndays = monthrange(year, month)
|
| 254 |
+
days_before = (day1 - self.firstweekday) % 7
|
| 255 |
+
days_after = (self.firstweekday - day1 - ndays) % 7
|
| 256 |
+
y, m = _prevmonth(year, month)
|
| 257 |
+
end = _monthlen(y, m) + 1
|
| 258 |
+
for d in range(end-days_before, end):
|
| 259 |
+
yield y, m, d
|
| 260 |
+
for d in range(1, ndays + 1):
|
| 261 |
+
yield year, month, d
|
| 262 |
+
y, m = _nextmonth(year, month)
|
| 263 |
+
for d in range(1, days_after + 1):
|
| 264 |
+
yield y, m, d
|
| 265 |
+
|
| 266 |
+
def itermonthdays4(self, year, month):
|
| 267 |
+
"""
|
| 268 |
+
Like itermonthdates(), but will yield (year, month, day, day_of_week) tuples.
|
| 269 |
+
Can be used for dates outside of datetime.date range.
|
| 270 |
+
"""
|
| 271 |
+
for i, (y, m, d) in enumerate(self.itermonthdays3(year, month)):
|
| 272 |
+
yield y, m, d, (self.firstweekday + i) % 7
|
| 273 |
+
|
| 274 |
+
def monthdatescalendar(self, year, month):
|
| 275 |
+
"""
|
| 276 |
+
Return a matrix (list of lists) representing a month's calendar.
|
| 277 |
+
Each row represents a week; week entries are datetime.date values.
|
| 278 |
+
"""
|
| 279 |
+
dates = list(self.itermonthdates(year, month))
|
| 280 |
+
return [ dates[i:i+7] for i in range(0, len(dates), 7) ]
|
| 281 |
+
|
| 282 |
+
def monthdays2calendar(self, year, month):
|
| 283 |
+
"""
|
| 284 |
+
Return a matrix representing a month's calendar.
|
| 285 |
+
Each row represents a week; week entries are
|
| 286 |
+
(day number, weekday number) tuples. Day numbers outside this month
|
| 287 |
+
are zero.
|
| 288 |
+
"""
|
| 289 |
+
days = list(self.itermonthdays2(year, month))
|
| 290 |
+
return [ days[i:i+7] for i in range(0, len(days), 7) ]
|
| 291 |
+
|
| 292 |
+
def monthdayscalendar(self, year, month):
|
| 293 |
+
"""
|
| 294 |
+
Return a matrix representing a month's calendar.
|
| 295 |
+
Each row represents a week; days outside this month are zero.
|
| 296 |
+
"""
|
| 297 |
+
days = list(self.itermonthdays(year, month))
|
| 298 |
+
return [ days[i:i+7] for i in range(0, len(days), 7) ]
|
| 299 |
+
|
| 300 |
+
def yeardatescalendar(self, year, width=3):
|
| 301 |
+
"""
|
| 302 |
+
Return the data for the specified year ready for formatting. The return
|
| 303 |
+
value is a list of month rows. Each month row contains up to width months.
|
| 304 |
+
Each month contains between 4 and 6 weeks and each week contains 1-7
|
| 305 |
+
days. Days are datetime.date objects.
|
| 306 |
+
"""
|
| 307 |
+
months = [self.monthdatescalendar(year, m) for m in Month]
|
| 308 |
+
return [months[i:i+width] for i in range(0, len(months), width) ]
|
| 309 |
+
|
| 310 |
+
def yeardays2calendar(self, year, width=3):
|
| 311 |
+
"""
|
| 312 |
+
Return the data for the specified year ready for formatting (similar to
|
| 313 |
+
yeardatescalendar()). Entries in the week lists are
|
| 314 |
+
(day number, weekday number) tuples. Day numbers outside this month are
|
| 315 |
+
zero.
|
| 316 |
+
"""
|
| 317 |
+
months = [self.monthdays2calendar(year, m) for m in Month]
|
| 318 |
+
return [months[i:i+width] for i in range(0, len(months), width) ]
|
| 319 |
+
|
| 320 |
+
def yeardayscalendar(self, year, width=3):
|
| 321 |
+
"""
|
| 322 |
+
Return the data for the specified year ready for formatting (similar to
|
| 323 |
+
yeardatescalendar()). Entries in the week lists are day numbers.
|
| 324 |
+
Day numbers outside this month are zero.
|
| 325 |
+
"""
|
| 326 |
+
months = [self.monthdayscalendar(year, m) for m in Month]
|
| 327 |
+
return [months[i:i+width] for i in range(0, len(months), width) ]
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class TextCalendar(Calendar):
|
| 331 |
+
"""
|
| 332 |
+
Subclass of Calendar that outputs a calendar as a simple plain text
|
| 333 |
+
similar to the UNIX program cal.
|
| 334 |
+
"""
|
| 335 |
+
|
| 336 |
+
def prweek(self, theweek, width):
|
| 337 |
+
"""
|
| 338 |
+
Print a single week (no newline).
|
| 339 |
+
"""
|
| 340 |
+
print(self.formatweek(theweek, width), end='')
|
| 341 |
+
|
| 342 |
+
def formatday(self, day, weekday, width):
|
| 343 |
+
"""
|
| 344 |
+
Returns a formatted day.
|
| 345 |
+
"""
|
| 346 |
+
if day == 0:
|
| 347 |
+
s = ''
|
| 348 |
+
else:
|
| 349 |
+
s = '%2i' % day # right-align single-digit days
|
| 350 |
+
return s.center(width)
|
| 351 |
+
|
| 352 |
+
def formatweek(self, theweek, width):
|
| 353 |
+
"""
|
| 354 |
+
Returns a single week in a string (no newline).
|
| 355 |
+
"""
|
| 356 |
+
return ' '.join(self.formatday(d, wd, width) for (d, wd) in theweek)
|
| 357 |
+
|
| 358 |
+
def formatweekday(self, day, width):
|
| 359 |
+
"""
|
| 360 |
+
Returns a formatted week day name.
|
| 361 |
+
"""
|
| 362 |
+
if width >= 9:
|
| 363 |
+
names = day_name
|
| 364 |
+
else:
|
| 365 |
+
names = day_abbr
|
| 366 |
+
return names[day][:width].center(width)
|
| 367 |
+
|
| 368 |
+
def formatweekheader(self, width):
|
| 369 |
+
"""
|
| 370 |
+
Return a header for a week.
|
| 371 |
+
"""
|
| 372 |
+
return ' '.join(self.formatweekday(i, width) for i in self.iterweekdays())
|
| 373 |
+
|
| 374 |
+
def formatmonthname(self, theyear, themonth, width, withyear=True):
|
| 375 |
+
"""
|
| 376 |
+
Return a formatted month name.
|
| 377 |
+
"""
|
| 378 |
+
_validate_month(themonth)
|
| 379 |
+
|
| 380 |
+
s = month_name[themonth]
|
| 381 |
+
if withyear:
|
| 382 |
+
s = "%s %r" % (s, theyear)
|
| 383 |
+
return s.center(width)
|
| 384 |
+
|
| 385 |
+
def prmonth(self, theyear, themonth, w=0, l=0):
|
| 386 |
+
"""
|
| 387 |
+
Print a month's calendar.
|
| 388 |
+
"""
|
| 389 |
+
print(self.formatmonth(theyear, themonth, w, l), end='')
|
| 390 |
+
|
| 391 |
+
def formatmonth(self, theyear, themonth, w=0, l=0):
|
| 392 |
+
"""
|
| 393 |
+
Return a month's calendar string (multi-line).
|
| 394 |
+
"""
|
| 395 |
+
w = max(2, w)
|
| 396 |
+
l = max(1, l)
|
| 397 |
+
s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1)
|
| 398 |
+
s = s.rstrip()
|
| 399 |
+
s += '\n' * l
|
| 400 |
+
s += self.formatweekheader(w).rstrip()
|
| 401 |
+
s += '\n' * l
|
| 402 |
+
for week in self.monthdays2calendar(theyear, themonth):
|
| 403 |
+
s += self.formatweek(week, w).rstrip()
|
| 404 |
+
s += '\n' * l
|
| 405 |
+
return s
|
| 406 |
+
|
| 407 |
+
def formatyear(self, theyear, w=2, l=1, c=6, m=3):
|
| 408 |
+
"""
|
| 409 |
+
Returns a year's calendar as a multi-line string.
|
| 410 |
+
"""
|
| 411 |
+
w = max(2, w)
|
| 412 |
+
l = max(1, l)
|
| 413 |
+
c = max(2, c)
|
| 414 |
+
colwidth = (w + 1) * 7 - 1
|
| 415 |
+
v = []
|
| 416 |
+
a = v.append
|
| 417 |
+
a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip())
|
| 418 |
+
a('\n'*l)
|
| 419 |
+
header = self.formatweekheader(w)
|
| 420 |
+
for (i, row) in enumerate(self.yeardays2calendar(theyear, m)):
|
| 421 |
+
# months in this row
|
| 422 |
+
months = range(m*i+1, min(m*(i+1)+1, 13))
|
| 423 |
+
a('\n'*l)
|
| 424 |
+
names = (self.formatmonthname(theyear, k, colwidth, False)
|
| 425 |
+
for k in months)
|
| 426 |
+
a(formatstring(names, colwidth, c).rstrip())
|
| 427 |
+
a('\n'*l)
|
| 428 |
+
headers = (header for k in months)
|
| 429 |
+
a(formatstring(headers, colwidth, c).rstrip())
|
| 430 |
+
a('\n'*l)
|
| 431 |
+
|
| 432 |
+
# max number of weeks for this row
|
| 433 |
+
height = max(len(cal) for cal in row)
|
| 434 |
+
for j in range(height):
|
| 435 |
+
weeks = []
|
| 436 |
+
for cal in row:
|
| 437 |
+
if j >= len(cal):
|
| 438 |
+
weeks.append('')
|
| 439 |
+
else:
|
| 440 |
+
weeks.append(self.formatweek(cal[j], w))
|
| 441 |
+
a(formatstring(weeks, colwidth, c).rstrip())
|
| 442 |
+
a('\n' * l)
|
| 443 |
+
return ''.join(v)
|
| 444 |
+
|
| 445 |
+
def pryear(self, theyear, w=0, l=0, c=6, m=3):
|
| 446 |
+
"""Print a year's calendar."""
|
| 447 |
+
print(self.formatyear(theyear, w, l, c, m), end='')
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
class HTMLCalendar(Calendar):
|
| 451 |
+
"""
|
| 452 |
+
This calendar returns complete HTML pages.
|
| 453 |
+
"""
|
| 454 |
+
|
| 455 |
+
# CSS classes for the day <td>s
|
| 456 |
+
cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
|
| 457 |
+
|
| 458 |
+
# CSS classes for the day <th>s
|
| 459 |
+
cssclasses_weekday_head = cssclasses
|
| 460 |
+
|
| 461 |
+
# CSS class for the days before and after current month
|
| 462 |
+
cssclass_noday = "noday"
|
| 463 |
+
|
| 464 |
+
# CSS class for the month's head
|
| 465 |
+
cssclass_month_head = "month"
|
| 466 |
+
|
| 467 |
+
# CSS class for the month
|
| 468 |
+
cssclass_month = "month"
|
| 469 |
+
|
| 470 |
+
# CSS class for the year's table head
|
| 471 |
+
cssclass_year_head = "year"
|
| 472 |
+
|
| 473 |
+
# CSS class for the whole year table
|
| 474 |
+
cssclass_year = "year"
|
| 475 |
+
|
| 476 |
+
def formatday(self, day, weekday):
|
| 477 |
+
"""
|
| 478 |
+
Return a day as a table cell.
|
| 479 |
+
"""
|
| 480 |
+
if day == 0:
|
| 481 |
+
# day outside month
|
| 482 |
+
return '<td class="%s"> </td>' % self.cssclass_noday
|
| 483 |
+
else:
|
| 484 |
+
return '<td class="%s">%d</td>' % (self.cssclasses[weekday], day)
|
| 485 |
+
|
| 486 |
+
def formatweek(self, theweek):
|
| 487 |
+
"""
|
| 488 |
+
Return a complete week as a table row.
|
| 489 |
+
"""
|
| 490 |
+
s = ''.join(self.formatday(d, wd) for (d, wd) in theweek)
|
| 491 |
+
return '<tr>%s</tr>' % s
|
| 492 |
+
|
| 493 |
+
def formatweekday(self, day):
|
| 494 |
+
"""
|
| 495 |
+
Return a weekday name as a table header.
|
| 496 |
+
"""
|
| 497 |
+
return '<th class="%s">%s</th>' % (
|
| 498 |
+
self.cssclasses_weekday_head[day], day_abbr[day])
|
| 499 |
+
|
| 500 |
+
def formatweekheader(self):
|
| 501 |
+
"""
|
| 502 |
+
Return a header for a week as a table row.
|
| 503 |
+
"""
|
| 504 |
+
s = ''.join(self.formatweekday(i) for i in self.iterweekdays())
|
| 505 |
+
return '<tr>%s</tr>' % s
|
| 506 |
+
|
| 507 |
+
def formatmonthname(self, theyear, themonth, withyear=True):
|
| 508 |
+
"""
|
| 509 |
+
Return a month name as a table row.
|
| 510 |
+
"""
|
| 511 |
+
_validate_month(themonth)
|
| 512 |
+
if withyear:
|
| 513 |
+
s = '%s %s' % (month_name[themonth], theyear)
|
| 514 |
+
else:
|
| 515 |
+
s = '%s' % month_name[themonth]
|
| 516 |
+
return '<tr><th colspan="7" class="%s">%s</th></tr>' % (
|
| 517 |
+
self.cssclass_month_head, s)
|
| 518 |
+
|
| 519 |
+
def formatmonth(self, theyear, themonth, withyear=True):
|
| 520 |
+
"""
|
| 521 |
+
Return a formatted month as a table.
|
| 522 |
+
"""
|
| 523 |
+
v = []
|
| 524 |
+
a = v.append
|
| 525 |
+
a('<table border="0" cellpadding="0" cellspacing="0" class="%s">' % (
|
| 526 |
+
self.cssclass_month))
|
| 527 |
+
a('\n')
|
| 528 |
+
a(self.formatmonthname(theyear, themonth, withyear=withyear))
|
| 529 |
+
a('\n')
|
| 530 |
+
a(self.formatweekheader())
|
| 531 |
+
a('\n')
|
| 532 |
+
for week in self.monthdays2calendar(theyear, themonth):
|
| 533 |
+
a(self.formatweek(week))
|
| 534 |
+
a('\n')
|
| 535 |
+
a('</table>')
|
| 536 |
+
a('\n')
|
| 537 |
+
return ''.join(v)
|
| 538 |
+
|
| 539 |
+
def formatyear(self, theyear, width=3):
|
| 540 |
+
"""
|
| 541 |
+
Return a formatted year as a table of tables.
|
| 542 |
+
"""
|
| 543 |
+
v = []
|
| 544 |
+
a = v.append
|
| 545 |
+
width = max(width, 1)
|
| 546 |
+
a('<table border="0" cellpadding="0" cellspacing="0" class="%s">' %
|
| 547 |
+
self.cssclass_year)
|
| 548 |
+
a('\n')
|
| 549 |
+
a('<tr><th colspan="%d" class="%s">%s</th></tr>' % (
|
| 550 |
+
width, self.cssclass_year_head, theyear))
|
| 551 |
+
for i in range(JANUARY, JANUARY+12, width):
|
| 552 |
+
# months in this row
|
| 553 |
+
months = range(i, min(i+width, 13))
|
| 554 |
+
a('<tr>')
|
| 555 |
+
for m in months:
|
| 556 |
+
a('<td>')
|
| 557 |
+
a(self.formatmonth(theyear, m, withyear=False))
|
| 558 |
+
a('</td>')
|
| 559 |
+
a('</tr>')
|
| 560 |
+
a('</table>')
|
| 561 |
+
return ''.join(v)
|
| 562 |
+
|
| 563 |
+
def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None):
|
| 564 |
+
"""
|
| 565 |
+
Return a formatted year as a complete HTML page.
|
| 566 |
+
"""
|
| 567 |
+
if encoding is None:
|
| 568 |
+
encoding = sys.getdefaultencoding()
|
| 569 |
+
v = []
|
| 570 |
+
a = v.append
|
| 571 |
+
a('<?xml version="1.0" encoding="%s"?>\n' % encoding)
|
| 572 |
+
a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n')
|
| 573 |
+
a('<html>\n')
|
| 574 |
+
a('<head>\n')
|
| 575 |
+
a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding)
|
| 576 |
+
if css is not None:
|
| 577 |
+
a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css)
|
| 578 |
+
a('<title>Calendar for %d</title>\n' % theyear)
|
| 579 |
+
a('</head>\n')
|
| 580 |
+
a('<body>\n')
|
| 581 |
+
a(self.formatyear(theyear, width))
|
| 582 |
+
a('</body>\n')
|
| 583 |
+
a('</html>\n')
|
| 584 |
+
return ''.join(v).encode(encoding, "xmlcharrefreplace")
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
class different_locale:
|
| 588 |
+
def __init__(self, locale):
|
| 589 |
+
self.locale = locale
|
| 590 |
+
self.oldlocale = None
|
| 591 |
+
|
| 592 |
+
def __enter__(self):
|
| 593 |
+
self.oldlocale = _locale.setlocale(_locale.LC_TIME, None)
|
| 594 |
+
_locale.setlocale(_locale.LC_TIME, self.locale)
|
| 595 |
+
|
| 596 |
+
def __exit__(self, *args):
|
| 597 |
+
_locale.setlocale(_locale.LC_TIME, self.oldlocale)
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
def _get_default_locale():
|
| 601 |
+
locale = _locale.setlocale(_locale.LC_TIME, None)
|
| 602 |
+
if locale == "C":
|
| 603 |
+
with different_locale(""):
|
| 604 |
+
# The LC_TIME locale does not seem to be configured:
|
| 605 |
+
# get the user preferred locale.
|
| 606 |
+
locale = _locale.setlocale(_locale.LC_TIME, None)
|
| 607 |
+
return locale
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
class LocaleTextCalendar(TextCalendar):
|
| 611 |
+
"""
|
| 612 |
+
This class can be passed a locale name in the constructor and will return
|
| 613 |
+
month and weekday names in the specified locale.
|
| 614 |
+
"""
|
| 615 |
+
|
| 616 |
+
def __init__(self, firstweekday=0, locale=None):
|
| 617 |
+
TextCalendar.__init__(self, firstweekday)
|
| 618 |
+
if locale is None:
|
| 619 |
+
locale = _get_default_locale()
|
| 620 |
+
self.locale = locale
|
| 621 |
+
|
| 622 |
+
def formatweekday(self, day, width):
|
| 623 |
+
with different_locale(self.locale):
|
| 624 |
+
return super().formatweekday(day, width)
|
| 625 |
+
|
| 626 |
+
def formatmonthname(self, theyear, themonth, width, withyear=True):
|
| 627 |
+
with different_locale(self.locale):
|
| 628 |
+
return super().formatmonthname(theyear, themonth, width, withyear)
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
class LocaleHTMLCalendar(HTMLCalendar):
|
| 632 |
+
"""
|
| 633 |
+
This class can be passed a locale name in the constructor and will return
|
| 634 |
+
month and weekday names in the specified locale.
|
| 635 |
+
"""
|
| 636 |
+
def __init__(self, firstweekday=0, locale=None):
|
| 637 |
+
HTMLCalendar.__init__(self, firstweekday)
|
| 638 |
+
if locale is None:
|
| 639 |
+
locale = _get_default_locale()
|
| 640 |
+
self.locale = locale
|
| 641 |
+
|
| 642 |
+
def formatweekday(self, day):
|
| 643 |
+
with different_locale(self.locale):
|
| 644 |
+
return super().formatweekday(day)
|
| 645 |
+
|
| 646 |
+
def formatmonthname(self, theyear, themonth, withyear=True):
|
| 647 |
+
with different_locale(self.locale):
|
| 648 |
+
return super().formatmonthname(theyear, themonth, withyear)
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
class _CLIDemoCalendar(TextCalendar):
|
| 652 |
+
def __init__(self, highlight_day=None, *args, **kwargs):
|
| 653 |
+
super().__init__(*args, **kwargs)
|
| 654 |
+
self.highlight_day = highlight_day
|
| 655 |
+
|
| 656 |
+
def formatweek(self, theweek, width, *, highlight_day=None):
|
| 657 |
+
"""
|
| 658 |
+
Returns a single week in a string (no newline).
|
| 659 |
+
"""
|
| 660 |
+
if highlight_day:
|
| 661 |
+
from _colorize import get_colors
|
| 662 |
+
|
| 663 |
+
ansi = get_colors()
|
| 664 |
+
highlight = f"{ansi.BLACK}{ansi.BACKGROUND_YELLOW}"
|
| 665 |
+
reset = ansi.RESET
|
| 666 |
+
else:
|
| 667 |
+
highlight = reset = ""
|
| 668 |
+
|
| 669 |
+
return ' '.join(
|
| 670 |
+
(
|
| 671 |
+
f"{highlight}{self.formatday(d, wd, width)}{reset}"
|
| 672 |
+
if d == highlight_day
|
| 673 |
+
else self.formatday(d, wd, width)
|
| 674 |
+
)
|
| 675 |
+
for (d, wd) in theweek
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
def formatmonth(self, theyear, themonth, w=0, l=0):
|
| 679 |
+
"""
|
| 680 |
+
Return a month's calendar string (multi-line).
|
| 681 |
+
"""
|
| 682 |
+
if (
|
| 683 |
+
self.highlight_day
|
| 684 |
+
and self.highlight_day.year == theyear
|
| 685 |
+
and self.highlight_day.month == themonth
|
| 686 |
+
):
|
| 687 |
+
highlight_day = self.highlight_day.day
|
| 688 |
+
else:
|
| 689 |
+
highlight_day = None
|
| 690 |
+
w = max(2, w)
|
| 691 |
+
l = max(1, l)
|
| 692 |
+
s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1)
|
| 693 |
+
s = s.rstrip()
|
| 694 |
+
s += '\n' * l
|
| 695 |
+
s += self.formatweekheader(w).rstrip()
|
| 696 |
+
s += '\n' * l
|
| 697 |
+
for week in self.monthdays2calendar(theyear, themonth):
|
| 698 |
+
s += self.formatweek(week, w, highlight_day=highlight_day).rstrip()
|
| 699 |
+
s += '\n' * l
|
| 700 |
+
return s
|
| 701 |
+
|
| 702 |
+
def formatyear(self, theyear, w=2, l=1, c=6, m=3):
|
| 703 |
+
"""
|
| 704 |
+
Returns a year's calendar as a multi-line string.
|
| 705 |
+
"""
|
| 706 |
+
w = max(2, w)
|
| 707 |
+
l = max(1, l)
|
| 708 |
+
c = max(2, c)
|
| 709 |
+
colwidth = (w + 1) * 7 - 1
|
| 710 |
+
v = []
|
| 711 |
+
a = v.append
|
| 712 |
+
a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip())
|
| 713 |
+
a('\n'*l)
|
| 714 |
+
header = self.formatweekheader(w)
|
| 715 |
+
for (i, row) in enumerate(self.yeardays2calendar(theyear, m)):
|
| 716 |
+
# months in this row
|
| 717 |
+
months = range(m*i+1, min(m*(i+1)+1, 13))
|
| 718 |
+
a('\n'*l)
|
| 719 |
+
names = (self.formatmonthname(theyear, k, colwidth, False)
|
| 720 |
+
for k in months)
|
| 721 |
+
a(formatstring(names, colwidth, c).rstrip())
|
| 722 |
+
a('\n'*l)
|
| 723 |
+
headers = (header for k in months)
|
| 724 |
+
a(formatstring(headers, colwidth, c).rstrip())
|
| 725 |
+
a('\n'*l)
|
| 726 |
+
|
| 727 |
+
if (
|
| 728 |
+
self.highlight_day
|
| 729 |
+
and self.highlight_day.year == theyear
|
| 730 |
+
and self.highlight_day.month in months
|
| 731 |
+
):
|
| 732 |
+
month_pos = months.index(self.highlight_day.month)
|
| 733 |
+
else:
|
| 734 |
+
month_pos = None
|
| 735 |
+
|
| 736 |
+
# max number of weeks for this row
|
| 737 |
+
height = max(len(cal) for cal in row)
|
| 738 |
+
for j in range(height):
|
| 739 |
+
weeks = []
|
| 740 |
+
for k, cal in enumerate(row):
|
| 741 |
+
if j >= len(cal):
|
| 742 |
+
weeks.append('')
|
| 743 |
+
else:
|
| 744 |
+
day = (
|
| 745 |
+
self.highlight_day.day if k == month_pos else None
|
| 746 |
+
)
|
| 747 |
+
weeks.append(
|
| 748 |
+
self.formatweek(cal[j], w, highlight_day=day)
|
| 749 |
+
)
|
| 750 |
+
a(formatstring(weeks, colwidth, c).rstrip())
|
| 751 |
+
a('\n' * l)
|
| 752 |
+
return ''.join(v)
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
class _CLIDemoLocaleCalendar(LocaleTextCalendar, _CLIDemoCalendar):
|
| 756 |
+
def __init__(self, highlight_day=None, *args, **kwargs):
|
| 757 |
+
super().__init__(*args, **kwargs)
|
| 758 |
+
self.highlight_day = highlight_day
|
| 759 |
+
|
| 760 |
+
|
| 761 |
+
# Support for old module level interface
|
| 762 |
+
c = TextCalendar()
|
| 763 |
+
|
| 764 |
+
firstweekday = c.getfirstweekday
|
| 765 |
+
|
| 766 |
+
def setfirstweekday(firstweekday):
|
| 767 |
+
if not MONDAY <= firstweekday <= SUNDAY:
|
| 768 |
+
raise IllegalWeekdayError(firstweekday)
|
| 769 |
+
c.firstweekday = firstweekday
|
| 770 |
+
|
| 771 |
+
monthcalendar = c.monthdayscalendar
|
| 772 |
+
prweek = c.prweek
|
| 773 |
+
week = c.formatweek
|
| 774 |
+
weekheader = c.formatweekheader
|
| 775 |
+
prmonth = c.prmonth
|
| 776 |
+
month = c.formatmonth
|
| 777 |
+
calendar = c.formatyear
|
| 778 |
+
prcal = c.pryear
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
# Spacing of month columns for multi-column year calendar
|
| 782 |
+
_colwidth = 7*3 - 1 # Amount printed by prweek()
|
| 783 |
+
_spacing = 6 # Number of spaces between columns
|
| 784 |
+
|
| 785 |
+
|
| 786 |
+
def format(cols, colwidth=_colwidth, spacing=_spacing):
|
| 787 |
+
"""Prints multi-column formatting for year calendars"""
|
| 788 |
+
print(formatstring(cols, colwidth, spacing))
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
def formatstring(cols, colwidth=_colwidth, spacing=_spacing):
|
| 792 |
+
"""Returns a string formatted from n strings, centered within n columns."""
|
| 793 |
+
spacing *= ' '
|
| 794 |
+
return spacing.join(c.center(colwidth) for c in cols)
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
EPOCH = 1970
|
| 798 |
+
_EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal()
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
def timegm(tuple):
|
| 802 |
+
"""Unrelated but handy function to calculate Unix timestamp from GMT."""
|
| 803 |
+
year, month, day, hour, minute, second = tuple[:6]
|
| 804 |
+
days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1
|
| 805 |
+
hours = days*24 + hour
|
| 806 |
+
minutes = hours*60 + minute
|
| 807 |
+
seconds = minutes*60 + second
|
| 808 |
+
return seconds
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
def main(args=None):
|
| 812 |
+
import argparse
|
| 813 |
+
parser = argparse.ArgumentParser(color=True)
|
| 814 |
+
textgroup = parser.add_argument_group('text only arguments')
|
| 815 |
+
htmlgroup = parser.add_argument_group('html only arguments')
|
| 816 |
+
textgroup.add_argument(
|
| 817 |
+
"-w", "--width",
|
| 818 |
+
type=int, default=2,
|
| 819 |
+
help="width of date column (default 2)"
|
| 820 |
+
)
|
| 821 |
+
textgroup.add_argument(
|
| 822 |
+
"-l", "--lines",
|
| 823 |
+
type=int, default=1,
|
| 824 |
+
help="number of lines for each week (default 1)"
|
| 825 |
+
)
|
| 826 |
+
textgroup.add_argument(
|
| 827 |
+
"-s", "--spacing",
|
| 828 |
+
type=int, default=6,
|
| 829 |
+
help="spacing between months (default 6)"
|
| 830 |
+
)
|
| 831 |
+
textgroup.add_argument(
|
| 832 |
+
"-m", "--months",
|
| 833 |
+
type=int, default=3,
|
| 834 |
+
help="months per row (default 3)"
|
| 835 |
+
)
|
| 836 |
+
htmlgroup.add_argument(
|
| 837 |
+
"-c", "--css",
|
| 838 |
+
default="calendar.css",
|
| 839 |
+
help="CSS to use for page"
|
| 840 |
+
)
|
| 841 |
+
parser.add_argument(
|
| 842 |
+
"-L", "--locale",
|
| 843 |
+
default=None,
|
| 844 |
+
help="locale to use for month and weekday names"
|
| 845 |
+
)
|
| 846 |
+
parser.add_argument(
|
| 847 |
+
"-e", "--encoding",
|
| 848 |
+
default=None,
|
| 849 |
+
help="encoding to use for output"
|
| 850 |
+
)
|
| 851 |
+
parser.add_argument(
|
| 852 |
+
"-t", "--type",
|
| 853 |
+
default="text",
|
| 854 |
+
choices=("text", "html"),
|
| 855 |
+
help="output type (text or html)"
|
| 856 |
+
)
|
| 857 |
+
parser.add_argument(
|
| 858 |
+
"-f", "--first-weekday",
|
| 859 |
+
type=int, default=0,
|
| 860 |
+
help="weekday (0 is Monday, 6 is Sunday) to start each week (default 0)"
|
| 861 |
+
)
|
| 862 |
+
parser.add_argument(
|
| 863 |
+
"year",
|
| 864 |
+
nargs='?', type=int,
|
| 865 |
+
help="year number"
|
| 866 |
+
)
|
| 867 |
+
parser.add_argument(
|
| 868 |
+
"month",
|
| 869 |
+
nargs='?', type=int,
|
| 870 |
+
help="month number (1-12, text only)"
|
| 871 |
+
)
|
| 872 |
+
|
| 873 |
+
options = parser.parse_args(args)
|
| 874 |
+
|
| 875 |
+
if options.locale and not options.encoding:
|
| 876 |
+
parser.error("if --locale is specified --encoding is required")
|
| 877 |
+
sys.exit(1)
|
| 878 |
+
|
| 879 |
+
locale = options.locale, options.encoding
|
| 880 |
+
today = datetime.date.today()
|
| 881 |
+
|
| 882 |
+
if options.type == "html":
|
| 883 |
+
if options.month:
|
| 884 |
+
parser.error("incorrect number of arguments")
|
| 885 |
+
sys.exit(1)
|
| 886 |
+
if options.locale:
|
| 887 |
+
cal = LocaleHTMLCalendar(locale=locale)
|
| 888 |
+
else:
|
| 889 |
+
cal = HTMLCalendar()
|
| 890 |
+
cal.setfirstweekday(options.first_weekday)
|
| 891 |
+
encoding = options.encoding
|
| 892 |
+
if encoding is None:
|
| 893 |
+
encoding = sys.getdefaultencoding()
|
| 894 |
+
optdict = dict(encoding=encoding, css=options.css)
|
| 895 |
+
write = sys.stdout.buffer.write
|
| 896 |
+
if options.year is None:
|
| 897 |
+
write(cal.formatyearpage(today.year, **optdict))
|
| 898 |
+
else:
|
| 899 |
+
write(cal.formatyearpage(options.year, **optdict))
|
| 900 |
+
else:
|
| 901 |
+
if options.locale:
|
| 902 |
+
cal = _CLIDemoLocaleCalendar(highlight_day=today, locale=locale)
|
| 903 |
+
else:
|
| 904 |
+
cal = _CLIDemoCalendar(highlight_day=today)
|
| 905 |
+
cal.setfirstweekday(options.first_weekday)
|
| 906 |
+
optdict = dict(w=options.width, l=options.lines)
|
| 907 |
+
if options.month is None:
|
| 908 |
+
optdict["c"] = options.spacing
|
| 909 |
+
optdict["m"] = options.months
|
| 910 |
+
else:
|
| 911 |
+
_validate_month(options.month)
|
| 912 |
+
if options.year is None:
|
| 913 |
+
result = cal.formatyear(today.year, **optdict)
|
| 914 |
+
elif options.month is None:
|
| 915 |
+
result = cal.formatyear(options.year, **optdict)
|
| 916 |
+
else:
|
| 917 |
+
result = cal.formatmonth(options.year, options.month, **optdict)
|
| 918 |
+
write = sys.stdout.write
|
| 919 |
+
if options.encoding:
|
| 920 |
+
result = result.encode(options.encoding)
|
| 921 |
+
write = sys.stdout.buffer.write
|
| 922 |
+
write(result)
|
| 923 |
+
|
| 924 |
+
|
| 925 |
+
if __name__ == "__main__":
|
| 926 |
+
main()
|
micromamba_root/envs/hf_sync/Lib/cmd.py
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A generic class to build line-oriented command interpreters.
|
| 2 |
+
|
| 3 |
+
Interpreters constructed with this class obey the following conventions:
|
| 4 |
+
|
| 5 |
+
1. End of file on input is processed as the command 'EOF'.
|
| 6 |
+
2. A command is parsed out of each line by collecting the prefix composed
|
| 7 |
+
of characters in the identchars member.
|
| 8 |
+
3. A command 'foo' is dispatched to a method 'do_foo()'; the do_ method
|
| 9 |
+
is passed a single argument consisting of the remainder of the line.
|
| 10 |
+
4. Typing an empty line repeats the last command. (Actually, it calls the
|
| 11 |
+
method 'emptyline', which may be overridden in a subclass.)
|
| 12 |
+
5. There is a predefined 'help' method. Given an argument 'topic', it
|
| 13 |
+
calls the command 'help_topic'. With no arguments, it lists all topics
|
| 14 |
+
with defined help_ functions, broken into up to three topics; documented
|
| 15 |
+
commands, miscellaneous help topics, and undocumented commands.
|
| 16 |
+
6. The command '?' is a synonym for 'help'. The command '!' is a synonym
|
| 17 |
+
for 'shell', if a do_shell method exists.
|
| 18 |
+
7. If completion is enabled, completing commands will be done automatically,
|
| 19 |
+
and completing of commands args is done by calling complete_foo() with
|
| 20 |
+
arguments text, line, begidx, endidx. text is string we are matching
|
| 21 |
+
against, all returned matches must begin with it. line is the current
|
| 22 |
+
input line (lstripped), begidx and endidx are the beginning and end
|
| 23 |
+
indexes of the text being matched, which could be used to provide
|
| 24 |
+
different completion depending upon which position the argument is in.
|
| 25 |
+
|
| 26 |
+
The 'default' method may be overridden to intercept commands for which there
|
| 27 |
+
is no do_ method.
|
| 28 |
+
|
| 29 |
+
The 'completedefault' method may be overridden to intercept completions for
|
| 30 |
+
commands that have no complete_ method.
|
| 31 |
+
|
| 32 |
+
The data member 'self.ruler' sets the character used to draw separator lines
|
| 33 |
+
in the help messages. If empty, no ruler line is drawn. It defaults to "=".
|
| 34 |
+
|
| 35 |
+
If the value of 'self.intro' is nonempty when the cmdloop method is called,
|
| 36 |
+
it is printed out on interpreter startup. This value may be overridden
|
| 37 |
+
via an optional argument to the cmdloop() method.
|
| 38 |
+
|
| 39 |
+
The data members 'self.doc_header', 'self.misc_header', and
|
| 40 |
+
'self.undoc_header' set the headers used for the help function's
|
| 41 |
+
listings of documented functions, miscellaneous topics, and undocumented
|
| 42 |
+
functions respectively.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
import sys
|
| 46 |
+
|
| 47 |
+
__all__ = ["Cmd"]
|
| 48 |
+
|
| 49 |
+
PROMPT = '(Cmd) '
|
| 50 |
+
IDENTCHARS = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
| 51 |
+
'abcdefghijklmnopqrstuvwxyz'
|
| 52 |
+
'0123456789'
|
| 53 |
+
'_')
|
| 54 |
+
|
| 55 |
+
class Cmd:
|
| 56 |
+
"""A simple framework for writing line-oriented command interpreters.
|
| 57 |
+
|
| 58 |
+
These are often useful for test harnesses, administrative tools, and
|
| 59 |
+
prototypes that will later be wrapped in a more sophisticated interface.
|
| 60 |
+
|
| 61 |
+
A Cmd instance or subclass instance is a line-oriented interpreter
|
| 62 |
+
framework. There is no good reason to instantiate Cmd itself; rather,
|
| 63 |
+
it's useful as a superclass of an interpreter class you define yourself
|
| 64 |
+
in order to inherit Cmd's methods and encapsulate action methods.
|
| 65 |
+
|
| 66 |
+
"""
|
| 67 |
+
prompt = PROMPT
|
| 68 |
+
identchars = IDENTCHARS
|
| 69 |
+
ruler = '='
|
| 70 |
+
lastcmd = ''
|
| 71 |
+
intro = None
|
| 72 |
+
doc_leader = ""
|
| 73 |
+
doc_header = "Documented commands (type help <topic>):"
|
| 74 |
+
misc_header = "Miscellaneous help topics:"
|
| 75 |
+
undoc_header = "Undocumented commands:"
|
| 76 |
+
nohelp = "*** No help on %s"
|
| 77 |
+
use_rawinput = 1
|
| 78 |
+
|
| 79 |
+
def __init__(self, completekey='tab', stdin=None, stdout=None):
|
| 80 |
+
"""Instantiate a line-oriented interpreter framework.
|
| 81 |
+
|
| 82 |
+
The optional argument 'completekey' is the readline name of a
|
| 83 |
+
completion key; it defaults to the Tab key. If completekey is
|
| 84 |
+
not None and the readline module is available, command completion
|
| 85 |
+
is done automatically. The optional arguments stdin and stdout
|
| 86 |
+
specify alternate input and output file objects; if not specified,
|
| 87 |
+
sys.stdin and sys.stdout are used.
|
| 88 |
+
|
| 89 |
+
"""
|
| 90 |
+
if stdin is not None:
|
| 91 |
+
self.stdin = stdin
|
| 92 |
+
else:
|
| 93 |
+
self.stdin = sys.stdin
|
| 94 |
+
if stdout is not None:
|
| 95 |
+
self.stdout = stdout
|
| 96 |
+
else:
|
| 97 |
+
self.stdout = sys.stdout
|
| 98 |
+
self.cmdqueue = []
|
| 99 |
+
self.completekey = completekey
|
| 100 |
+
|
| 101 |
+
def cmdloop(self, intro=None):
|
| 102 |
+
"""Repeatedly issue a prompt, accept input, parse an initial prefix
|
| 103 |
+
off the received input, and dispatch to action methods, passing them
|
| 104 |
+
the remainder of the line as argument.
|
| 105 |
+
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
self.preloop()
|
| 109 |
+
if self.use_rawinput and self.completekey:
|
| 110 |
+
try:
|
| 111 |
+
import readline
|
| 112 |
+
self.old_completer = readline.get_completer()
|
| 113 |
+
readline.set_completer(self.complete)
|
| 114 |
+
if readline.backend == "editline":
|
| 115 |
+
if self.completekey == 'tab':
|
| 116 |
+
# libedit uses "^I" instead of "tab"
|
| 117 |
+
command_string = "bind ^I rl_complete"
|
| 118 |
+
else:
|
| 119 |
+
command_string = f"bind {self.completekey} rl_complete"
|
| 120 |
+
else:
|
| 121 |
+
command_string = f"{self.completekey}: complete"
|
| 122 |
+
readline.parse_and_bind(command_string)
|
| 123 |
+
except ImportError:
|
| 124 |
+
pass
|
| 125 |
+
try:
|
| 126 |
+
if intro is not None:
|
| 127 |
+
self.intro = intro
|
| 128 |
+
if self.intro:
|
| 129 |
+
self.stdout.write(str(self.intro)+"\n")
|
| 130 |
+
stop = None
|
| 131 |
+
while not stop:
|
| 132 |
+
if self.cmdqueue:
|
| 133 |
+
line = self.cmdqueue.pop(0)
|
| 134 |
+
else:
|
| 135 |
+
if self.use_rawinput:
|
| 136 |
+
try:
|
| 137 |
+
line = input(self.prompt)
|
| 138 |
+
except EOFError:
|
| 139 |
+
line = 'EOF'
|
| 140 |
+
else:
|
| 141 |
+
self.stdout.write(self.prompt)
|
| 142 |
+
self.stdout.flush()
|
| 143 |
+
line = self.stdin.readline()
|
| 144 |
+
if not len(line):
|
| 145 |
+
line = 'EOF'
|
| 146 |
+
else:
|
| 147 |
+
line = line.rstrip('\r\n')
|
| 148 |
+
line = self.precmd(line)
|
| 149 |
+
stop = self.onecmd(line)
|
| 150 |
+
stop = self.postcmd(stop, line)
|
| 151 |
+
self.postloop()
|
| 152 |
+
finally:
|
| 153 |
+
if self.use_rawinput and self.completekey:
|
| 154 |
+
try:
|
| 155 |
+
import readline
|
| 156 |
+
readline.set_completer(self.old_completer)
|
| 157 |
+
except ImportError:
|
| 158 |
+
pass
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def precmd(self, line):
|
| 162 |
+
"""Hook method executed just before the command line is
|
| 163 |
+
interpreted, but after the input prompt is generated and issued.
|
| 164 |
+
|
| 165 |
+
"""
|
| 166 |
+
return line
|
| 167 |
+
|
| 168 |
+
def postcmd(self, stop, line):
|
| 169 |
+
"""Hook method executed just after a command dispatch is finished."""
|
| 170 |
+
return stop
|
| 171 |
+
|
| 172 |
+
def preloop(self):
|
| 173 |
+
"""Hook method executed once when the cmdloop() method is called."""
|
| 174 |
+
pass
|
| 175 |
+
|
| 176 |
+
def postloop(self):
|
| 177 |
+
"""Hook method executed once when the cmdloop() method is about to
|
| 178 |
+
return.
|
| 179 |
+
|
| 180 |
+
"""
|
| 181 |
+
pass
|
| 182 |
+
|
| 183 |
+
def parseline(self, line):
|
| 184 |
+
"""Parse the line into a command name and a string containing
|
| 185 |
+
the arguments. Returns a tuple containing (command, args, line).
|
| 186 |
+
'command' and 'args' may be None if the line couldn't be parsed.
|
| 187 |
+
"""
|
| 188 |
+
line = line.strip()
|
| 189 |
+
if not line:
|
| 190 |
+
return None, None, line
|
| 191 |
+
elif line[0] == '?':
|
| 192 |
+
line = 'help ' + line[1:]
|
| 193 |
+
elif line[0] == '!':
|
| 194 |
+
if hasattr(self, 'do_shell'):
|
| 195 |
+
line = 'shell ' + line[1:]
|
| 196 |
+
else:
|
| 197 |
+
return None, None, line
|
| 198 |
+
i, n = 0, len(line)
|
| 199 |
+
while i < n and line[i] in self.identchars: i = i+1
|
| 200 |
+
cmd, arg = line[:i], line[i:].strip()
|
| 201 |
+
return cmd, arg, line
|
| 202 |
+
|
| 203 |
+
def onecmd(self, line):
|
| 204 |
+
"""Interpret the argument as though it had been typed in response
|
| 205 |
+
to the prompt.
|
| 206 |
+
|
| 207 |
+
This may be overridden, but should not normally need to be;
|
| 208 |
+
see the precmd() and postcmd() methods for useful execution hooks.
|
| 209 |
+
The return value is a flag indicating whether interpretation of
|
| 210 |
+
commands by the interpreter should stop.
|
| 211 |
+
|
| 212 |
+
"""
|
| 213 |
+
cmd, arg, line = self.parseline(line)
|
| 214 |
+
if not line:
|
| 215 |
+
return self.emptyline()
|
| 216 |
+
if cmd is None:
|
| 217 |
+
return self.default(line)
|
| 218 |
+
self.lastcmd = line
|
| 219 |
+
if line == 'EOF' :
|
| 220 |
+
self.lastcmd = ''
|
| 221 |
+
if cmd == '':
|
| 222 |
+
return self.default(line)
|
| 223 |
+
else:
|
| 224 |
+
func = getattr(self, 'do_' + cmd, None)
|
| 225 |
+
if func is None:
|
| 226 |
+
return self.default(line)
|
| 227 |
+
return func(arg)
|
| 228 |
+
|
| 229 |
+
def emptyline(self):
|
| 230 |
+
"""Called when an empty line is entered in response to the prompt.
|
| 231 |
+
|
| 232 |
+
If this method is not overridden, it repeats the last nonempty
|
| 233 |
+
command entered.
|
| 234 |
+
|
| 235 |
+
"""
|
| 236 |
+
if self.lastcmd:
|
| 237 |
+
return self.onecmd(self.lastcmd)
|
| 238 |
+
|
| 239 |
+
def default(self, line):
|
| 240 |
+
"""Called on an input line when the command prefix is not recognized.
|
| 241 |
+
|
| 242 |
+
If this method is not overridden, it prints an error message and
|
| 243 |
+
returns.
|
| 244 |
+
|
| 245 |
+
"""
|
| 246 |
+
self.stdout.write('*** Unknown syntax: %s\n'%line)
|
| 247 |
+
|
| 248 |
+
def completedefault(self, *ignored):
|
| 249 |
+
"""Method called to complete an input line when no command-specific
|
| 250 |
+
complete_*() method is available.
|
| 251 |
+
|
| 252 |
+
By default, it returns an empty list.
|
| 253 |
+
|
| 254 |
+
"""
|
| 255 |
+
return []
|
| 256 |
+
|
| 257 |
+
def completenames(self, text, *ignored):
|
| 258 |
+
dotext = 'do_'+text
|
| 259 |
+
return [a[3:] for a in self.get_names() if a.startswith(dotext)]
|
| 260 |
+
|
| 261 |
+
def complete(self, text, state):
|
| 262 |
+
"""Return the next possible completion for 'text'.
|
| 263 |
+
|
| 264 |
+
If a command has not been entered, then complete against command list.
|
| 265 |
+
Otherwise try to call complete_<command> to get list of completions.
|
| 266 |
+
"""
|
| 267 |
+
if state == 0:
|
| 268 |
+
import readline
|
| 269 |
+
origline = readline.get_line_buffer()
|
| 270 |
+
line = origline.lstrip()
|
| 271 |
+
stripped = len(origline) - len(line)
|
| 272 |
+
begidx = readline.get_begidx() - stripped
|
| 273 |
+
endidx = readline.get_endidx() - stripped
|
| 274 |
+
if begidx>0:
|
| 275 |
+
cmd, args, foo = self.parseline(line)
|
| 276 |
+
if not cmd:
|
| 277 |
+
compfunc = self.completedefault
|
| 278 |
+
else:
|
| 279 |
+
try:
|
| 280 |
+
compfunc = getattr(self, 'complete_' + cmd)
|
| 281 |
+
except AttributeError:
|
| 282 |
+
compfunc = self.completedefault
|
| 283 |
+
else:
|
| 284 |
+
compfunc = self.completenames
|
| 285 |
+
self.completion_matches = compfunc(text, line, begidx, endidx)
|
| 286 |
+
try:
|
| 287 |
+
return self.completion_matches[state]
|
| 288 |
+
except IndexError:
|
| 289 |
+
return None
|
| 290 |
+
|
| 291 |
+
def get_names(self):
|
| 292 |
+
# This method used to pull in base class attributes
|
| 293 |
+
# at a time dir() didn't do it yet.
|
| 294 |
+
return dir(self.__class__)
|
| 295 |
+
|
| 296 |
+
def complete_help(self, *args):
|
| 297 |
+
commands = set(self.completenames(*args))
|
| 298 |
+
topics = set(a[5:] for a in self.get_names()
|
| 299 |
+
if a.startswith('help_' + args[0]))
|
| 300 |
+
return list(commands | topics)
|
| 301 |
+
|
| 302 |
+
def do_help(self, arg):
|
| 303 |
+
'List available commands with "help" or detailed help with "help cmd".'
|
| 304 |
+
if arg:
|
| 305 |
+
# XXX check arg syntax
|
| 306 |
+
try:
|
| 307 |
+
func = getattr(self, 'help_' + arg)
|
| 308 |
+
except AttributeError:
|
| 309 |
+
from inspect import cleandoc
|
| 310 |
+
|
| 311 |
+
try:
|
| 312 |
+
doc=getattr(self, 'do_' + arg).__doc__
|
| 313 |
+
doc = cleandoc(doc)
|
| 314 |
+
if doc:
|
| 315 |
+
self.stdout.write("%s\n"%str(doc))
|
| 316 |
+
return
|
| 317 |
+
except AttributeError:
|
| 318 |
+
pass
|
| 319 |
+
self.stdout.write("%s\n"%str(self.nohelp % (arg,)))
|
| 320 |
+
return
|
| 321 |
+
func()
|
| 322 |
+
else:
|
| 323 |
+
names = self.get_names()
|
| 324 |
+
cmds_doc = []
|
| 325 |
+
cmds_undoc = []
|
| 326 |
+
topics = set()
|
| 327 |
+
for name in names:
|
| 328 |
+
if name[:5] == 'help_':
|
| 329 |
+
topics.add(name[5:])
|
| 330 |
+
names.sort()
|
| 331 |
+
# There can be duplicates if routines overridden
|
| 332 |
+
prevname = ''
|
| 333 |
+
for name in names:
|
| 334 |
+
if name[:3] == 'do_':
|
| 335 |
+
if name == prevname:
|
| 336 |
+
continue
|
| 337 |
+
prevname = name
|
| 338 |
+
cmd=name[3:]
|
| 339 |
+
if cmd in topics:
|
| 340 |
+
cmds_doc.append(cmd)
|
| 341 |
+
topics.remove(cmd)
|
| 342 |
+
elif getattr(self, name).__doc__:
|
| 343 |
+
cmds_doc.append(cmd)
|
| 344 |
+
else:
|
| 345 |
+
cmds_undoc.append(cmd)
|
| 346 |
+
self.stdout.write("%s\n"%str(self.doc_leader))
|
| 347 |
+
self.print_topics(self.doc_header, cmds_doc, 15,80)
|
| 348 |
+
self.print_topics(self.misc_header, sorted(topics),15,80)
|
| 349 |
+
self.print_topics(self.undoc_header, cmds_undoc, 15,80)
|
| 350 |
+
|
| 351 |
+
def print_topics(self, header, cmds, cmdlen, maxcol):
|
| 352 |
+
if cmds:
|
| 353 |
+
self.stdout.write("%s\n"%str(header))
|
| 354 |
+
if self.ruler:
|
| 355 |
+
self.stdout.write("%s\n"%str(self.ruler * len(header)))
|
| 356 |
+
self.columnize(cmds, maxcol-1)
|
| 357 |
+
self.stdout.write("\n")
|
| 358 |
+
|
| 359 |
+
def columnize(self, list, displaywidth=80):
|
| 360 |
+
"""Display a list of strings as a compact set of columns.
|
| 361 |
+
|
| 362 |
+
Each column is only as wide as necessary.
|
| 363 |
+
Columns are separated by two spaces (one was not legible enough).
|
| 364 |
+
"""
|
| 365 |
+
if not list:
|
| 366 |
+
self.stdout.write("<empty>\n")
|
| 367 |
+
return
|
| 368 |
+
|
| 369 |
+
nonstrings = [i for i in range(len(list))
|
| 370 |
+
if not isinstance(list[i], str)]
|
| 371 |
+
if nonstrings:
|
| 372 |
+
raise TypeError("list[i] not a string for i in %s"
|
| 373 |
+
% ", ".join(map(str, nonstrings)))
|
| 374 |
+
size = len(list)
|
| 375 |
+
if size == 1:
|
| 376 |
+
self.stdout.write('%s\n'%str(list[0]))
|
| 377 |
+
return
|
| 378 |
+
# Try every row count from 1 upwards
|
| 379 |
+
for nrows in range(1, len(list)):
|
| 380 |
+
ncols = (size+nrows-1) // nrows
|
| 381 |
+
colwidths = []
|
| 382 |
+
totwidth = -2
|
| 383 |
+
for col in range(ncols):
|
| 384 |
+
colwidth = 0
|
| 385 |
+
for row in range(nrows):
|
| 386 |
+
i = row + nrows*col
|
| 387 |
+
if i >= size:
|
| 388 |
+
break
|
| 389 |
+
x = list[i]
|
| 390 |
+
colwidth = max(colwidth, len(x))
|
| 391 |
+
colwidths.append(colwidth)
|
| 392 |
+
totwidth += colwidth + 2
|
| 393 |
+
if totwidth > displaywidth:
|
| 394 |
+
break
|
| 395 |
+
if totwidth <= displaywidth:
|
| 396 |
+
break
|
| 397 |
+
else:
|
| 398 |
+
nrows = len(list)
|
| 399 |
+
ncols = 1
|
| 400 |
+
colwidths = [0]
|
| 401 |
+
for row in range(nrows):
|
| 402 |
+
texts = []
|
| 403 |
+
for col in range(ncols):
|
| 404 |
+
i = row + nrows*col
|
| 405 |
+
if i >= size:
|
| 406 |
+
x = ""
|
| 407 |
+
else:
|
| 408 |
+
x = list[i]
|
| 409 |
+
texts.append(x)
|
| 410 |
+
while texts and not texts[-1]:
|
| 411 |
+
del texts[-1]
|
| 412 |
+
for col in range(len(texts)):
|
| 413 |
+
texts[col] = texts[col].ljust(colwidths[col])
|
| 414 |
+
self.stdout.write("%s\n"%str(" ".join(texts)))
|
micromamba_root/envs/hf_sync/Lib/code.py
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utilities needed to emulate Python's interactive interpreter.
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
# Inspired by similar code by Jeff Epler and Fredrik Lundh.
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
import builtins
|
| 9 |
+
import sys
|
| 10 |
+
import traceback
|
| 11 |
+
from codeop import CommandCompiler, compile_command
|
| 12 |
+
|
| 13 |
+
__all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact",
|
| 14 |
+
"compile_command"]
|
| 15 |
+
|
| 16 |
+
class InteractiveInterpreter:
|
| 17 |
+
"""Base class for InteractiveConsole.
|
| 18 |
+
|
| 19 |
+
This class deals with parsing and interpreter state (the user's
|
| 20 |
+
namespace); it doesn't deal with input buffering or prompting or
|
| 21 |
+
input file naming (the filename is always passed in explicitly).
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(self, locals=None):
|
| 26 |
+
"""Constructor.
|
| 27 |
+
|
| 28 |
+
The optional 'locals' argument specifies a mapping to use as the
|
| 29 |
+
namespace in which code will be executed; it defaults to a newly
|
| 30 |
+
created dictionary with key "__name__" set to "__console__" and
|
| 31 |
+
key "__doc__" set to None.
|
| 32 |
+
|
| 33 |
+
"""
|
| 34 |
+
if locals is None:
|
| 35 |
+
locals = {"__name__": "__console__", "__doc__": None}
|
| 36 |
+
self.locals = locals
|
| 37 |
+
self.compile = CommandCompiler()
|
| 38 |
+
|
| 39 |
+
def runsource(self, source, filename="<input>", symbol="single"):
|
| 40 |
+
"""Compile and run some source in the interpreter.
|
| 41 |
+
|
| 42 |
+
Arguments are as for compile_command().
|
| 43 |
+
|
| 44 |
+
One of several things can happen:
|
| 45 |
+
|
| 46 |
+
1) The input is incorrect; compile_command() raised an
|
| 47 |
+
exception (SyntaxError or OverflowError). A syntax traceback
|
| 48 |
+
will be printed by calling the showsyntaxerror() method.
|
| 49 |
+
|
| 50 |
+
2) The input is incomplete, and more input is required;
|
| 51 |
+
compile_command() returned None. Nothing happens.
|
| 52 |
+
|
| 53 |
+
3) The input is complete; compile_command() returned a code
|
| 54 |
+
object. The code is executed by calling self.runcode() (which
|
| 55 |
+
also handles run-time exceptions, except for SystemExit).
|
| 56 |
+
|
| 57 |
+
The return value is True in case 2, False in the other cases (unless
|
| 58 |
+
an exception is raised). The return value can be used to
|
| 59 |
+
decide whether to use sys.ps1 or sys.ps2 to prompt the next
|
| 60 |
+
line.
|
| 61 |
+
|
| 62 |
+
"""
|
| 63 |
+
try:
|
| 64 |
+
code = self.compile(source, filename, symbol)
|
| 65 |
+
except (OverflowError, SyntaxError, ValueError):
|
| 66 |
+
# Case 1
|
| 67 |
+
self.showsyntaxerror(filename, source=source)
|
| 68 |
+
return False
|
| 69 |
+
|
| 70 |
+
if code is None:
|
| 71 |
+
# Case 2
|
| 72 |
+
return True
|
| 73 |
+
|
| 74 |
+
# Case 3
|
| 75 |
+
self.runcode(code)
|
| 76 |
+
return False
|
| 77 |
+
|
| 78 |
+
def runcode(self, code):
|
| 79 |
+
"""Execute a code object.
|
| 80 |
+
|
| 81 |
+
When an exception occurs, self.showtraceback() is called to
|
| 82 |
+
display a traceback. All exceptions are caught except
|
| 83 |
+
SystemExit, which is reraised.
|
| 84 |
+
|
| 85 |
+
A note about KeyboardInterrupt: this exception may occur
|
| 86 |
+
elsewhere in this code, and may not always be caught. The
|
| 87 |
+
caller should be prepared to deal with it.
|
| 88 |
+
|
| 89 |
+
"""
|
| 90 |
+
try:
|
| 91 |
+
exec(code, self.locals)
|
| 92 |
+
except SystemExit:
|
| 93 |
+
raise
|
| 94 |
+
except:
|
| 95 |
+
self.showtraceback()
|
| 96 |
+
|
| 97 |
+
def showsyntaxerror(self, filename=None, **kwargs):
|
| 98 |
+
"""Display the syntax error that just occurred.
|
| 99 |
+
|
| 100 |
+
This doesn't display a stack trace because there isn't one.
|
| 101 |
+
|
| 102 |
+
If a filename is given, it is stuffed in the exception instead
|
| 103 |
+
of what was there before (because Python's parser always uses
|
| 104 |
+
"<string>" when reading from a string).
|
| 105 |
+
|
| 106 |
+
The output is written by self.write(), below.
|
| 107 |
+
|
| 108 |
+
"""
|
| 109 |
+
try:
|
| 110 |
+
typ, value, tb = sys.exc_info()
|
| 111 |
+
if filename and issubclass(typ, SyntaxError):
|
| 112 |
+
value.filename = filename
|
| 113 |
+
source = kwargs.pop('source', "")
|
| 114 |
+
self._showtraceback(typ, value, None, source)
|
| 115 |
+
finally:
|
| 116 |
+
typ = value = tb = None
|
| 117 |
+
|
| 118 |
+
def showtraceback(self):
|
| 119 |
+
"""Display the exception that just occurred.
|
| 120 |
+
|
| 121 |
+
We remove the first stack item because it is our own code.
|
| 122 |
+
|
| 123 |
+
The output is written by self.write(), below.
|
| 124 |
+
|
| 125 |
+
"""
|
| 126 |
+
try:
|
| 127 |
+
typ, value, tb = sys.exc_info()
|
| 128 |
+
self._showtraceback(typ, value, tb.tb_next, "")
|
| 129 |
+
finally:
|
| 130 |
+
typ = value = tb = None
|
| 131 |
+
|
| 132 |
+
def _showtraceback(self, typ, value, tb, source):
|
| 133 |
+
sys.last_type = typ
|
| 134 |
+
sys.last_traceback = tb
|
| 135 |
+
value = value.with_traceback(tb)
|
| 136 |
+
# Set the line of text that the exception refers to
|
| 137 |
+
lines = source.splitlines()
|
| 138 |
+
if (source and typ is SyntaxError
|
| 139 |
+
and not value.text and value.lineno is not None
|
| 140 |
+
and len(lines) >= value.lineno):
|
| 141 |
+
value.text = lines[value.lineno - 1]
|
| 142 |
+
sys.last_exc = sys.last_value = value
|
| 143 |
+
if sys.excepthook is sys.__excepthook__:
|
| 144 |
+
self._excepthook(typ, value, tb)
|
| 145 |
+
else:
|
| 146 |
+
# If someone has set sys.excepthook, we let that take precedence
|
| 147 |
+
# over self.write
|
| 148 |
+
try:
|
| 149 |
+
sys.excepthook(typ, value, tb)
|
| 150 |
+
except SystemExit:
|
| 151 |
+
raise
|
| 152 |
+
except BaseException as e:
|
| 153 |
+
e.__context__ = None
|
| 154 |
+
e = e.with_traceback(e.__traceback__.tb_next)
|
| 155 |
+
print('Error in sys.excepthook:', file=sys.stderr)
|
| 156 |
+
sys.__excepthook__(type(e), e, e.__traceback__)
|
| 157 |
+
print(file=sys.stderr)
|
| 158 |
+
print('Original exception was:', file=sys.stderr)
|
| 159 |
+
sys.__excepthook__(typ, value, tb)
|
| 160 |
+
|
| 161 |
+
def _excepthook(self, typ, value, tb):
|
| 162 |
+
# This method is being overwritten in
|
| 163 |
+
# _pyrepl.console.InteractiveColoredConsole
|
| 164 |
+
lines = traceback.format_exception(typ, value, tb)
|
| 165 |
+
self.write(''.join(lines))
|
| 166 |
+
|
| 167 |
+
def write(self, data):
|
| 168 |
+
"""Write a string.
|
| 169 |
+
|
| 170 |
+
The base implementation writes to sys.stderr; a subclass may
|
| 171 |
+
replace this with a different implementation.
|
| 172 |
+
|
| 173 |
+
"""
|
| 174 |
+
sys.stderr.write(data)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class InteractiveConsole(InteractiveInterpreter):
|
| 178 |
+
"""Closely emulate the behavior of the interactive Python interpreter.
|
| 179 |
+
|
| 180 |
+
This class builds on InteractiveInterpreter and adds prompting
|
| 181 |
+
using the familiar sys.ps1 and sys.ps2, and input buffering.
|
| 182 |
+
|
| 183 |
+
"""
|
| 184 |
+
|
| 185 |
+
def __init__(self, locals=None, filename="<console>", *, local_exit=False):
|
| 186 |
+
"""Constructor.
|
| 187 |
+
|
| 188 |
+
The optional locals argument will be passed to the
|
| 189 |
+
InteractiveInterpreter base class.
|
| 190 |
+
|
| 191 |
+
The optional filename argument should specify the (file)name
|
| 192 |
+
of the input stream; it will show up in tracebacks.
|
| 193 |
+
|
| 194 |
+
"""
|
| 195 |
+
InteractiveInterpreter.__init__(self, locals)
|
| 196 |
+
self.filename = filename
|
| 197 |
+
self.local_exit = local_exit
|
| 198 |
+
self.resetbuffer()
|
| 199 |
+
|
| 200 |
+
def resetbuffer(self):
|
| 201 |
+
"""Reset the input buffer."""
|
| 202 |
+
self.buffer = []
|
| 203 |
+
|
| 204 |
+
def interact(self, banner=None, exitmsg=None):
|
| 205 |
+
"""Closely emulate the interactive Python console.
|
| 206 |
+
|
| 207 |
+
The optional banner argument specifies the banner to print
|
| 208 |
+
before the first interaction; by default it prints a banner
|
| 209 |
+
similar to the one printed by the real Python interpreter,
|
| 210 |
+
followed by the current class name in parentheses (so as not
|
| 211 |
+
to confuse this with the real interpreter -- since it's so
|
| 212 |
+
close!).
|
| 213 |
+
|
| 214 |
+
The optional exitmsg argument specifies the exit message
|
| 215 |
+
printed when exiting. Pass the empty string to suppress
|
| 216 |
+
printing an exit message. If exitmsg is not given or None,
|
| 217 |
+
a default message is printed.
|
| 218 |
+
|
| 219 |
+
"""
|
| 220 |
+
try:
|
| 221 |
+
sys.ps1
|
| 222 |
+
delete_ps1_after = False
|
| 223 |
+
except AttributeError:
|
| 224 |
+
sys.ps1 = ">>> "
|
| 225 |
+
delete_ps1_after = True
|
| 226 |
+
try:
|
| 227 |
+
_ps2 = sys.ps2
|
| 228 |
+
delete_ps2_after = False
|
| 229 |
+
except AttributeError:
|
| 230 |
+
sys.ps2 = "... "
|
| 231 |
+
delete_ps2_after = True
|
| 232 |
+
|
| 233 |
+
cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
|
| 234 |
+
if banner is None:
|
| 235 |
+
self.write("Python %s on %s\n%s\n(%s)\n" %
|
| 236 |
+
(sys.version, sys.platform, cprt,
|
| 237 |
+
self.__class__.__name__))
|
| 238 |
+
elif banner:
|
| 239 |
+
self.write("%s\n" % str(banner))
|
| 240 |
+
more = 0
|
| 241 |
+
|
| 242 |
+
# When the user uses exit() or quit() in their interactive shell
|
| 243 |
+
# they probably just want to exit the created shell, not the whole
|
| 244 |
+
# process. exit and quit in builtins closes sys.stdin which makes
|
| 245 |
+
# it super difficult to restore
|
| 246 |
+
#
|
| 247 |
+
# When self.local_exit is True, we overwrite the builtins so
|
| 248 |
+
# exit() and quit() only raises SystemExit and we can catch that
|
| 249 |
+
# to only exit the interactive shell
|
| 250 |
+
|
| 251 |
+
_exit = None
|
| 252 |
+
_quit = None
|
| 253 |
+
|
| 254 |
+
if self.local_exit:
|
| 255 |
+
if hasattr(builtins, "exit"):
|
| 256 |
+
_exit = builtins.exit
|
| 257 |
+
builtins.exit = Quitter("exit")
|
| 258 |
+
|
| 259 |
+
if hasattr(builtins, "quit"):
|
| 260 |
+
_quit = builtins.quit
|
| 261 |
+
builtins.quit = Quitter("quit")
|
| 262 |
+
|
| 263 |
+
try:
|
| 264 |
+
while True:
|
| 265 |
+
try:
|
| 266 |
+
if more:
|
| 267 |
+
prompt = sys.ps2
|
| 268 |
+
else:
|
| 269 |
+
prompt = sys.ps1
|
| 270 |
+
try:
|
| 271 |
+
line = self.raw_input(prompt)
|
| 272 |
+
except EOFError:
|
| 273 |
+
self.write("\n")
|
| 274 |
+
break
|
| 275 |
+
else:
|
| 276 |
+
more = self.push(line)
|
| 277 |
+
except KeyboardInterrupt:
|
| 278 |
+
self.write("\nKeyboardInterrupt\n")
|
| 279 |
+
self.resetbuffer()
|
| 280 |
+
more = 0
|
| 281 |
+
except SystemExit as e:
|
| 282 |
+
if self.local_exit:
|
| 283 |
+
self.write("\n")
|
| 284 |
+
break
|
| 285 |
+
else:
|
| 286 |
+
raise e
|
| 287 |
+
finally:
|
| 288 |
+
# restore exit and quit in builtins if they were modified
|
| 289 |
+
if _exit is not None:
|
| 290 |
+
builtins.exit = _exit
|
| 291 |
+
|
| 292 |
+
if _quit is not None:
|
| 293 |
+
builtins.quit = _quit
|
| 294 |
+
|
| 295 |
+
if delete_ps1_after:
|
| 296 |
+
del sys.ps1
|
| 297 |
+
|
| 298 |
+
if delete_ps2_after:
|
| 299 |
+
del sys.ps2
|
| 300 |
+
|
| 301 |
+
if exitmsg is None:
|
| 302 |
+
self.write('now exiting %s...\n' % self.__class__.__name__)
|
| 303 |
+
elif exitmsg != '':
|
| 304 |
+
self.write('%s\n' % exitmsg)
|
| 305 |
+
|
| 306 |
+
def push(self, line, filename=None, _symbol="single"):
|
| 307 |
+
"""Push a line to the interpreter.
|
| 308 |
+
|
| 309 |
+
The line should not have a trailing newline; it may have
|
| 310 |
+
internal newlines. The line is appended to a buffer and the
|
| 311 |
+
interpreter's runsource() method is called with the
|
| 312 |
+
concatenated contents of the buffer as source. If this
|
| 313 |
+
indicates that the command was executed or invalid, the buffer
|
| 314 |
+
is reset; otherwise, the command is incomplete, and the buffer
|
| 315 |
+
is left as it was after the line was appended. The return
|
| 316 |
+
value is 1 if more input is required, 0 if the line was dealt
|
| 317 |
+
with in some way (this is the same as runsource()).
|
| 318 |
+
|
| 319 |
+
"""
|
| 320 |
+
self.buffer.append(line)
|
| 321 |
+
source = "\n".join(self.buffer)
|
| 322 |
+
if filename is None:
|
| 323 |
+
filename = self.filename
|
| 324 |
+
more = self.runsource(source, filename, symbol=_symbol)
|
| 325 |
+
if not more:
|
| 326 |
+
self.resetbuffer()
|
| 327 |
+
return more
|
| 328 |
+
|
| 329 |
+
def raw_input(self, prompt=""):
|
| 330 |
+
"""Write a prompt and read a line.
|
| 331 |
+
|
| 332 |
+
The returned line does not include the trailing newline.
|
| 333 |
+
When the user enters the EOF key sequence, EOFError is raised.
|
| 334 |
+
|
| 335 |
+
The base implementation uses the built-in function
|
| 336 |
+
input(); a subclass may replace this with a different
|
| 337 |
+
implementation.
|
| 338 |
+
|
| 339 |
+
"""
|
| 340 |
+
return input(prompt)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
class Quitter:
|
| 344 |
+
def __init__(self, name):
|
| 345 |
+
self.name = name
|
| 346 |
+
if sys.platform == "win32":
|
| 347 |
+
self.eof = 'Ctrl-Z plus Return'
|
| 348 |
+
else:
|
| 349 |
+
self.eof = 'Ctrl-D (i.e. EOF)'
|
| 350 |
+
|
| 351 |
+
def __repr__(self):
|
| 352 |
+
return f'Use {self.name} or {self.eof} to exit'
|
| 353 |
+
|
| 354 |
+
def __call__(self, code=None):
|
| 355 |
+
raise SystemExit(code)
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def interact(banner=None, readfunc=None, local=None, exitmsg=None, local_exit=False):
|
| 359 |
+
"""Closely emulate the interactive Python interpreter.
|
| 360 |
+
|
| 361 |
+
This is a backwards compatible interface to the InteractiveConsole
|
| 362 |
+
class. When readfunc is not specified, it attempts to import the
|
| 363 |
+
readline module to enable GNU readline if it is available.
|
| 364 |
+
|
| 365 |
+
Arguments (all optional, all default to None):
|
| 366 |
+
|
| 367 |
+
banner -- passed to InteractiveConsole.interact()
|
| 368 |
+
readfunc -- if not None, replaces InteractiveConsole.raw_input()
|
| 369 |
+
local -- passed to InteractiveInterpreter.__init__()
|
| 370 |
+
exitmsg -- passed to InteractiveConsole.interact()
|
| 371 |
+
local_exit -- passed to InteractiveConsole.__init__()
|
| 372 |
+
|
| 373 |
+
"""
|
| 374 |
+
console = InteractiveConsole(local, local_exit=local_exit)
|
| 375 |
+
if readfunc is not None:
|
| 376 |
+
console.raw_input = readfunc
|
| 377 |
+
else:
|
| 378 |
+
try:
|
| 379 |
+
import readline # noqa: F401
|
| 380 |
+
except ImportError:
|
| 381 |
+
pass
|
| 382 |
+
console.interact(banner, exitmsg)
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
if __name__ == "__main__":
|
| 386 |
+
import argparse
|
| 387 |
+
|
| 388 |
+
parser = argparse.ArgumentParser(color=True)
|
| 389 |
+
parser.add_argument('-q', action='store_true',
|
| 390 |
+
help="don't print version and copyright messages")
|
| 391 |
+
args = parser.parse_args()
|
| 392 |
+
if args.q or sys.flags.quiet:
|
| 393 |
+
banner = ''
|
| 394 |
+
else:
|
| 395 |
+
banner = None
|
| 396 |
+
interact(banner)
|
micromamba_root/envs/hf_sync/Lib/codecs.py
ADDED
|
@@ -0,0 +1,1125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" codecs -- Python Codec Registry, API and helpers.
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
Written by Marc-Andre Lemburg (mal@lemburg.com).
|
| 5 |
+
|
| 6 |
+
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import builtins
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
### Registry and builtin stateless codec functions
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
from _codecs import *
|
| 17 |
+
except ImportError as why:
|
| 18 |
+
raise SystemError('Failed to load the builtin codecs: %s' % why)
|
| 19 |
+
|
| 20 |
+
__all__ = ["register", "lookup", "open", "EncodedFile", "BOM", "BOM_BE",
|
| 21 |
+
"BOM_LE", "BOM32_BE", "BOM32_LE", "BOM64_BE", "BOM64_LE",
|
| 22 |
+
"BOM_UTF8", "BOM_UTF16", "BOM_UTF16_LE", "BOM_UTF16_BE",
|
| 23 |
+
"BOM_UTF32", "BOM_UTF32_LE", "BOM_UTF32_BE",
|
| 24 |
+
"CodecInfo", "Codec", "IncrementalEncoder", "IncrementalDecoder",
|
| 25 |
+
"StreamReader", "StreamWriter",
|
| 26 |
+
"StreamReaderWriter", "StreamRecoder",
|
| 27 |
+
"getencoder", "getdecoder", "getincrementalencoder",
|
| 28 |
+
"getincrementaldecoder", "getreader", "getwriter",
|
| 29 |
+
"encode", "decode", "iterencode", "iterdecode",
|
| 30 |
+
"strict_errors", "ignore_errors", "replace_errors",
|
| 31 |
+
"xmlcharrefreplace_errors",
|
| 32 |
+
"backslashreplace_errors", "namereplace_errors",
|
| 33 |
+
"register_error", "lookup_error"]
|
| 34 |
+
|
| 35 |
+
### Constants
|
| 36 |
+
|
| 37 |
+
#
|
| 38 |
+
# Byte Order Mark (BOM = ZERO WIDTH NO-BREAK SPACE = U+FEFF)
|
| 39 |
+
# and its possible byte string values
|
| 40 |
+
# for UTF8/UTF16/UTF32 output and little/big endian machines
|
| 41 |
+
#
|
| 42 |
+
|
| 43 |
+
# UTF-8
|
| 44 |
+
BOM_UTF8 = b'\xef\xbb\xbf'
|
| 45 |
+
|
| 46 |
+
# UTF-16, little endian
|
| 47 |
+
BOM_LE = BOM_UTF16_LE = b'\xff\xfe'
|
| 48 |
+
|
| 49 |
+
# UTF-16, big endian
|
| 50 |
+
BOM_BE = BOM_UTF16_BE = b'\xfe\xff'
|
| 51 |
+
|
| 52 |
+
# UTF-32, little endian
|
| 53 |
+
BOM_UTF32_LE = b'\xff\xfe\x00\x00'
|
| 54 |
+
|
| 55 |
+
# UTF-32, big endian
|
| 56 |
+
BOM_UTF32_BE = b'\x00\x00\xfe\xff'
|
| 57 |
+
|
| 58 |
+
if sys.byteorder == 'little':
|
| 59 |
+
|
| 60 |
+
# UTF-16, native endianness
|
| 61 |
+
BOM = BOM_UTF16 = BOM_UTF16_LE
|
| 62 |
+
|
| 63 |
+
# UTF-32, native endianness
|
| 64 |
+
BOM_UTF32 = BOM_UTF32_LE
|
| 65 |
+
|
| 66 |
+
else:
|
| 67 |
+
|
| 68 |
+
# UTF-16, native endianness
|
| 69 |
+
BOM = BOM_UTF16 = BOM_UTF16_BE
|
| 70 |
+
|
| 71 |
+
# UTF-32, native endianness
|
| 72 |
+
BOM_UTF32 = BOM_UTF32_BE
|
| 73 |
+
|
| 74 |
+
# Old broken names (don't use in new code)
|
| 75 |
+
BOM32_LE = BOM_UTF16_LE
|
| 76 |
+
BOM32_BE = BOM_UTF16_BE
|
| 77 |
+
BOM64_LE = BOM_UTF32_LE
|
| 78 |
+
BOM64_BE = BOM_UTF32_BE
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
### Codec base classes (defining the API)
|
| 82 |
+
|
| 83 |
+
class CodecInfo(tuple):
|
| 84 |
+
"""Codec details when looking up the codec registry"""
|
| 85 |
+
|
| 86 |
+
# Private API to allow Python 3.4 to denylist the known non-Unicode
|
| 87 |
+
# codecs in the standard library. A more general mechanism to
|
| 88 |
+
# reliably distinguish test encodings from other codecs will hopefully
|
| 89 |
+
# be defined for Python 3.5
|
| 90 |
+
#
|
| 91 |
+
# See http://bugs.python.org/issue19619
|
| 92 |
+
_is_text_encoding = True # Assume codecs are text encodings by default
|
| 93 |
+
|
| 94 |
+
def __new__(cls, encode, decode, streamreader=None, streamwriter=None,
|
| 95 |
+
incrementalencoder=None, incrementaldecoder=None, name=None,
|
| 96 |
+
*, _is_text_encoding=None):
|
| 97 |
+
self = tuple.__new__(cls, (encode, decode, streamreader, streamwriter))
|
| 98 |
+
self.name = name
|
| 99 |
+
self.encode = encode
|
| 100 |
+
self.decode = decode
|
| 101 |
+
self.incrementalencoder = incrementalencoder
|
| 102 |
+
self.incrementaldecoder = incrementaldecoder
|
| 103 |
+
self.streamwriter = streamwriter
|
| 104 |
+
self.streamreader = streamreader
|
| 105 |
+
if _is_text_encoding is not None:
|
| 106 |
+
self._is_text_encoding = _is_text_encoding
|
| 107 |
+
return self
|
| 108 |
+
|
| 109 |
+
def __repr__(self):
|
| 110 |
+
return "<%s.%s object for encoding %s at %#x>" % \
|
| 111 |
+
(self.__class__.__module__, self.__class__.__qualname__,
|
| 112 |
+
self.name, id(self))
|
| 113 |
+
|
| 114 |
+
def __getnewargs__(self):
|
| 115 |
+
return tuple(self)
|
| 116 |
+
|
| 117 |
+
class Codec:
|
| 118 |
+
|
| 119 |
+
""" Defines the interface for stateless encoders/decoders.
|
| 120 |
+
|
| 121 |
+
The .encode()/.decode() methods may use different error
|
| 122 |
+
handling schemes by providing the errors argument. These
|
| 123 |
+
string values are predefined:
|
| 124 |
+
|
| 125 |
+
'strict' - raise a ValueError error (or a subclass)
|
| 126 |
+
'ignore' - ignore the character and continue with the next
|
| 127 |
+
'replace' - replace with a suitable replacement character;
|
| 128 |
+
Python will use the official U+FFFD REPLACEMENT
|
| 129 |
+
CHARACTER for the builtin Unicode codecs on
|
| 130 |
+
decoding and '?' on encoding.
|
| 131 |
+
'surrogateescape' - replace with private code points U+DCnn.
|
| 132 |
+
'xmlcharrefreplace' - Replace with the appropriate XML
|
| 133 |
+
character reference (only for encoding).
|
| 134 |
+
'backslashreplace' - Replace with backslashed escape sequences.
|
| 135 |
+
'namereplace' - Replace with \\N{...} escape sequences
|
| 136 |
+
(only for encoding).
|
| 137 |
+
|
| 138 |
+
The set of allowed values can be extended via register_error.
|
| 139 |
+
|
| 140 |
+
"""
|
| 141 |
+
def encode(self, input, errors='strict'):
|
| 142 |
+
|
| 143 |
+
""" Encodes the object input and returns a tuple (output
|
| 144 |
+
object, length consumed).
|
| 145 |
+
|
| 146 |
+
errors defines the error handling to apply. It defaults to
|
| 147 |
+
'strict' handling.
|
| 148 |
+
|
| 149 |
+
The method may not store state in the Codec instance. Use
|
| 150 |
+
StreamWriter for codecs which have to keep state in order to
|
| 151 |
+
make encoding efficient.
|
| 152 |
+
|
| 153 |
+
The encoder must be able to handle zero length input and
|
| 154 |
+
return an empty object of the output object type in this
|
| 155 |
+
situation.
|
| 156 |
+
|
| 157 |
+
"""
|
| 158 |
+
raise NotImplementedError
|
| 159 |
+
|
| 160 |
+
def decode(self, input, errors='strict'):
|
| 161 |
+
|
| 162 |
+
""" Decodes the object input and returns a tuple (output
|
| 163 |
+
object, length consumed).
|
| 164 |
+
|
| 165 |
+
input must be an object which provides the bf_getreadbuf
|
| 166 |
+
buffer slot. Python strings, buffer objects and memory
|
| 167 |
+
mapped files are examples of objects providing this slot.
|
| 168 |
+
|
| 169 |
+
errors defines the error handling to apply. It defaults to
|
| 170 |
+
'strict' handling.
|
| 171 |
+
|
| 172 |
+
The method may not store state in the Codec instance. Use
|
| 173 |
+
StreamReader for codecs which have to keep state in order to
|
| 174 |
+
make decoding efficient.
|
| 175 |
+
|
| 176 |
+
The decoder must be able to handle zero length input and
|
| 177 |
+
return an empty object of the output object type in this
|
| 178 |
+
situation.
|
| 179 |
+
|
| 180 |
+
"""
|
| 181 |
+
raise NotImplementedError
|
| 182 |
+
|
| 183 |
+
class IncrementalEncoder(object):
|
| 184 |
+
"""
|
| 185 |
+
An IncrementalEncoder encodes an input in multiple steps. The input can
|
| 186 |
+
be passed piece by piece to the encode() method. The IncrementalEncoder
|
| 187 |
+
remembers the state of the encoding process between calls to encode().
|
| 188 |
+
"""
|
| 189 |
+
def __init__(self, errors='strict'):
|
| 190 |
+
"""
|
| 191 |
+
Creates an IncrementalEncoder instance.
|
| 192 |
+
|
| 193 |
+
The IncrementalEncoder may use different error handling schemes by
|
| 194 |
+
providing the errors keyword argument. See the module docstring
|
| 195 |
+
for a list of possible values.
|
| 196 |
+
"""
|
| 197 |
+
self.errors = errors
|
| 198 |
+
self.buffer = ""
|
| 199 |
+
|
| 200 |
+
def encode(self, input, final=False):
|
| 201 |
+
"""
|
| 202 |
+
Encodes input and returns the resulting object.
|
| 203 |
+
"""
|
| 204 |
+
raise NotImplementedError
|
| 205 |
+
|
| 206 |
+
def reset(self):
|
| 207 |
+
"""
|
| 208 |
+
Resets the encoder to the initial state.
|
| 209 |
+
"""
|
| 210 |
+
|
| 211 |
+
def getstate(self):
|
| 212 |
+
"""
|
| 213 |
+
Return the current state of the encoder.
|
| 214 |
+
"""
|
| 215 |
+
return 0
|
| 216 |
+
|
| 217 |
+
def setstate(self, state):
|
| 218 |
+
"""
|
| 219 |
+
Set the current state of the encoder. state must have been
|
| 220 |
+
returned by getstate().
|
| 221 |
+
"""
|
| 222 |
+
|
| 223 |
+
class BufferedIncrementalEncoder(IncrementalEncoder):
|
| 224 |
+
"""
|
| 225 |
+
This subclass of IncrementalEncoder can be used as the baseclass for an
|
| 226 |
+
incremental encoder if the encoder must keep some of the output in a
|
| 227 |
+
buffer between calls to encode().
|
| 228 |
+
"""
|
| 229 |
+
def __init__(self, errors='strict'):
|
| 230 |
+
IncrementalEncoder.__init__(self, errors)
|
| 231 |
+
# unencoded input that is kept between calls to encode()
|
| 232 |
+
self.buffer = ""
|
| 233 |
+
|
| 234 |
+
def _buffer_encode(self, input, errors, final):
|
| 235 |
+
# Overwrite this method in subclasses: It must encode input
|
| 236 |
+
# and return an (output, length consumed) tuple
|
| 237 |
+
raise NotImplementedError
|
| 238 |
+
|
| 239 |
+
def encode(self, input, final=False):
|
| 240 |
+
# encode input (taking the buffer into account)
|
| 241 |
+
data = self.buffer + input
|
| 242 |
+
(result, consumed) = self._buffer_encode(data, self.errors, final)
|
| 243 |
+
# keep unencoded input until the next call
|
| 244 |
+
self.buffer = data[consumed:]
|
| 245 |
+
return result
|
| 246 |
+
|
| 247 |
+
def reset(self):
|
| 248 |
+
IncrementalEncoder.reset(self)
|
| 249 |
+
self.buffer = ""
|
| 250 |
+
|
| 251 |
+
def getstate(self):
|
| 252 |
+
return self.buffer or 0
|
| 253 |
+
|
| 254 |
+
def setstate(self, state):
|
| 255 |
+
self.buffer = state or ""
|
| 256 |
+
|
| 257 |
+
class IncrementalDecoder(object):
|
| 258 |
+
"""
|
| 259 |
+
An IncrementalDecoder decodes an input in multiple steps. The input can
|
| 260 |
+
be passed piece by piece to the decode() method. The IncrementalDecoder
|
| 261 |
+
remembers the state of the decoding process between calls to decode().
|
| 262 |
+
"""
|
| 263 |
+
def __init__(self, errors='strict'):
|
| 264 |
+
"""
|
| 265 |
+
Create an IncrementalDecoder instance.
|
| 266 |
+
|
| 267 |
+
The IncrementalDecoder may use different error handling schemes by
|
| 268 |
+
providing the errors keyword argument. See the module docstring
|
| 269 |
+
for a list of possible values.
|
| 270 |
+
"""
|
| 271 |
+
self.errors = errors
|
| 272 |
+
|
| 273 |
+
def decode(self, input, final=False):
|
| 274 |
+
"""
|
| 275 |
+
Decode input and returns the resulting object.
|
| 276 |
+
"""
|
| 277 |
+
raise NotImplementedError
|
| 278 |
+
|
| 279 |
+
def reset(self):
|
| 280 |
+
"""
|
| 281 |
+
Reset the decoder to the initial state.
|
| 282 |
+
"""
|
| 283 |
+
|
| 284 |
+
def getstate(self):
|
| 285 |
+
"""
|
| 286 |
+
Return the current state of the decoder.
|
| 287 |
+
|
| 288 |
+
This must be a (buffered_input, additional_state_info) tuple.
|
| 289 |
+
buffered_input must be a bytes object containing bytes that
|
| 290 |
+
were passed to decode() that have not yet been converted.
|
| 291 |
+
additional_state_info must be a non-negative integer
|
| 292 |
+
representing the state of the decoder WITHOUT yet having
|
| 293 |
+
processed the contents of buffered_input. In the initial state
|
| 294 |
+
and after reset(), getstate() must return (b"", 0).
|
| 295 |
+
"""
|
| 296 |
+
return (b"", 0)
|
| 297 |
+
|
| 298 |
+
def setstate(self, state):
|
| 299 |
+
"""
|
| 300 |
+
Set the current state of the decoder.
|
| 301 |
+
|
| 302 |
+
state must have been returned by getstate(). The effect of
|
| 303 |
+
setstate((b"", 0)) must be equivalent to reset().
|
| 304 |
+
"""
|
| 305 |
+
|
| 306 |
+
class BufferedIncrementalDecoder(IncrementalDecoder):
|
| 307 |
+
"""
|
| 308 |
+
This subclass of IncrementalDecoder can be used as the baseclass for an
|
| 309 |
+
incremental decoder if the decoder must be able to handle incomplete
|
| 310 |
+
byte sequences.
|
| 311 |
+
"""
|
| 312 |
+
def __init__(self, errors='strict'):
|
| 313 |
+
IncrementalDecoder.__init__(self, errors)
|
| 314 |
+
# undecoded input that is kept between calls to decode()
|
| 315 |
+
self.buffer = b""
|
| 316 |
+
|
| 317 |
+
def _buffer_decode(self, input, errors, final):
|
| 318 |
+
# Overwrite this method in subclasses: It must decode input
|
| 319 |
+
# and return an (output, length consumed) tuple
|
| 320 |
+
raise NotImplementedError
|
| 321 |
+
|
| 322 |
+
def decode(self, input, final=False):
|
| 323 |
+
# decode input (taking the buffer into account)
|
| 324 |
+
data = self.buffer + input
|
| 325 |
+
(result, consumed) = self._buffer_decode(data, self.errors, final)
|
| 326 |
+
# keep undecoded input until the next call
|
| 327 |
+
self.buffer = data[consumed:]
|
| 328 |
+
return result
|
| 329 |
+
|
| 330 |
+
def reset(self):
|
| 331 |
+
IncrementalDecoder.reset(self)
|
| 332 |
+
self.buffer = b""
|
| 333 |
+
|
| 334 |
+
def getstate(self):
|
| 335 |
+
# additional state info is always 0
|
| 336 |
+
return (self.buffer, 0)
|
| 337 |
+
|
| 338 |
+
def setstate(self, state):
|
| 339 |
+
# ignore additional state info
|
| 340 |
+
self.buffer = state[0]
|
| 341 |
+
|
| 342 |
+
#
|
| 343 |
+
# The StreamWriter and StreamReader class provide generic working
|
| 344 |
+
# interfaces which can be used to implement new encoding submodules
|
| 345 |
+
# very easily. See encodings/utf_8.py for an example on how this is
|
| 346 |
+
# done.
|
| 347 |
+
#
|
| 348 |
+
|
| 349 |
+
class StreamWriter(Codec):
|
| 350 |
+
|
| 351 |
+
def __init__(self, stream, errors='strict'):
|
| 352 |
+
|
| 353 |
+
""" Creates a StreamWriter instance.
|
| 354 |
+
|
| 355 |
+
stream must be a file-like object open for writing.
|
| 356 |
+
|
| 357 |
+
The StreamWriter may use different error handling
|
| 358 |
+
schemes by providing the errors keyword argument. These
|
| 359 |
+
parameters are predefined:
|
| 360 |
+
|
| 361 |
+
'strict' - raise a ValueError (or a subclass)
|
| 362 |
+
'ignore' - ignore the character and continue with the next
|
| 363 |
+
'replace'- replace with a suitable replacement character
|
| 364 |
+
'xmlcharrefreplace' - Replace with the appropriate XML
|
| 365 |
+
character reference.
|
| 366 |
+
'backslashreplace' - Replace with backslashed escape
|
| 367 |
+
sequences.
|
| 368 |
+
'namereplace' - Replace with \\N{...} escape sequences.
|
| 369 |
+
|
| 370 |
+
The set of allowed parameter values can be extended via
|
| 371 |
+
register_error.
|
| 372 |
+
"""
|
| 373 |
+
self.stream = stream
|
| 374 |
+
self.errors = errors
|
| 375 |
+
|
| 376 |
+
def write(self, object):
|
| 377 |
+
|
| 378 |
+
""" Writes the object's contents encoded to self.stream.
|
| 379 |
+
"""
|
| 380 |
+
data, consumed = self.encode(object, self.errors)
|
| 381 |
+
self.stream.write(data)
|
| 382 |
+
|
| 383 |
+
def writelines(self, list):
|
| 384 |
+
|
| 385 |
+
""" Writes the concatenated list of strings to the stream
|
| 386 |
+
using .write().
|
| 387 |
+
"""
|
| 388 |
+
self.write(''.join(list))
|
| 389 |
+
|
| 390 |
+
def reset(self):
|
| 391 |
+
|
| 392 |
+
""" Resets the codec buffers used for keeping internal state.
|
| 393 |
+
|
| 394 |
+
Calling this method should ensure that the data on the
|
| 395 |
+
output is put into a clean state, that allows appending
|
| 396 |
+
of new fresh data without having to rescan the whole
|
| 397 |
+
stream to recover state.
|
| 398 |
+
|
| 399 |
+
"""
|
| 400 |
+
pass
|
| 401 |
+
|
| 402 |
+
def seek(self, offset, whence=0):
|
| 403 |
+
self.stream.seek(offset, whence)
|
| 404 |
+
if whence == 0 and offset == 0:
|
| 405 |
+
self.reset()
|
| 406 |
+
|
| 407 |
+
def __getattr__(self, name,
|
| 408 |
+
getattr=getattr):
|
| 409 |
+
|
| 410 |
+
""" Inherit all other methods from the underlying stream.
|
| 411 |
+
"""
|
| 412 |
+
return getattr(self.stream, name)
|
| 413 |
+
|
| 414 |
+
def __enter__(self):
|
| 415 |
+
return self
|
| 416 |
+
|
| 417 |
+
def __exit__(self, type, value, tb):
|
| 418 |
+
self.stream.close()
|
| 419 |
+
|
| 420 |
+
def __reduce_ex__(self, proto):
|
| 421 |
+
raise TypeError("can't serialize %s" % self.__class__.__name__)
|
| 422 |
+
|
| 423 |
+
###
|
| 424 |
+
|
| 425 |
+
class StreamReader(Codec):
|
| 426 |
+
|
| 427 |
+
charbuffertype = str
|
| 428 |
+
|
| 429 |
+
def __init__(self, stream, errors='strict'):
|
| 430 |
+
|
| 431 |
+
""" Creates a StreamReader instance.
|
| 432 |
+
|
| 433 |
+
stream must be a file-like object open for reading.
|
| 434 |
+
|
| 435 |
+
The StreamReader may use different error handling
|
| 436 |
+
schemes by providing the errors keyword argument. These
|
| 437 |
+
parameters are predefined:
|
| 438 |
+
|
| 439 |
+
'strict' - raise a ValueError (or a subclass)
|
| 440 |
+
'ignore' - ignore the character and continue with the next
|
| 441 |
+
'replace'- replace with a suitable replacement character
|
| 442 |
+
'backslashreplace' - Replace with backslashed escape sequences;
|
| 443 |
+
|
| 444 |
+
The set of allowed parameter values can be extended via
|
| 445 |
+
register_error.
|
| 446 |
+
"""
|
| 447 |
+
self.stream = stream
|
| 448 |
+
self.errors = errors
|
| 449 |
+
self.bytebuffer = b""
|
| 450 |
+
self._empty_charbuffer = self.charbuffertype()
|
| 451 |
+
self.charbuffer = self._empty_charbuffer
|
| 452 |
+
self.linebuffer = None
|
| 453 |
+
|
| 454 |
+
def decode(self, input, errors='strict'):
|
| 455 |
+
raise NotImplementedError
|
| 456 |
+
|
| 457 |
+
def read(self, size=-1, chars=-1, firstline=False):
|
| 458 |
+
|
| 459 |
+
""" Decodes data from the stream self.stream and returns the
|
| 460 |
+
resulting object.
|
| 461 |
+
|
| 462 |
+
chars indicates the number of decoded code points or bytes to
|
| 463 |
+
return. read() will never return more data than requested,
|
| 464 |
+
but it might return less, if there is not enough available.
|
| 465 |
+
|
| 466 |
+
size indicates the approximate maximum number of decoded
|
| 467 |
+
bytes or code points to read for decoding. The decoder
|
| 468 |
+
can modify this setting as appropriate. The default value
|
| 469 |
+
-1 indicates to read and decode as much as possible. size
|
| 470 |
+
is intended to prevent having to decode huge files in one
|
| 471 |
+
step.
|
| 472 |
+
|
| 473 |
+
If firstline is true, and a UnicodeDecodeError happens
|
| 474 |
+
after the first line terminator in the input only the first line
|
| 475 |
+
will be returned, the rest of the input will be kept until the
|
| 476 |
+
next call to read().
|
| 477 |
+
|
| 478 |
+
The method should use a greedy read strategy, meaning that
|
| 479 |
+
it should read as much data as is allowed within the
|
| 480 |
+
definition of the encoding and the given size, e.g. if
|
| 481 |
+
optional encoding endings or state markers are available
|
| 482 |
+
on the stream, these should be read too.
|
| 483 |
+
"""
|
| 484 |
+
# If we have lines cached, first merge them back into characters
|
| 485 |
+
if self.linebuffer:
|
| 486 |
+
self.charbuffer = self._empty_charbuffer.join(self.linebuffer)
|
| 487 |
+
self.linebuffer = None
|
| 488 |
+
|
| 489 |
+
if chars < 0:
|
| 490 |
+
# For compatibility with other read() methods that take a
|
| 491 |
+
# single argument
|
| 492 |
+
chars = size
|
| 493 |
+
|
| 494 |
+
# read until we get the required number of characters (if available)
|
| 495 |
+
while True:
|
| 496 |
+
# can the request be satisfied from the character buffer?
|
| 497 |
+
if chars >= 0:
|
| 498 |
+
if len(self.charbuffer) >= chars:
|
| 499 |
+
break
|
| 500 |
+
# we need more data
|
| 501 |
+
if size < 0:
|
| 502 |
+
newdata = self.stream.read()
|
| 503 |
+
else:
|
| 504 |
+
newdata = self.stream.read(size)
|
| 505 |
+
# decode bytes (those remaining from the last call included)
|
| 506 |
+
data = self.bytebuffer + newdata
|
| 507 |
+
if not data:
|
| 508 |
+
break
|
| 509 |
+
try:
|
| 510 |
+
newchars, decodedbytes = self.decode(data, self.errors)
|
| 511 |
+
except UnicodeDecodeError as exc:
|
| 512 |
+
if firstline:
|
| 513 |
+
newchars, decodedbytes = \
|
| 514 |
+
self.decode(data[:exc.start], self.errors)
|
| 515 |
+
lines = newchars.splitlines(keepends=True)
|
| 516 |
+
if len(lines)<=1:
|
| 517 |
+
raise
|
| 518 |
+
else:
|
| 519 |
+
raise
|
| 520 |
+
# keep undecoded bytes until the next call
|
| 521 |
+
self.bytebuffer = data[decodedbytes:]
|
| 522 |
+
# put new characters in the character buffer
|
| 523 |
+
self.charbuffer += newchars
|
| 524 |
+
# there was no data available
|
| 525 |
+
if not newdata:
|
| 526 |
+
break
|
| 527 |
+
if chars < 0:
|
| 528 |
+
# Return everything we've got
|
| 529 |
+
result = self.charbuffer
|
| 530 |
+
self.charbuffer = self._empty_charbuffer
|
| 531 |
+
else:
|
| 532 |
+
# Return the first chars characters
|
| 533 |
+
result = self.charbuffer[:chars]
|
| 534 |
+
self.charbuffer = self.charbuffer[chars:]
|
| 535 |
+
return result
|
| 536 |
+
|
| 537 |
+
def readline(self, size=None, keepends=True):
|
| 538 |
+
|
| 539 |
+
""" Read one line from the input stream and return the
|
| 540 |
+
decoded data.
|
| 541 |
+
|
| 542 |
+
size, if given, is passed as size argument to the
|
| 543 |
+
read() method.
|
| 544 |
+
|
| 545 |
+
"""
|
| 546 |
+
# If we have lines cached from an earlier read, return
|
| 547 |
+
# them unconditionally
|
| 548 |
+
if self.linebuffer:
|
| 549 |
+
line = self.linebuffer[0]
|
| 550 |
+
del self.linebuffer[0]
|
| 551 |
+
if len(self.linebuffer) == 1:
|
| 552 |
+
# revert to charbuffer mode; we might need more data
|
| 553 |
+
# next time
|
| 554 |
+
self.charbuffer = self.linebuffer[0]
|
| 555 |
+
self.linebuffer = None
|
| 556 |
+
if not keepends:
|
| 557 |
+
line = line.splitlines(keepends=False)[0]
|
| 558 |
+
return line
|
| 559 |
+
|
| 560 |
+
readsize = size or 72
|
| 561 |
+
line = self._empty_charbuffer
|
| 562 |
+
# If size is given, we call read() only once
|
| 563 |
+
while True:
|
| 564 |
+
data = self.read(readsize, firstline=True)
|
| 565 |
+
if data:
|
| 566 |
+
# If we're at a "\r" read one extra character (which might
|
| 567 |
+
# be a "\n") to get a proper line ending. If the stream is
|
| 568 |
+
# temporarily exhausted we return the wrong line ending.
|
| 569 |
+
if (isinstance(data, str) and data.endswith("\r")) or \
|
| 570 |
+
(isinstance(data, bytes) and data.endswith(b"\r")):
|
| 571 |
+
data += self.read(size=1, chars=1)
|
| 572 |
+
|
| 573 |
+
line += data
|
| 574 |
+
lines = line.splitlines(keepends=True)
|
| 575 |
+
if lines:
|
| 576 |
+
if len(lines) > 1:
|
| 577 |
+
# More than one line result; the first line is a full line
|
| 578 |
+
# to return
|
| 579 |
+
line = lines[0]
|
| 580 |
+
del lines[0]
|
| 581 |
+
if len(lines) > 1:
|
| 582 |
+
# cache the remaining lines
|
| 583 |
+
lines[-1] += self.charbuffer
|
| 584 |
+
self.linebuffer = lines
|
| 585 |
+
self.charbuffer = None
|
| 586 |
+
else:
|
| 587 |
+
# only one remaining line, put it back into charbuffer
|
| 588 |
+
self.charbuffer = lines[0] + self.charbuffer
|
| 589 |
+
if not keepends:
|
| 590 |
+
line = line.splitlines(keepends=False)[0]
|
| 591 |
+
break
|
| 592 |
+
line0withend = lines[0]
|
| 593 |
+
line0withoutend = lines[0].splitlines(keepends=False)[0]
|
| 594 |
+
if line0withend != line0withoutend: # We really have a line end
|
| 595 |
+
# Put the rest back together and keep it until the next call
|
| 596 |
+
self.charbuffer = self._empty_charbuffer.join(lines[1:]) + \
|
| 597 |
+
self.charbuffer
|
| 598 |
+
if keepends:
|
| 599 |
+
line = line0withend
|
| 600 |
+
else:
|
| 601 |
+
line = line0withoutend
|
| 602 |
+
break
|
| 603 |
+
# we didn't get anything or this was our only try
|
| 604 |
+
if not data or size is not None:
|
| 605 |
+
if line and not keepends:
|
| 606 |
+
line = line.splitlines(keepends=False)[0]
|
| 607 |
+
break
|
| 608 |
+
if readsize < 8000:
|
| 609 |
+
readsize *= 2
|
| 610 |
+
return line
|
| 611 |
+
|
| 612 |
+
def readlines(self, sizehint=None, keepends=True):
|
| 613 |
+
|
| 614 |
+
""" Read all lines available on the input stream
|
| 615 |
+
and return them as a list.
|
| 616 |
+
|
| 617 |
+
Line breaks are implemented using the codec's decoder
|
| 618 |
+
method and are included in the list entries.
|
| 619 |
+
|
| 620 |
+
sizehint, if given, is ignored since there is no efficient
|
| 621 |
+
way of finding the true end-of-line.
|
| 622 |
+
|
| 623 |
+
"""
|
| 624 |
+
data = self.read()
|
| 625 |
+
return data.splitlines(keepends)
|
| 626 |
+
|
| 627 |
+
def reset(self):
|
| 628 |
+
|
| 629 |
+
""" Resets the codec buffers used for keeping internal state.
|
| 630 |
+
|
| 631 |
+
Note that no stream repositioning should take place.
|
| 632 |
+
This method is primarily intended to be able to recover
|
| 633 |
+
from decoding errors.
|
| 634 |
+
|
| 635 |
+
"""
|
| 636 |
+
self.bytebuffer = b""
|
| 637 |
+
self.charbuffer = self._empty_charbuffer
|
| 638 |
+
self.linebuffer = None
|
| 639 |
+
|
| 640 |
+
def seek(self, offset, whence=0):
|
| 641 |
+
""" Set the input stream's current position.
|
| 642 |
+
|
| 643 |
+
Resets the codec buffers used for keeping state.
|
| 644 |
+
"""
|
| 645 |
+
self.stream.seek(offset, whence)
|
| 646 |
+
self.reset()
|
| 647 |
+
|
| 648 |
+
def __next__(self):
|
| 649 |
+
|
| 650 |
+
""" Return the next decoded line from the input stream."""
|
| 651 |
+
line = self.readline()
|
| 652 |
+
if line:
|
| 653 |
+
return line
|
| 654 |
+
raise StopIteration
|
| 655 |
+
|
| 656 |
+
def __iter__(self):
|
| 657 |
+
return self
|
| 658 |
+
|
| 659 |
+
def __getattr__(self, name,
|
| 660 |
+
getattr=getattr):
|
| 661 |
+
|
| 662 |
+
""" Inherit all other methods from the underlying stream.
|
| 663 |
+
"""
|
| 664 |
+
return getattr(self.stream, name)
|
| 665 |
+
|
| 666 |
+
def __enter__(self):
|
| 667 |
+
return self
|
| 668 |
+
|
| 669 |
+
def __exit__(self, type, value, tb):
|
| 670 |
+
self.stream.close()
|
| 671 |
+
|
| 672 |
+
def __reduce_ex__(self, proto):
|
| 673 |
+
raise TypeError("can't serialize %s" % self.__class__.__name__)
|
| 674 |
+
|
| 675 |
+
###
|
| 676 |
+
|
| 677 |
+
class StreamReaderWriter:
|
| 678 |
+
|
| 679 |
+
""" StreamReaderWriter instances allow wrapping streams which
|
| 680 |
+
work in both read and write modes.
|
| 681 |
+
|
| 682 |
+
The design is such that one can use the factory functions
|
| 683 |
+
returned by the codec.lookup() function to construct the
|
| 684 |
+
instance.
|
| 685 |
+
|
| 686 |
+
"""
|
| 687 |
+
# Optional attributes set by the file wrappers below
|
| 688 |
+
encoding = 'unknown'
|
| 689 |
+
|
| 690 |
+
def __init__(self, stream, Reader, Writer, errors='strict'):
|
| 691 |
+
|
| 692 |
+
""" Creates a StreamReaderWriter instance.
|
| 693 |
+
|
| 694 |
+
stream must be a Stream-like object.
|
| 695 |
+
|
| 696 |
+
Reader, Writer must be factory functions or classes
|
| 697 |
+
providing the StreamReader, StreamWriter interface resp.
|
| 698 |
+
|
| 699 |
+
Error handling is done in the same way as defined for the
|
| 700 |
+
StreamWriter/Readers.
|
| 701 |
+
|
| 702 |
+
"""
|
| 703 |
+
self.stream = stream
|
| 704 |
+
self.reader = Reader(stream, errors)
|
| 705 |
+
self.writer = Writer(stream, errors)
|
| 706 |
+
self.errors = errors
|
| 707 |
+
|
| 708 |
+
def read(self, size=-1):
|
| 709 |
+
|
| 710 |
+
return self.reader.read(size)
|
| 711 |
+
|
| 712 |
+
def readline(self, size=None, keepends=True):
|
| 713 |
+
|
| 714 |
+
return self.reader.readline(size, keepends)
|
| 715 |
+
|
| 716 |
+
def readlines(self, sizehint=None, keepends=True):
|
| 717 |
+
|
| 718 |
+
return self.reader.readlines(sizehint, keepends)
|
| 719 |
+
|
| 720 |
+
def __next__(self):
|
| 721 |
+
|
| 722 |
+
""" Return the next decoded line from the input stream."""
|
| 723 |
+
return next(self.reader)
|
| 724 |
+
|
| 725 |
+
def __iter__(self):
|
| 726 |
+
return self
|
| 727 |
+
|
| 728 |
+
def write(self, data):
|
| 729 |
+
|
| 730 |
+
return self.writer.write(data)
|
| 731 |
+
|
| 732 |
+
def writelines(self, list):
|
| 733 |
+
|
| 734 |
+
return self.writer.writelines(list)
|
| 735 |
+
|
| 736 |
+
def reset(self):
|
| 737 |
+
|
| 738 |
+
self.reader.reset()
|
| 739 |
+
self.writer.reset()
|
| 740 |
+
|
| 741 |
+
def seek(self, offset, whence=0):
|
| 742 |
+
self.stream.seek(offset, whence)
|
| 743 |
+
self.reader.reset()
|
| 744 |
+
if whence == 0 and offset == 0:
|
| 745 |
+
self.writer.reset()
|
| 746 |
+
|
| 747 |
+
def __getattr__(self, name,
|
| 748 |
+
getattr=getattr):
|
| 749 |
+
|
| 750 |
+
""" Inherit all other methods from the underlying stream.
|
| 751 |
+
"""
|
| 752 |
+
return getattr(self.stream, name)
|
| 753 |
+
|
| 754 |
+
# these are needed to make "with StreamReaderWriter(...)" work properly
|
| 755 |
+
|
| 756 |
+
def __enter__(self):
|
| 757 |
+
return self
|
| 758 |
+
|
| 759 |
+
def __exit__(self, type, value, tb):
|
| 760 |
+
self.stream.close()
|
| 761 |
+
|
| 762 |
+
def __reduce_ex__(self, proto):
|
| 763 |
+
raise TypeError("can't serialize %s" % self.__class__.__name__)
|
| 764 |
+
|
| 765 |
+
###
|
| 766 |
+
|
| 767 |
+
class StreamRecoder:
|
| 768 |
+
|
| 769 |
+
""" StreamRecoder instances translate data from one encoding to another.
|
| 770 |
+
|
| 771 |
+
They use the complete set of APIs returned by the
|
| 772 |
+
codecs.lookup() function to implement their task.
|
| 773 |
+
|
| 774 |
+
Data written to the StreamRecoder is first decoded into an
|
| 775 |
+
intermediate format (depending on the "decode" codec) and then
|
| 776 |
+
written to the underlying stream using an instance of the provided
|
| 777 |
+
Writer class.
|
| 778 |
+
|
| 779 |
+
In the other direction, data is read from the underlying stream using
|
| 780 |
+
a Reader instance and then encoded and returned to the caller.
|
| 781 |
+
|
| 782 |
+
"""
|
| 783 |
+
# Optional attributes set by the file wrappers below
|
| 784 |
+
data_encoding = 'unknown'
|
| 785 |
+
file_encoding = 'unknown'
|
| 786 |
+
|
| 787 |
+
def __init__(self, stream, encode, decode, Reader, Writer,
|
| 788 |
+
errors='strict'):
|
| 789 |
+
|
| 790 |
+
""" Creates a StreamRecoder instance which implements a two-way
|
| 791 |
+
conversion: encode and decode work on the frontend (the
|
| 792 |
+
data visible to .read() and .write()) while Reader and Writer
|
| 793 |
+
work on the backend (the data in stream).
|
| 794 |
+
|
| 795 |
+
You can use these objects to do transparent
|
| 796 |
+
transcodings from e.g. latin-1 to utf-8 and back.
|
| 797 |
+
|
| 798 |
+
stream must be a file-like object.
|
| 799 |
+
|
| 800 |
+
encode and decode must adhere to the Codec interface; Reader and
|
| 801 |
+
Writer must be factory functions or classes providing the
|
| 802 |
+
StreamReader and StreamWriter interfaces resp.
|
| 803 |
+
|
| 804 |
+
Error handling is done in the same way as defined for the
|
| 805 |
+
StreamWriter/Readers.
|
| 806 |
+
|
| 807 |
+
"""
|
| 808 |
+
self.stream = stream
|
| 809 |
+
self.encode = encode
|
| 810 |
+
self.decode = decode
|
| 811 |
+
self.reader = Reader(stream, errors)
|
| 812 |
+
self.writer = Writer(stream, errors)
|
| 813 |
+
self.errors = errors
|
| 814 |
+
|
| 815 |
+
def read(self, size=-1):
|
| 816 |
+
|
| 817 |
+
data = self.reader.read(size)
|
| 818 |
+
data, bytesencoded = self.encode(data, self.errors)
|
| 819 |
+
return data
|
| 820 |
+
|
| 821 |
+
def readline(self, size=None):
|
| 822 |
+
|
| 823 |
+
if size is None:
|
| 824 |
+
data = self.reader.readline()
|
| 825 |
+
else:
|
| 826 |
+
data = self.reader.readline(size)
|
| 827 |
+
data, bytesencoded = self.encode(data, self.errors)
|
| 828 |
+
return data
|
| 829 |
+
|
| 830 |
+
def readlines(self, sizehint=None):
|
| 831 |
+
|
| 832 |
+
data = self.reader.read()
|
| 833 |
+
data, bytesencoded = self.encode(data, self.errors)
|
| 834 |
+
return data.splitlines(keepends=True)
|
| 835 |
+
|
| 836 |
+
def __next__(self):
|
| 837 |
+
|
| 838 |
+
""" Return the next decoded line from the input stream."""
|
| 839 |
+
data = next(self.reader)
|
| 840 |
+
data, bytesencoded = self.encode(data, self.errors)
|
| 841 |
+
return data
|
| 842 |
+
|
| 843 |
+
def __iter__(self):
|
| 844 |
+
return self
|
| 845 |
+
|
| 846 |
+
def write(self, data):
|
| 847 |
+
|
| 848 |
+
data, bytesdecoded = self.decode(data, self.errors)
|
| 849 |
+
return self.writer.write(data)
|
| 850 |
+
|
| 851 |
+
def writelines(self, list):
|
| 852 |
+
|
| 853 |
+
data = b''.join(list)
|
| 854 |
+
data, bytesdecoded = self.decode(data, self.errors)
|
| 855 |
+
return self.writer.write(data)
|
| 856 |
+
|
| 857 |
+
def reset(self):
|
| 858 |
+
|
| 859 |
+
self.reader.reset()
|
| 860 |
+
self.writer.reset()
|
| 861 |
+
|
| 862 |
+
def seek(self, offset, whence=0):
|
| 863 |
+
# Seeks must be propagated to both the readers and writers
|
| 864 |
+
# as they might need to reset their internal buffers.
|
| 865 |
+
self.reader.seek(offset, whence)
|
| 866 |
+
self.writer.seek(offset, whence)
|
| 867 |
+
|
| 868 |
+
def __getattr__(self, name,
|
| 869 |
+
getattr=getattr):
|
| 870 |
+
|
| 871 |
+
""" Inherit all other methods from the underlying stream.
|
| 872 |
+
"""
|
| 873 |
+
return getattr(self.stream, name)
|
| 874 |
+
|
| 875 |
+
def __enter__(self):
|
| 876 |
+
return self
|
| 877 |
+
|
| 878 |
+
def __exit__(self, type, value, tb):
|
| 879 |
+
self.stream.close()
|
| 880 |
+
|
| 881 |
+
def __reduce_ex__(self, proto):
|
| 882 |
+
raise TypeError("can't serialize %s" % self.__class__.__name__)
|
| 883 |
+
|
| 884 |
+
### Shortcuts
|
| 885 |
+
|
| 886 |
+
def open(filename, mode='r', encoding=None, errors='strict', buffering=-1):
|
| 887 |
+
""" Open an encoded file using the given mode and return
|
| 888 |
+
a wrapped version providing transparent encoding/decoding.
|
| 889 |
+
|
| 890 |
+
Note: The wrapped version will only accept the object format
|
| 891 |
+
defined by the codecs, i.e. Unicode objects for most builtin
|
| 892 |
+
codecs. Output is also codec dependent and will usually be
|
| 893 |
+
Unicode as well.
|
| 894 |
+
|
| 895 |
+
If encoding is not None, then the
|
| 896 |
+
underlying encoded files are always opened in binary mode.
|
| 897 |
+
The default file mode is 'r', meaning to open the file in read mode.
|
| 898 |
+
|
| 899 |
+
encoding specifies the encoding which is to be used for the
|
| 900 |
+
file.
|
| 901 |
+
|
| 902 |
+
errors may be given to define the error handling. It defaults
|
| 903 |
+
to 'strict' which causes ValueErrors to be raised in case an
|
| 904 |
+
encoding error occurs.
|
| 905 |
+
|
| 906 |
+
buffering has the same meaning as for the builtin open() API.
|
| 907 |
+
It defaults to -1 which means that the default buffer size will
|
| 908 |
+
be used.
|
| 909 |
+
|
| 910 |
+
The returned wrapped file object provides an extra attribute
|
| 911 |
+
.encoding which allows querying the used encoding. This
|
| 912 |
+
attribute is only available if an encoding was specified as
|
| 913 |
+
parameter.
|
| 914 |
+
"""
|
| 915 |
+
import warnings
|
| 916 |
+
warnings.warn("codecs.open() is deprecated. Use open() instead.",
|
| 917 |
+
DeprecationWarning, stacklevel=2)
|
| 918 |
+
|
| 919 |
+
if encoding is not None and \
|
| 920 |
+
'b' not in mode:
|
| 921 |
+
# Force opening of the file in binary mode
|
| 922 |
+
mode = mode + 'b'
|
| 923 |
+
file = builtins.open(filename, mode, buffering)
|
| 924 |
+
if encoding is None:
|
| 925 |
+
return file
|
| 926 |
+
|
| 927 |
+
try:
|
| 928 |
+
info = lookup(encoding)
|
| 929 |
+
srw = StreamReaderWriter(file, info.streamreader, info.streamwriter, errors)
|
| 930 |
+
# Add attributes to simplify introspection
|
| 931 |
+
srw.encoding = encoding
|
| 932 |
+
return srw
|
| 933 |
+
except:
|
| 934 |
+
file.close()
|
| 935 |
+
raise
|
| 936 |
+
|
| 937 |
+
def EncodedFile(file, data_encoding, file_encoding=None, errors='strict'):
|
| 938 |
+
|
| 939 |
+
""" Return a wrapped version of file which provides transparent
|
| 940 |
+
encoding translation.
|
| 941 |
+
|
| 942 |
+
Data written to the wrapped file is decoded according
|
| 943 |
+
to the given data_encoding and then encoded to the underlying
|
| 944 |
+
file using file_encoding. The intermediate data type
|
| 945 |
+
will usually be Unicode but depends on the specified codecs.
|
| 946 |
+
|
| 947 |
+
Bytes read from the file are decoded using file_encoding and then
|
| 948 |
+
passed back to the caller encoded using data_encoding.
|
| 949 |
+
|
| 950 |
+
If file_encoding is not given, it defaults to data_encoding.
|
| 951 |
+
|
| 952 |
+
errors may be given to define the error handling. It defaults
|
| 953 |
+
to 'strict' which causes ValueErrors to be raised in case an
|
| 954 |
+
encoding error occurs.
|
| 955 |
+
|
| 956 |
+
The returned wrapped file object provides two extra attributes
|
| 957 |
+
.data_encoding and .file_encoding which reflect the given
|
| 958 |
+
parameters of the same name. The attributes can be used for
|
| 959 |
+
introspection by Python programs.
|
| 960 |
+
|
| 961 |
+
"""
|
| 962 |
+
if file_encoding is None:
|
| 963 |
+
file_encoding = data_encoding
|
| 964 |
+
data_info = lookup(data_encoding)
|
| 965 |
+
file_info = lookup(file_encoding)
|
| 966 |
+
sr = StreamRecoder(file, data_info.encode, data_info.decode,
|
| 967 |
+
file_info.streamreader, file_info.streamwriter, errors)
|
| 968 |
+
# Add attributes to simplify introspection
|
| 969 |
+
sr.data_encoding = data_encoding
|
| 970 |
+
sr.file_encoding = file_encoding
|
| 971 |
+
return sr
|
| 972 |
+
|
| 973 |
+
### Helpers for codec lookup
|
| 974 |
+
|
| 975 |
+
def getencoder(encoding):
|
| 976 |
+
|
| 977 |
+
""" Lookup up the codec for the given encoding and return
|
| 978 |
+
its encoder function.
|
| 979 |
+
|
| 980 |
+
Raises a LookupError in case the encoding cannot be found.
|
| 981 |
+
|
| 982 |
+
"""
|
| 983 |
+
return lookup(encoding).encode
|
| 984 |
+
|
| 985 |
+
def getdecoder(encoding):
|
| 986 |
+
|
| 987 |
+
""" Lookup up the codec for the given encoding and return
|
| 988 |
+
its decoder function.
|
| 989 |
+
|
| 990 |
+
Raises a LookupError in case the encoding cannot be found.
|
| 991 |
+
|
| 992 |
+
"""
|
| 993 |
+
return lookup(encoding).decode
|
| 994 |
+
|
| 995 |
+
def getincrementalencoder(encoding):
|
| 996 |
+
|
| 997 |
+
""" Lookup up the codec for the given encoding and return
|
| 998 |
+
its IncrementalEncoder class or factory function.
|
| 999 |
+
|
| 1000 |
+
Raises a LookupError in case the encoding cannot be found
|
| 1001 |
+
or the codecs doesn't provide an incremental encoder.
|
| 1002 |
+
|
| 1003 |
+
"""
|
| 1004 |
+
encoder = lookup(encoding).incrementalencoder
|
| 1005 |
+
if encoder is None:
|
| 1006 |
+
raise LookupError(encoding)
|
| 1007 |
+
return encoder
|
| 1008 |
+
|
| 1009 |
+
def getincrementaldecoder(encoding):
|
| 1010 |
+
|
| 1011 |
+
""" Lookup up the codec for the given encoding and return
|
| 1012 |
+
its IncrementalDecoder class or factory function.
|
| 1013 |
+
|
| 1014 |
+
Raises a LookupError in case the encoding cannot be found
|
| 1015 |
+
or the codecs doesn't provide an incremental decoder.
|
| 1016 |
+
|
| 1017 |
+
"""
|
| 1018 |
+
decoder = lookup(encoding).incrementaldecoder
|
| 1019 |
+
if decoder is None:
|
| 1020 |
+
raise LookupError(encoding)
|
| 1021 |
+
return decoder
|
| 1022 |
+
|
| 1023 |
+
def getreader(encoding):
|
| 1024 |
+
|
| 1025 |
+
""" Lookup up the codec for the given encoding and return
|
| 1026 |
+
its StreamReader class or factory function.
|
| 1027 |
+
|
| 1028 |
+
Raises a LookupError in case the encoding cannot be found.
|
| 1029 |
+
|
| 1030 |
+
"""
|
| 1031 |
+
return lookup(encoding).streamreader
|
| 1032 |
+
|
| 1033 |
+
def getwriter(encoding):
|
| 1034 |
+
|
| 1035 |
+
""" Lookup up the codec for the given encoding and return
|
| 1036 |
+
its StreamWriter class or factory function.
|
| 1037 |
+
|
| 1038 |
+
Raises a LookupError in case the encoding cannot be found.
|
| 1039 |
+
|
| 1040 |
+
"""
|
| 1041 |
+
return lookup(encoding).streamwriter
|
| 1042 |
+
|
| 1043 |
+
def iterencode(iterator, encoding, errors='strict', **kwargs):
|
| 1044 |
+
"""
|
| 1045 |
+
Encoding iterator.
|
| 1046 |
+
|
| 1047 |
+
Encodes the input strings from the iterator using an IncrementalEncoder.
|
| 1048 |
+
|
| 1049 |
+
errors and kwargs are passed through to the IncrementalEncoder
|
| 1050 |
+
constructor.
|
| 1051 |
+
"""
|
| 1052 |
+
encoder = getincrementalencoder(encoding)(errors, **kwargs)
|
| 1053 |
+
for input in iterator:
|
| 1054 |
+
output = encoder.encode(input)
|
| 1055 |
+
if output:
|
| 1056 |
+
yield output
|
| 1057 |
+
output = encoder.encode("", True)
|
| 1058 |
+
if output:
|
| 1059 |
+
yield output
|
| 1060 |
+
|
| 1061 |
+
def iterdecode(iterator, encoding, errors='strict', **kwargs):
|
| 1062 |
+
"""
|
| 1063 |
+
Decoding iterator.
|
| 1064 |
+
|
| 1065 |
+
Decodes the input strings from the iterator using an IncrementalDecoder.
|
| 1066 |
+
|
| 1067 |
+
errors and kwargs are passed through to the IncrementalDecoder
|
| 1068 |
+
constructor.
|
| 1069 |
+
"""
|
| 1070 |
+
decoder = getincrementaldecoder(encoding)(errors, **kwargs)
|
| 1071 |
+
for input in iterator:
|
| 1072 |
+
output = decoder.decode(input)
|
| 1073 |
+
if output:
|
| 1074 |
+
yield output
|
| 1075 |
+
output = decoder.decode(b"", True)
|
| 1076 |
+
if output:
|
| 1077 |
+
yield output
|
| 1078 |
+
|
| 1079 |
+
### Helpers for charmap-based codecs
|
| 1080 |
+
|
| 1081 |
+
def make_identity_dict(rng):
|
| 1082 |
+
|
| 1083 |
+
""" make_identity_dict(rng) -> dict
|
| 1084 |
+
|
| 1085 |
+
Return a dictionary where elements of the rng sequence are
|
| 1086 |
+
mapped to themselves.
|
| 1087 |
+
|
| 1088 |
+
"""
|
| 1089 |
+
return {i:i for i in rng}
|
| 1090 |
+
|
| 1091 |
+
def make_encoding_map(decoding_map):
|
| 1092 |
+
|
| 1093 |
+
""" Creates an encoding map from a decoding map.
|
| 1094 |
+
|
| 1095 |
+
If a target mapping in the decoding map occurs multiple
|
| 1096 |
+
times, then that target is mapped to None (undefined mapping),
|
| 1097 |
+
causing an exception when encountered by the charmap codec
|
| 1098 |
+
during translation.
|
| 1099 |
+
|
| 1100 |
+
One example where this happens is cp875.py which decodes
|
| 1101 |
+
multiple character to \\u001a.
|
| 1102 |
+
|
| 1103 |
+
"""
|
| 1104 |
+
m = {}
|
| 1105 |
+
for k,v in decoding_map.items():
|
| 1106 |
+
if not v in m:
|
| 1107 |
+
m[v] = k
|
| 1108 |
+
else:
|
| 1109 |
+
m[v] = None
|
| 1110 |
+
return m
|
| 1111 |
+
|
| 1112 |
+
### error handlers
|
| 1113 |
+
|
| 1114 |
+
strict_errors = lookup_error("strict")
|
| 1115 |
+
ignore_errors = lookup_error("ignore")
|
| 1116 |
+
replace_errors = lookup_error("replace")
|
| 1117 |
+
xmlcharrefreplace_errors = lookup_error("xmlcharrefreplace")
|
| 1118 |
+
backslashreplace_errors = lookup_error("backslashreplace")
|
| 1119 |
+
namereplace_errors = lookup_error("namereplace")
|
| 1120 |
+
|
| 1121 |
+
# Tell modulefinder that using codecs probably needs the encodings
|
| 1122 |
+
# package
|
| 1123 |
+
_false = 0
|
| 1124 |
+
if _false:
|
| 1125 |
+
import encodings # noqa: F401
|
micromamba_root/envs/hf_sync/Lib/codeop.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""Utilities to compile possibly incomplete Python source code.
|
| 2 |
+
|
| 3 |
+
This module provides two interfaces, broadly similar to the builtin
|
| 4 |
+
function compile(), which take program text, a filename and a 'mode'
|
| 5 |
+
and:
|
| 6 |
+
|
| 7 |
+
- Return code object if the command is complete and valid
|
| 8 |
+
- Return None if the command is incomplete
|
| 9 |
+
- Raise SyntaxError, ValueError or OverflowError if the command is a
|
| 10 |
+
syntax error (OverflowError and ValueError can be produced by
|
| 11 |
+
malformed literals).
|
| 12 |
+
|
| 13 |
+
The two interfaces are:
|
| 14 |
+
|
| 15 |
+
compile_command(source, filename, symbol):
|
| 16 |
+
|
| 17 |
+
Compiles a single command in the manner described above.
|
| 18 |
+
|
| 19 |
+
CommandCompiler():
|
| 20 |
+
|
| 21 |
+
Instances of this class have __call__ methods identical in
|
| 22 |
+
signature to compile_command; the difference is that if the
|
| 23 |
+
instance compiles program text containing a __future__ statement,
|
| 24 |
+
the instance 'remembers' and compiles all subsequent program texts
|
| 25 |
+
with the statement in force.
|
| 26 |
+
|
| 27 |
+
The module also provides another class:
|
| 28 |
+
|
| 29 |
+
Compile():
|
| 30 |
+
|
| 31 |
+
Instances of this class act like the built-in function compile,
|
| 32 |
+
but with 'memory' in the sense described above.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
import __future__
|
| 36 |
+
import warnings
|
| 37 |
+
|
| 38 |
+
_features = [getattr(__future__, fname)
|
| 39 |
+
for fname in __future__.all_feature_names]
|
| 40 |
+
|
| 41 |
+
__all__ = ["compile_command", "Compile", "CommandCompiler"]
|
| 42 |
+
|
| 43 |
+
# The following flags match the values from Include/cpython/compile.h
|
| 44 |
+
# Caveat emptor: These flags are undocumented on purpose and depending
|
| 45 |
+
# on their effect outside the standard library is **unsupported**.
|
| 46 |
+
PyCF_DONT_IMPLY_DEDENT = 0x200
|
| 47 |
+
PyCF_ONLY_AST = 0x400
|
| 48 |
+
PyCF_ALLOW_INCOMPLETE_INPUT = 0x4000
|
| 49 |
+
|
| 50 |
+
def _maybe_compile(compiler, source, filename, symbol, flags):
|
| 51 |
+
# Check for source consisting of only blank lines and comments.
|
| 52 |
+
for line in source.split("\n"):
|
| 53 |
+
line = line.strip()
|
| 54 |
+
if line and line[0] != '#':
|
| 55 |
+
break # Leave it alone.
|
| 56 |
+
else:
|
| 57 |
+
if symbol != "eval":
|
| 58 |
+
source = "pass" # Replace it with a 'pass' statement
|
| 59 |
+
|
| 60 |
+
# Disable compiler warnings when checking for incomplete input.
|
| 61 |
+
with warnings.catch_warnings():
|
| 62 |
+
warnings.simplefilter("ignore", (SyntaxWarning, DeprecationWarning))
|
| 63 |
+
try:
|
| 64 |
+
compiler(source, filename, symbol, flags=flags)
|
| 65 |
+
except SyntaxError: # Let other compile() errors propagate.
|
| 66 |
+
try:
|
| 67 |
+
compiler(source + "\n", filename, symbol, flags=flags)
|
| 68 |
+
return None
|
| 69 |
+
except _IncompleteInputError as e:
|
| 70 |
+
return None
|
| 71 |
+
except SyntaxError as e:
|
| 72 |
+
pass
|
| 73 |
+
# fallthrough
|
| 74 |
+
|
| 75 |
+
return compiler(source, filename, symbol, incomplete_input=False)
|
| 76 |
+
|
| 77 |
+
def _compile(source, filename, symbol, incomplete_input=True, *, flags=0):
|
| 78 |
+
if incomplete_input:
|
| 79 |
+
flags |= PyCF_ALLOW_INCOMPLETE_INPUT
|
| 80 |
+
flags |= PyCF_DONT_IMPLY_DEDENT
|
| 81 |
+
return compile(source, filename, symbol, flags)
|
| 82 |
+
|
| 83 |
+
def compile_command(source, filename="<input>", symbol="single", flags=0):
|
| 84 |
+
r"""Compile a command and determine whether it is incomplete.
|
| 85 |
+
|
| 86 |
+
Arguments:
|
| 87 |
+
|
| 88 |
+
source -- the source string; may contain \n characters
|
| 89 |
+
filename -- optional filename from which source was read; default
|
| 90 |
+
"<input>"
|
| 91 |
+
symbol -- optional grammar start symbol; "single" (default), "exec"
|
| 92 |
+
or "eval"
|
| 93 |
+
|
| 94 |
+
Return value / exceptions raised:
|
| 95 |
+
|
| 96 |
+
- Return a code object if the command is complete and valid
|
| 97 |
+
- Return None if the command is incomplete
|
| 98 |
+
- Raise SyntaxError, ValueError or OverflowError if the command is a
|
| 99 |
+
syntax error (OverflowError and ValueError can be produced by
|
| 100 |
+
malformed literals).
|
| 101 |
+
"""
|
| 102 |
+
return _maybe_compile(_compile, source, filename, symbol, flags)
|
| 103 |
+
|
| 104 |
+
class Compile:
|
| 105 |
+
"""Instances of this class behave much like the built-in compile
|
| 106 |
+
function, but if one is used to compile text containing a future
|
| 107 |
+
statement, it "remembers" and compiles all subsequent program texts
|
| 108 |
+
with the statement in force."""
|
| 109 |
+
def __init__(self):
|
| 110 |
+
self.flags = PyCF_DONT_IMPLY_DEDENT | PyCF_ALLOW_INCOMPLETE_INPUT
|
| 111 |
+
|
| 112 |
+
def __call__(self, source, filename, symbol, flags=0, **kwargs):
|
| 113 |
+
flags |= self.flags
|
| 114 |
+
if kwargs.get('incomplete_input', True) is False:
|
| 115 |
+
flags &= ~PyCF_DONT_IMPLY_DEDENT
|
| 116 |
+
flags &= ~PyCF_ALLOW_INCOMPLETE_INPUT
|
| 117 |
+
codeob = compile(source, filename, symbol, flags, True)
|
| 118 |
+
if flags & PyCF_ONLY_AST:
|
| 119 |
+
return codeob # this is an ast.Module in this case
|
| 120 |
+
for feature in _features:
|
| 121 |
+
if codeob.co_flags & feature.compiler_flag:
|
| 122 |
+
self.flags |= feature.compiler_flag
|
| 123 |
+
return codeob
|
| 124 |
+
|
| 125 |
+
class CommandCompiler:
|
| 126 |
+
"""Instances of this class have __call__ methods identical in
|
| 127 |
+
signature to compile_command; the difference is that if the
|
| 128 |
+
instance compiles program text containing a __future__ statement,
|
| 129 |
+
the instance 'remembers' and compiles all subsequent program texts
|
| 130 |
+
with the statement in force."""
|
| 131 |
+
|
| 132 |
+
def __init__(self,):
|
| 133 |
+
self.compiler = Compile()
|
| 134 |
+
|
| 135 |
+
def __call__(self, source, filename="<input>", symbol="single"):
|
| 136 |
+
r"""Compile a command and determine whether it is incomplete.
|
| 137 |
+
|
| 138 |
+
Arguments:
|
| 139 |
+
|
| 140 |
+
source -- the source string; may contain \n characters
|
| 141 |
+
filename -- optional filename from which source was read;
|
| 142 |
+
default "<input>"
|
| 143 |
+
symbol -- optional grammar start symbol; "single" (default) or
|
| 144 |
+
"eval"
|
| 145 |
+
|
| 146 |
+
Return value / exceptions raised:
|
| 147 |
+
|
| 148 |
+
- Return a code object if the command is complete and valid
|
| 149 |
+
- Return None if the command is incomplete
|
| 150 |
+
- Raise SyntaxError, ValueError or OverflowError if the command is a
|
| 151 |
+
syntax error (OverflowError and ValueError can be produced by
|
| 152 |
+
malformed literals).
|
| 153 |
+
"""
|
| 154 |
+
return _maybe_compile(self.compiler, source, filename, symbol, flags=self.compiler.flags)
|
micromamba_root/envs/hf_sync/Lib/colorsys.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Conversion functions between RGB and other color systems.
|
| 2 |
+
|
| 3 |
+
This modules provides two functions for each color system ABC:
|
| 4 |
+
|
| 5 |
+
rgb_to_abc(r, g, b) --> a, b, c
|
| 6 |
+
abc_to_rgb(a, b, c) --> r, g, b
|
| 7 |
+
|
| 8 |
+
All inputs and outputs are triples of floats in the range [0.0...1.0]
|
| 9 |
+
(with the exception of I and Q, which covers a slightly larger range).
|
| 10 |
+
Inputs outside the valid range may cause exceptions or invalid outputs.
|
| 11 |
+
|
| 12 |
+
Supported color systems:
|
| 13 |
+
RGB: Red, Green, Blue components
|
| 14 |
+
YIQ: Luminance, Chrominance (used by composite video signals)
|
| 15 |
+
HLS: Hue, Luminance, Saturation
|
| 16 |
+
HSV: Hue, Saturation, Value
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
# References:
|
| 20 |
+
# http://en.wikipedia.org/wiki/YIQ
|
| 21 |
+
# http://en.wikipedia.org/wiki/HLS_color_space
|
| 22 |
+
# http://en.wikipedia.org/wiki/HSV_color_space
|
| 23 |
+
|
| 24 |
+
__all__ = ["rgb_to_yiq","yiq_to_rgb","rgb_to_hls","hls_to_rgb",
|
| 25 |
+
"rgb_to_hsv","hsv_to_rgb"]
|
| 26 |
+
|
| 27 |
+
# Some floating-point constants
|
| 28 |
+
|
| 29 |
+
ONE_THIRD = 1.0/3.0
|
| 30 |
+
ONE_SIXTH = 1.0/6.0
|
| 31 |
+
TWO_THIRD = 2.0/3.0
|
| 32 |
+
|
| 33 |
+
# YIQ: used by composite video signals (linear combinations of RGB)
|
| 34 |
+
# Y: perceived grey level (0.0 == black, 1.0 == white)
|
| 35 |
+
# I, Q: color components
|
| 36 |
+
#
|
| 37 |
+
# There are a great many versions of the constants used in these formulae.
|
| 38 |
+
# The ones in this library uses constants from the FCC version of NTSC.
|
| 39 |
+
|
| 40 |
+
def rgb_to_yiq(r, g, b):
|
| 41 |
+
y = 0.30*r + 0.59*g + 0.11*b
|
| 42 |
+
i = 0.74*(r-y) - 0.27*(b-y)
|
| 43 |
+
q = 0.48*(r-y) + 0.41*(b-y)
|
| 44 |
+
return (y, i, q)
|
| 45 |
+
|
| 46 |
+
def yiq_to_rgb(y, i, q):
|
| 47 |
+
# r = y + (0.27*q + 0.41*i) / (0.74*0.41 + 0.27*0.48)
|
| 48 |
+
# b = y + (0.74*q - 0.48*i) / (0.74*0.41 + 0.27*0.48)
|
| 49 |
+
# g = y - (0.30*(r-y) + 0.11*(b-y)) / 0.59
|
| 50 |
+
|
| 51 |
+
r = y + 0.9468822170900693*i + 0.6235565819861433*q
|
| 52 |
+
g = y - 0.27478764629897834*i - 0.6356910791873801*q
|
| 53 |
+
b = y - 1.1085450346420322*i + 1.7090069284064666*q
|
| 54 |
+
|
| 55 |
+
if r < 0.0:
|
| 56 |
+
r = 0.0
|
| 57 |
+
if g < 0.0:
|
| 58 |
+
g = 0.0
|
| 59 |
+
if b < 0.0:
|
| 60 |
+
b = 0.0
|
| 61 |
+
if r > 1.0:
|
| 62 |
+
r = 1.0
|
| 63 |
+
if g > 1.0:
|
| 64 |
+
g = 1.0
|
| 65 |
+
if b > 1.0:
|
| 66 |
+
b = 1.0
|
| 67 |
+
return (r, g, b)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# HLS: Hue, Luminance, Saturation
|
| 71 |
+
# H: position in the spectrum
|
| 72 |
+
# L: color lightness
|
| 73 |
+
# S: color saturation
|
| 74 |
+
|
| 75 |
+
def rgb_to_hls(r, g, b):
|
| 76 |
+
maxc = max(r, g, b)
|
| 77 |
+
minc = min(r, g, b)
|
| 78 |
+
sumc = (maxc+minc)
|
| 79 |
+
rangec = (maxc-minc)
|
| 80 |
+
l = sumc/2.0
|
| 81 |
+
if minc == maxc:
|
| 82 |
+
return 0.0, l, 0.0
|
| 83 |
+
if l <= 0.5:
|
| 84 |
+
s = rangec / sumc
|
| 85 |
+
else:
|
| 86 |
+
s = rangec / (2.0-maxc-minc) # Not always 2.0-sumc: gh-106498.
|
| 87 |
+
rc = (maxc-r) / rangec
|
| 88 |
+
gc = (maxc-g) / rangec
|
| 89 |
+
bc = (maxc-b) / rangec
|
| 90 |
+
if r == maxc:
|
| 91 |
+
h = bc-gc
|
| 92 |
+
elif g == maxc:
|
| 93 |
+
h = 2.0+rc-bc
|
| 94 |
+
else:
|
| 95 |
+
h = 4.0+gc-rc
|
| 96 |
+
h = (h/6.0) % 1.0
|
| 97 |
+
return h, l, s
|
| 98 |
+
|
| 99 |
+
def hls_to_rgb(h, l, s):
|
| 100 |
+
if s == 0.0:
|
| 101 |
+
return l, l, l
|
| 102 |
+
if l <= 0.5:
|
| 103 |
+
m2 = l * (1.0+s)
|
| 104 |
+
else:
|
| 105 |
+
m2 = l+s-(l*s)
|
| 106 |
+
m1 = 2.0*l - m2
|
| 107 |
+
return (_v(m1, m2, h+ONE_THIRD), _v(m1, m2, h), _v(m1, m2, h-ONE_THIRD))
|
| 108 |
+
|
| 109 |
+
def _v(m1, m2, hue):
|
| 110 |
+
hue = hue % 1.0
|
| 111 |
+
if hue < ONE_SIXTH:
|
| 112 |
+
return m1 + (m2-m1)*hue*6.0
|
| 113 |
+
if hue < 0.5:
|
| 114 |
+
return m2
|
| 115 |
+
if hue < TWO_THIRD:
|
| 116 |
+
return m1 + (m2-m1)*(TWO_THIRD-hue)*6.0
|
| 117 |
+
return m1
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# HSV: Hue, Saturation, Value
|
| 121 |
+
# H: position in the spectrum
|
| 122 |
+
# S: color saturation ("purity")
|
| 123 |
+
# V: color brightness
|
| 124 |
+
|
| 125 |
+
def rgb_to_hsv(r, g, b):
|
| 126 |
+
maxc = max(r, g, b)
|
| 127 |
+
minc = min(r, g, b)
|
| 128 |
+
rangec = (maxc-minc)
|
| 129 |
+
v = maxc
|
| 130 |
+
if minc == maxc:
|
| 131 |
+
return 0.0, 0.0, v
|
| 132 |
+
s = rangec / maxc
|
| 133 |
+
rc = (maxc-r) / rangec
|
| 134 |
+
gc = (maxc-g) / rangec
|
| 135 |
+
bc = (maxc-b) / rangec
|
| 136 |
+
if r == maxc:
|
| 137 |
+
h = bc-gc
|
| 138 |
+
elif g == maxc:
|
| 139 |
+
h = 2.0+rc-bc
|
| 140 |
+
else:
|
| 141 |
+
h = 4.0+gc-rc
|
| 142 |
+
h = (h/6.0) % 1.0
|
| 143 |
+
return h, s, v
|
| 144 |
+
|
| 145 |
+
def hsv_to_rgb(h, s, v):
|
| 146 |
+
if s == 0.0:
|
| 147 |
+
return v, v, v
|
| 148 |
+
i = int(h*6.0) # XXX assume int() truncates!
|
| 149 |
+
f = (h*6.0) - i
|
| 150 |
+
p = v*(1.0 - s)
|
| 151 |
+
q = v*(1.0 - s*f)
|
| 152 |
+
t = v*(1.0 - s*(1.0-f))
|
| 153 |
+
i = i%6
|
| 154 |
+
if i == 0:
|
| 155 |
+
return v, t, p
|
| 156 |
+
if i == 1:
|
| 157 |
+
return q, v, p
|
| 158 |
+
if i == 2:
|
| 159 |
+
return p, v, t
|
| 160 |
+
if i == 3:
|
| 161 |
+
return p, q, v
|
| 162 |
+
if i == 4:
|
| 163 |
+
return t, p, v
|
| 164 |
+
if i == 5:
|
| 165 |
+
return v, p, q
|
| 166 |
+
# Cannot get here
|
micromamba_root/envs/hf_sync/Lib/compileall.py
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Module/script to byte-compile all .py files to .pyc files.
|
| 2 |
+
|
| 3 |
+
When called as a script with arguments, this compiles the directories
|
| 4 |
+
given as arguments recursively; the -l option prevents it from
|
| 5 |
+
recursing into directories.
|
| 6 |
+
|
| 7 |
+
Without arguments, it compiles all modules on sys.path, without
|
| 8 |
+
recursing into subdirectories. (Even though it should do so for
|
| 9 |
+
packages -- for now, you'll have to deal with packages separately.)
|
| 10 |
+
|
| 11 |
+
See module py_compile for details of the actual byte-compilation.
|
| 12 |
+
"""
|
| 13 |
+
import os
|
| 14 |
+
import sys
|
| 15 |
+
import importlib.util
|
| 16 |
+
import py_compile
|
| 17 |
+
import struct
|
| 18 |
+
import filecmp
|
| 19 |
+
|
| 20 |
+
from functools import partial
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
__all__ = ["compile_dir","compile_file","compile_path"]
|
| 24 |
+
|
| 25 |
+
def _walk_dir(dir, maxlevels, quiet=0):
|
| 26 |
+
if quiet < 2 and isinstance(dir, os.PathLike):
|
| 27 |
+
dir = os.fspath(dir)
|
| 28 |
+
if not quiet:
|
| 29 |
+
print('Listing {!r}...'.format(dir))
|
| 30 |
+
try:
|
| 31 |
+
names = os.listdir(dir)
|
| 32 |
+
except OSError:
|
| 33 |
+
if quiet < 2:
|
| 34 |
+
print("Can't list {!r}".format(dir))
|
| 35 |
+
names = []
|
| 36 |
+
names.sort()
|
| 37 |
+
for name in names:
|
| 38 |
+
if name == '__pycache__':
|
| 39 |
+
continue
|
| 40 |
+
fullname = os.path.join(dir, name)
|
| 41 |
+
if not os.path.isdir(fullname):
|
| 42 |
+
yield fullname
|
| 43 |
+
elif (maxlevels > 0 and name != os.curdir and name != os.pardir and
|
| 44 |
+
os.path.isdir(fullname) and not os.path.islink(fullname)):
|
| 45 |
+
yield from _walk_dir(fullname, maxlevels=maxlevels - 1,
|
| 46 |
+
quiet=quiet)
|
| 47 |
+
|
| 48 |
+
def compile_dir(dir, maxlevels=None, ddir=None, force=False,
|
| 49 |
+
rx=None, quiet=0, legacy=False, optimize=-1, workers=1,
|
| 50 |
+
invalidation_mode=None, *, stripdir=None,
|
| 51 |
+
prependdir=None, limit_sl_dest=None, hardlink_dupes=False):
|
| 52 |
+
"""Byte-compile all modules in the given directory tree.
|
| 53 |
+
|
| 54 |
+
Arguments (only dir is required):
|
| 55 |
+
|
| 56 |
+
dir: the directory to byte-compile
|
| 57 |
+
maxlevels: maximum recursion level (default `sys.getrecursionlimit()`)
|
| 58 |
+
ddir: the directory that will be prepended to the path to the
|
| 59 |
+
file as it is compiled into each byte-code file.
|
| 60 |
+
force: if True, force compilation, even if timestamps are up-to-date
|
| 61 |
+
quiet: full output with False or 0, errors only with 1,
|
| 62 |
+
no output with 2
|
| 63 |
+
legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
|
| 64 |
+
optimize: int or list of optimization levels or -1 for level of
|
| 65 |
+
the interpreter. Multiple levels leads to multiple compiled
|
| 66 |
+
files each with one optimization level.
|
| 67 |
+
workers: maximum number of parallel workers
|
| 68 |
+
invalidation_mode: how the up-to-dateness of the pyc will be checked
|
| 69 |
+
stripdir: part of path to left-strip from source file path
|
| 70 |
+
prependdir: path to prepend to beginning of original file path, applied
|
| 71 |
+
after stripdir
|
| 72 |
+
limit_sl_dest: ignore symlinks if they are pointing outside of
|
| 73 |
+
the defined path
|
| 74 |
+
hardlink_dupes: hardlink duplicated pyc files
|
| 75 |
+
"""
|
| 76 |
+
ProcessPoolExecutor = None
|
| 77 |
+
if ddir is not None and (stripdir is not None or prependdir is not None):
|
| 78 |
+
raise ValueError(("Destination dir (ddir) cannot be used "
|
| 79 |
+
"in combination with stripdir or prependdir"))
|
| 80 |
+
if ddir is not None:
|
| 81 |
+
stripdir = dir
|
| 82 |
+
prependdir = ddir
|
| 83 |
+
ddir = None
|
| 84 |
+
if workers < 0:
|
| 85 |
+
raise ValueError('workers must be greater or equal to 0')
|
| 86 |
+
if workers != 1:
|
| 87 |
+
# Check if this is a system where ProcessPoolExecutor can function.
|
| 88 |
+
from concurrent.futures.process import _check_system_limits
|
| 89 |
+
try:
|
| 90 |
+
_check_system_limits()
|
| 91 |
+
except NotImplementedError:
|
| 92 |
+
workers = 1
|
| 93 |
+
else:
|
| 94 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 95 |
+
if maxlevels is None:
|
| 96 |
+
maxlevels = sys.getrecursionlimit()
|
| 97 |
+
files = _walk_dir(dir, quiet=quiet, maxlevels=maxlevels)
|
| 98 |
+
success = True
|
| 99 |
+
if workers != 1 and ProcessPoolExecutor is not None:
|
| 100 |
+
import multiprocessing
|
| 101 |
+
if multiprocessing.get_start_method() == 'fork':
|
| 102 |
+
mp_context = multiprocessing.get_context('forkserver')
|
| 103 |
+
else:
|
| 104 |
+
mp_context = None
|
| 105 |
+
# If workers == 0, let ProcessPoolExecutor choose
|
| 106 |
+
workers = workers or None
|
| 107 |
+
with ProcessPoolExecutor(max_workers=workers,
|
| 108 |
+
mp_context=mp_context) as executor:
|
| 109 |
+
results = executor.map(partial(compile_file,
|
| 110 |
+
ddir=ddir, force=force,
|
| 111 |
+
rx=rx, quiet=quiet,
|
| 112 |
+
legacy=legacy,
|
| 113 |
+
optimize=optimize,
|
| 114 |
+
invalidation_mode=invalidation_mode,
|
| 115 |
+
stripdir=stripdir,
|
| 116 |
+
prependdir=prependdir,
|
| 117 |
+
limit_sl_dest=limit_sl_dest,
|
| 118 |
+
hardlink_dupes=hardlink_dupes),
|
| 119 |
+
files,
|
| 120 |
+
chunksize=4)
|
| 121 |
+
success = min(results, default=True)
|
| 122 |
+
else:
|
| 123 |
+
for file in files:
|
| 124 |
+
if not compile_file(file, ddir, force, rx, quiet,
|
| 125 |
+
legacy, optimize, invalidation_mode,
|
| 126 |
+
stripdir=stripdir, prependdir=prependdir,
|
| 127 |
+
limit_sl_dest=limit_sl_dest,
|
| 128 |
+
hardlink_dupes=hardlink_dupes):
|
| 129 |
+
success = False
|
| 130 |
+
return success
|
| 131 |
+
|
| 132 |
+
def compile_file(fullname, ddir=None, force=False, rx=None, quiet=0,
|
| 133 |
+
legacy=False, optimize=-1,
|
| 134 |
+
invalidation_mode=None, *, stripdir=None, prependdir=None,
|
| 135 |
+
limit_sl_dest=None, hardlink_dupes=False):
|
| 136 |
+
"""Byte-compile one file.
|
| 137 |
+
|
| 138 |
+
Arguments (only fullname is required):
|
| 139 |
+
|
| 140 |
+
fullname: the file to byte-compile
|
| 141 |
+
ddir: if given, the directory name compiled in to the
|
| 142 |
+
byte-code file.
|
| 143 |
+
force: if True, force compilation, even if timestamps are up-to-date
|
| 144 |
+
quiet: full output with False or 0, errors only with 1,
|
| 145 |
+
no output with 2
|
| 146 |
+
legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
|
| 147 |
+
optimize: int or list of optimization levels or -1 for level of
|
| 148 |
+
the interpreter. Multiple levels leads to multiple compiled
|
| 149 |
+
files each with one optimization level.
|
| 150 |
+
invalidation_mode: how the up-to-dateness of the pyc will be checked
|
| 151 |
+
stripdir: part of path to left-strip from source file path
|
| 152 |
+
prependdir: path to prepend to beginning of original file path, applied
|
| 153 |
+
after stripdir
|
| 154 |
+
limit_sl_dest: ignore symlinks if they are pointing outside of
|
| 155 |
+
the defined path.
|
| 156 |
+
hardlink_dupes: hardlink duplicated pyc files
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
if ddir is not None and (stripdir is not None or prependdir is not None):
|
| 160 |
+
raise ValueError(("Destination dir (ddir) cannot be used "
|
| 161 |
+
"in combination with stripdir or prependdir"))
|
| 162 |
+
|
| 163 |
+
success = True
|
| 164 |
+
fullname = os.fspath(fullname)
|
| 165 |
+
stripdir = os.fspath(stripdir) if stripdir is not None else None
|
| 166 |
+
name = os.path.basename(fullname)
|
| 167 |
+
|
| 168 |
+
dfile = None
|
| 169 |
+
|
| 170 |
+
if ddir is not None:
|
| 171 |
+
dfile = os.path.join(ddir, name)
|
| 172 |
+
|
| 173 |
+
if stripdir is not None:
|
| 174 |
+
fullname_parts = fullname.split(os.path.sep)
|
| 175 |
+
stripdir_parts = stripdir.split(os.path.sep)
|
| 176 |
+
|
| 177 |
+
if stripdir_parts != fullname_parts[:len(stripdir_parts)]:
|
| 178 |
+
if quiet < 2:
|
| 179 |
+
print("The stripdir path {!r} is not a valid prefix for "
|
| 180 |
+
"source path {!r}; ignoring".format(stripdir, fullname))
|
| 181 |
+
else:
|
| 182 |
+
dfile = os.path.join(*fullname_parts[len(stripdir_parts):])
|
| 183 |
+
|
| 184 |
+
if prependdir is not None:
|
| 185 |
+
if dfile is None:
|
| 186 |
+
dfile = os.path.join(prependdir, fullname)
|
| 187 |
+
else:
|
| 188 |
+
dfile = os.path.join(prependdir, dfile)
|
| 189 |
+
|
| 190 |
+
if isinstance(optimize, int):
|
| 191 |
+
optimize = [optimize]
|
| 192 |
+
|
| 193 |
+
# Use set() to remove duplicates.
|
| 194 |
+
# Use sorted() to create pyc files in a deterministic order.
|
| 195 |
+
optimize = sorted(set(optimize))
|
| 196 |
+
|
| 197 |
+
if hardlink_dupes and len(optimize) < 2:
|
| 198 |
+
raise ValueError("Hardlinking of duplicated bytecode makes sense "
|
| 199 |
+
"only for more than one optimization level")
|
| 200 |
+
|
| 201 |
+
if rx is not None:
|
| 202 |
+
mo = rx.search(fullname)
|
| 203 |
+
if mo:
|
| 204 |
+
return success
|
| 205 |
+
|
| 206 |
+
if limit_sl_dest is not None and os.path.islink(fullname):
|
| 207 |
+
if Path(limit_sl_dest).resolve() not in Path(fullname).resolve().parents:
|
| 208 |
+
return success
|
| 209 |
+
|
| 210 |
+
opt_cfiles = {}
|
| 211 |
+
|
| 212 |
+
if os.path.isfile(fullname):
|
| 213 |
+
for opt_level in optimize:
|
| 214 |
+
if legacy:
|
| 215 |
+
opt_cfiles[opt_level] = fullname + 'c'
|
| 216 |
+
else:
|
| 217 |
+
if opt_level >= 0:
|
| 218 |
+
opt = opt_level if opt_level >= 1 else ''
|
| 219 |
+
cfile = (importlib.util.cache_from_source(
|
| 220 |
+
fullname, optimization=opt))
|
| 221 |
+
opt_cfiles[opt_level] = cfile
|
| 222 |
+
else:
|
| 223 |
+
cfile = importlib.util.cache_from_source(fullname)
|
| 224 |
+
opt_cfiles[opt_level] = cfile
|
| 225 |
+
|
| 226 |
+
head, tail = name[:-3], name[-3:]
|
| 227 |
+
if tail == '.py':
|
| 228 |
+
if not force:
|
| 229 |
+
try:
|
| 230 |
+
mtime = int(os.stat(fullname).st_mtime)
|
| 231 |
+
expect = struct.pack('<4sLL', importlib.util.MAGIC_NUMBER,
|
| 232 |
+
0, mtime & 0xFFFF_FFFF)
|
| 233 |
+
for cfile in opt_cfiles.values():
|
| 234 |
+
with open(cfile, 'rb') as chandle:
|
| 235 |
+
actual = chandle.read(12)
|
| 236 |
+
if expect != actual:
|
| 237 |
+
break
|
| 238 |
+
else:
|
| 239 |
+
return success
|
| 240 |
+
except OSError:
|
| 241 |
+
pass
|
| 242 |
+
if not quiet:
|
| 243 |
+
print('Compiling {!r}...'.format(fullname))
|
| 244 |
+
try:
|
| 245 |
+
for index, opt_level in enumerate(optimize):
|
| 246 |
+
cfile = opt_cfiles[opt_level]
|
| 247 |
+
ok = py_compile.compile(fullname, cfile, dfile, True,
|
| 248 |
+
optimize=opt_level,
|
| 249 |
+
invalidation_mode=invalidation_mode)
|
| 250 |
+
if index > 0 and hardlink_dupes:
|
| 251 |
+
previous_cfile = opt_cfiles[optimize[index - 1]]
|
| 252 |
+
if filecmp.cmp(cfile, previous_cfile, shallow=False):
|
| 253 |
+
os.unlink(cfile)
|
| 254 |
+
os.link(previous_cfile, cfile)
|
| 255 |
+
except py_compile.PyCompileError as err:
|
| 256 |
+
success = False
|
| 257 |
+
if quiet >= 2:
|
| 258 |
+
return success
|
| 259 |
+
elif quiet:
|
| 260 |
+
print('*** Error compiling {!r}...'.format(fullname))
|
| 261 |
+
else:
|
| 262 |
+
print('*** ', end='')
|
| 263 |
+
# escape non-printable characters in msg
|
| 264 |
+
encoding = sys.stdout.encoding or sys.getdefaultencoding()
|
| 265 |
+
msg = err.msg.encode(encoding, errors='backslashreplace').decode(encoding)
|
| 266 |
+
print(msg)
|
| 267 |
+
except (SyntaxError, UnicodeError, OSError) as e:
|
| 268 |
+
success = False
|
| 269 |
+
if quiet >= 2:
|
| 270 |
+
return success
|
| 271 |
+
elif quiet:
|
| 272 |
+
print('*** Error compiling {!r}...'.format(fullname))
|
| 273 |
+
else:
|
| 274 |
+
print('*** ', end='')
|
| 275 |
+
print(e.__class__.__name__ + ':', e)
|
| 276 |
+
else:
|
| 277 |
+
if ok == 0:
|
| 278 |
+
success = False
|
| 279 |
+
return success
|
| 280 |
+
|
| 281 |
+
def compile_path(skip_curdir=1, maxlevels=0, force=False, quiet=0,
|
| 282 |
+
legacy=False, optimize=-1,
|
| 283 |
+
invalidation_mode=None):
|
| 284 |
+
"""Byte-compile all module on sys.path.
|
| 285 |
+
|
| 286 |
+
Arguments (all optional):
|
| 287 |
+
|
| 288 |
+
skip_curdir: if true, skip current directory (default True)
|
| 289 |
+
maxlevels: max recursion level (default 0)
|
| 290 |
+
force: as for compile_dir() (default False)
|
| 291 |
+
quiet: as for compile_dir() (default 0)
|
| 292 |
+
legacy: as for compile_dir() (default False)
|
| 293 |
+
optimize: as for compile_dir() (default -1)
|
| 294 |
+
invalidation_mode: as for compiler_dir()
|
| 295 |
+
"""
|
| 296 |
+
success = True
|
| 297 |
+
for dir in sys.path:
|
| 298 |
+
if (not dir or dir == os.curdir) and skip_curdir:
|
| 299 |
+
if quiet < 2:
|
| 300 |
+
print('Skipping current directory')
|
| 301 |
+
else:
|
| 302 |
+
success = success and compile_dir(
|
| 303 |
+
dir,
|
| 304 |
+
maxlevels,
|
| 305 |
+
None,
|
| 306 |
+
force,
|
| 307 |
+
quiet=quiet,
|
| 308 |
+
legacy=legacy,
|
| 309 |
+
optimize=optimize,
|
| 310 |
+
invalidation_mode=invalidation_mode,
|
| 311 |
+
)
|
| 312 |
+
return success
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def main():
|
| 316 |
+
"""Script main program."""
|
| 317 |
+
import argparse
|
| 318 |
+
|
| 319 |
+
parser = argparse.ArgumentParser(
|
| 320 |
+
description='Utilities to support installing Python libraries.',
|
| 321 |
+
color=True,
|
| 322 |
+
)
|
| 323 |
+
parser.add_argument('-l', action='store_const', const=0,
|
| 324 |
+
default=None, dest='maxlevels',
|
| 325 |
+
help="don't recurse into subdirectories")
|
| 326 |
+
parser.add_argument('-r', type=int, dest='recursion',
|
| 327 |
+
help=('control the maximum recursion level. '
|
| 328 |
+
'if `-l` and `-r` options are specified, '
|
| 329 |
+
'then `-r` takes precedence.'))
|
| 330 |
+
parser.add_argument('-f', action='store_true', dest='force',
|
| 331 |
+
help='force rebuild even if timestamps are up to date')
|
| 332 |
+
parser.add_argument('-q', action='count', dest='quiet', default=0,
|
| 333 |
+
help='output only error messages; -qq will suppress '
|
| 334 |
+
'the error messages as well.')
|
| 335 |
+
parser.add_argument('-b', action='store_true', dest='legacy',
|
| 336 |
+
help='use legacy (pre-PEP3147) compiled file locations')
|
| 337 |
+
parser.add_argument('-d', metavar='DESTDIR', dest='ddir', default=None,
|
| 338 |
+
help=('directory to prepend to file paths for use in '
|
| 339 |
+
'compile-time tracebacks and in runtime '
|
| 340 |
+
'tracebacks in cases where the source file is '
|
| 341 |
+
'unavailable'))
|
| 342 |
+
parser.add_argument('-s', metavar='STRIPDIR', dest='stripdir',
|
| 343 |
+
default=None,
|
| 344 |
+
help=('part of path to left-strip from path '
|
| 345 |
+
'to source file - for example buildroot. '
|
| 346 |
+
'`-d` and `-s` options cannot be '
|
| 347 |
+
'specified together.'))
|
| 348 |
+
parser.add_argument('-p', metavar='PREPENDDIR', dest='prependdir',
|
| 349 |
+
default=None,
|
| 350 |
+
help=('path to add as prefix to path '
|
| 351 |
+
'to source file - for example / to make '
|
| 352 |
+
'it absolute when some part is removed '
|
| 353 |
+
'by `-s` option. '
|
| 354 |
+
'`-d` and `-p` options cannot be '
|
| 355 |
+
'specified together.'))
|
| 356 |
+
parser.add_argument('-x', metavar='REGEXP', dest='rx', default=None,
|
| 357 |
+
help=('skip files matching the regular expression; '
|
| 358 |
+
'the regexp is searched for in the full path '
|
| 359 |
+
'of each file considered for compilation'))
|
| 360 |
+
parser.add_argument('-i', metavar='FILE', dest='flist',
|
| 361 |
+
help=('add all the files and directories listed in '
|
| 362 |
+
'FILE to the list considered for compilation; '
|
| 363 |
+
'if "-", names are read from stdin'))
|
| 364 |
+
parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='*',
|
| 365 |
+
help=('zero or more file and directory names '
|
| 366 |
+
'to compile; if no arguments given, defaults '
|
| 367 |
+
'to the equivalent of -l sys.path'))
|
| 368 |
+
parser.add_argument('-j', '--workers', default=1,
|
| 369 |
+
type=int, help='Run compileall concurrently')
|
| 370 |
+
invalidation_modes = [mode.name.lower().replace('_', '-')
|
| 371 |
+
for mode in py_compile.PycInvalidationMode]
|
| 372 |
+
parser.add_argument('--invalidation-mode',
|
| 373 |
+
choices=sorted(invalidation_modes),
|
| 374 |
+
help=('set .pyc invalidation mode; defaults to '
|
| 375 |
+
'"checked-hash" if the SOURCE_DATE_EPOCH '
|
| 376 |
+
'environment variable is set, and '
|
| 377 |
+
'"timestamp" otherwise.'))
|
| 378 |
+
parser.add_argument('-o', action='append', type=int, dest='opt_levels',
|
| 379 |
+
help=('Optimization levels to run compilation with. '
|
| 380 |
+
'Default is -1 which uses the optimization level '
|
| 381 |
+
'of the Python interpreter itself (see -O).'))
|
| 382 |
+
parser.add_argument('-e', metavar='DIR', dest='limit_sl_dest',
|
| 383 |
+
help='Ignore symlinks pointing outsite of the DIR')
|
| 384 |
+
parser.add_argument('--hardlink-dupes', action='store_true',
|
| 385 |
+
dest='hardlink_dupes',
|
| 386 |
+
help='Hardlink duplicated pyc files')
|
| 387 |
+
|
| 388 |
+
args = parser.parse_args()
|
| 389 |
+
compile_dests = args.compile_dest
|
| 390 |
+
|
| 391 |
+
if args.rx:
|
| 392 |
+
import re
|
| 393 |
+
args.rx = re.compile(args.rx)
|
| 394 |
+
|
| 395 |
+
if args.limit_sl_dest == "":
|
| 396 |
+
args.limit_sl_dest = None
|
| 397 |
+
|
| 398 |
+
if args.recursion is not None:
|
| 399 |
+
maxlevels = args.recursion
|
| 400 |
+
else:
|
| 401 |
+
maxlevels = args.maxlevels
|
| 402 |
+
|
| 403 |
+
if args.opt_levels is None:
|
| 404 |
+
args.opt_levels = [-1]
|
| 405 |
+
|
| 406 |
+
if len(args.opt_levels) == 1 and args.hardlink_dupes:
|
| 407 |
+
parser.error(("Hardlinking of duplicated bytecode makes sense "
|
| 408 |
+
"only for more than one optimization level."))
|
| 409 |
+
|
| 410 |
+
if args.ddir is not None and (
|
| 411 |
+
args.stripdir is not None or args.prependdir is not None
|
| 412 |
+
):
|
| 413 |
+
parser.error("-d cannot be used in combination with -s or -p")
|
| 414 |
+
|
| 415 |
+
# if flist is provided then load it
|
| 416 |
+
if args.flist:
|
| 417 |
+
try:
|
| 418 |
+
with (sys.stdin if args.flist=='-' else
|
| 419 |
+
open(args.flist, encoding="utf-8")) as f:
|
| 420 |
+
for line in f:
|
| 421 |
+
compile_dests.append(line.strip())
|
| 422 |
+
except OSError:
|
| 423 |
+
if args.quiet < 2:
|
| 424 |
+
print("Error reading file list {}".format(args.flist))
|
| 425 |
+
return False
|
| 426 |
+
|
| 427 |
+
if args.invalidation_mode:
|
| 428 |
+
ivl_mode = args.invalidation_mode.replace('-', '_').upper()
|
| 429 |
+
invalidation_mode = py_compile.PycInvalidationMode[ivl_mode]
|
| 430 |
+
else:
|
| 431 |
+
invalidation_mode = None
|
| 432 |
+
|
| 433 |
+
success = True
|
| 434 |
+
try:
|
| 435 |
+
if compile_dests:
|
| 436 |
+
for dest in compile_dests:
|
| 437 |
+
if os.path.isfile(dest):
|
| 438 |
+
if not compile_file(dest, args.ddir, args.force, args.rx,
|
| 439 |
+
args.quiet, args.legacy,
|
| 440 |
+
invalidation_mode=invalidation_mode,
|
| 441 |
+
stripdir=args.stripdir,
|
| 442 |
+
prependdir=args.prependdir,
|
| 443 |
+
optimize=args.opt_levels,
|
| 444 |
+
limit_sl_dest=args.limit_sl_dest,
|
| 445 |
+
hardlink_dupes=args.hardlink_dupes):
|
| 446 |
+
success = False
|
| 447 |
+
else:
|
| 448 |
+
if not compile_dir(dest, maxlevels, args.ddir,
|
| 449 |
+
args.force, args.rx, args.quiet,
|
| 450 |
+
args.legacy, workers=args.workers,
|
| 451 |
+
invalidation_mode=invalidation_mode,
|
| 452 |
+
stripdir=args.stripdir,
|
| 453 |
+
prependdir=args.prependdir,
|
| 454 |
+
optimize=args.opt_levels,
|
| 455 |
+
limit_sl_dest=args.limit_sl_dest,
|
| 456 |
+
hardlink_dupes=args.hardlink_dupes):
|
| 457 |
+
success = False
|
| 458 |
+
return success
|
| 459 |
+
else:
|
| 460 |
+
return compile_path(legacy=args.legacy, force=args.force,
|
| 461 |
+
quiet=args.quiet,
|
| 462 |
+
invalidation_mode=invalidation_mode)
|
| 463 |
+
except KeyboardInterrupt:
|
| 464 |
+
if args.quiet < 2:
|
| 465 |
+
print("\n[interrupted]")
|
| 466 |
+
return False
|
| 467 |
+
return True
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
if __name__ == '__main__':
|
| 471 |
+
exit_status = int(not main())
|
| 472 |
+
sys.exit(exit_status)
|
micromamba_root/envs/hf_sync/Lib/configparser.py
ADDED
|
@@ -0,0 +1,1415 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configuration file parser.
|
| 2 |
+
|
| 3 |
+
A configuration file consists of sections, lead by a "[section]" header,
|
| 4 |
+
and followed by "name: value" entries, with continuations and such in
|
| 5 |
+
the style of RFC 822.
|
| 6 |
+
|
| 7 |
+
Intrinsic defaults can be specified by passing them into the
|
| 8 |
+
ConfigParser constructor as a dictionary.
|
| 9 |
+
|
| 10 |
+
class:
|
| 11 |
+
|
| 12 |
+
ConfigParser -- responsible for parsing a list of
|
| 13 |
+
configuration files, and managing the parsed database.
|
| 14 |
+
|
| 15 |
+
methods:
|
| 16 |
+
|
| 17 |
+
__init__(defaults=None, dict_type=_default_dict, allow_no_value=False,
|
| 18 |
+
delimiters=('=', ':'), comment_prefixes=('#', ';'),
|
| 19 |
+
inline_comment_prefixes=None, strict=True,
|
| 20 |
+
empty_lines_in_values=True, default_section='DEFAULT',
|
| 21 |
+
interpolation=<unset>, converters=<unset>,
|
| 22 |
+
allow_unnamed_section=False):
|
| 23 |
+
Create the parser. When `defaults` is given, it is initialized into the
|
| 24 |
+
dictionary or intrinsic defaults. The keys must be strings, the values
|
| 25 |
+
must be appropriate for %()s string interpolation.
|
| 26 |
+
|
| 27 |
+
When `dict_type` is given, it will be used to create the dictionary
|
| 28 |
+
objects for the list of sections, for the options within a section, and
|
| 29 |
+
for the default values.
|
| 30 |
+
|
| 31 |
+
When `delimiters` is given, it will be used as the set of substrings
|
| 32 |
+
that divide keys from values.
|
| 33 |
+
|
| 34 |
+
When `comment_prefixes` is given, it will be used as the set of
|
| 35 |
+
substrings that prefix comments in empty lines. Comments can be
|
| 36 |
+
indented.
|
| 37 |
+
|
| 38 |
+
When `inline_comment_prefixes` is given, it will be used as the set of
|
| 39 |
+
substrings that prefix comments in non-empty lines.
|
| 40 |
+
|
| 41 |
+
When `strict` is True, the parser won't allow for any section or option
|
| 42 |
+
duplicates while reading from a single source (file, string or
|
| 43 |
+
dictionary). Default is True.
|
| 44 |
+
|
| 45 |
+
When `empty_lines_in_values` is False (default: True), each empty line
|
| 46 |
+
marks the end of an option. Otherwise, internal empty lines of
|
| 47 |
+
a multiline option are kept as part of the value.
|
| 48 |
+
|
| 49 |
+
When `allow_no_value` is True (default: False), options without
|
| 50 |
+
values are accepted; the value presented for these is None.
|
| 51 |
+
|
| 52 |
+
When `default_section` is given, the name of the special section is
|
| 53 |
+
named accordingly. By default it is called ``"DEFAULT"`` but this can
|
| 54 |
+
be customized to point to any other valid section name. Its current
|
| 55 |
+
value can be retrieved using the ``parser_instance.default_section``
|
| 56 |
+
attribute and may be modified at runtime.
|
| 57 |
+
|
| 58 |
+
When `interpolation` is given, it should be an Interpolation subclass
|
| 59 |
+
instance. It will be used as the handler for option value
|
| 60 |
+
pre-processing when using getters. RawConfigParser objects don't do
|
| 61 |
+
any sort of interpolation, whereas ConfigParser uses an instance of
|
| 62 |
+
BasicInterpolation. The library also provides a ``zc.buildout``
|
| 63 |
+
inspired ExtendedInterpolation implementation.
|
| 64 |
+
|
| 65 |
+
When `converters` is given, it should be a dictionary where each key
|
| 66 |
+
represents the name of a type converter and each value is a callable
|
| 67 |
+
implementing the conversion from string to the desired datatype. Every
|
| 68 |
+
converter gets its corresponding get*() method on the parser object and
|
| 69 |
+
section proxies.
|
| 70 |
+
|
| 71 |
+
When `allow_unnamed_section` is True (default: False), options
|
| 72 |
+
without section are accepted: the section for these is
|
| 73 |
+
``configparser.UNNAMED_SECTION``.
|
| 74 |
+
|
| 75 |
+
sections()
|
| 76 |
+
Return all the configuration section names, sans DEFAULT.
|
| 77 |
+
|
| 78 |
+
has_section(section)
|
| 79 |
+
Return whether the given section exists.
|
| 80 |
+
|
| 81 |
+
has_option(section, option)
|
| 82 |
+
Return whether the given option exists in the given section.
|
| 83 |
+
|
| 84 |
+
options(section)
|
| 85 |
+
Return list of configuration options for the named section.
|
| 86 |
+
|
| 87 |
+
read(filenames, encoding=None)
|
| 88 |
+
Read and parse the iterable of named configuration files, given by
|
| 89 |
+
name. A single filename is also allowed. Non-existing files
|
| 90 |
+
are ignored. Return list of successfully read files.
|
| 91 |
+
|
| 92 |
+
read_file(f, filename=None)
|
| 93 |
+
Read and parse one configuration file, given as a file object.
|
| 94 |
+
The filename defaults to f.name; it is only used in error
|
| 95 |
+
messages (if f has no `name` attribute, the string `<???>` is used).
|
| 96 |
+
|
| 97 |
+
read_string(string)
|
| 98 |
+
Read configuration from a given string.
|
| 99 |
+
|
| 100 |
+
read_dict(dictionary)
|
| 101 |
+
Read configuration from a dictionary. Keys are section names,
|
| 102 |
+
values are dictionaries with keys and values that should be present
|
| 103 |
+
in the section. If the used dictionary type preserves order, sections
|
| 104 |
+
and their keys will be added in order. Values are automatically
|
| 105 |
+
converted to strings.
|
| 106 |
+
|
| 107 |
+
get(section, option, raw=False, vars=None, fallback=_UNSET)
|
| 108 |
+
Return a string value for the named option. All % interpolations are
|
| 109 |
+
expanded in the return values, based on the defaults passed into the
|
| 110 |
+
constructor and the DEFAULT section. Additional substitutions may be
|
| 111 |
+
provided using the `vars` argument, which must be a dictionary whose
|
| 112 |
+
contents override any pre-existing defaults. If `option` is a key in
|
| 113 |
+
`vars`, the value from `vars` is used.
|
| 114 |
+
|
| 115 |
+
getint(section, options, raw=False, vars=None, fallback=_UNSET)
|
| 116 |
+
Like get(), but convert value to an integer.
|
| 117 |
+
|
| 118 |
+
getfloat(section, options, raw=False, vars=None, fallback=_UNSET)
|
| 119 |
+
Like get(), but convert value to a float.
|
| 120 |
+
|
| 121 |
+
getboolean(section, options, raw=False, vars=None, fallback=_UNSET)
|
| 122 |
+
Like get(), but convert value to a boolean (currently case
|
| 123 |
+
insensitively defined as 0, false, no, off for False, and 1, true,
|
| 124 |
+
yes, on for True). Returns False or True.
|
| 125 |
+
|
| 126 |
+
items(section=_UNSET, raw=False, vars=None)
|
| 127 |
+
If section is given, return a list of tuples with (name, value) for
|
| 128 |
+
each option in the section. Otherwise, return a list of tuples with
|
| 129 |
+
(section_name, section_proxy) for each section, including DEFAULTSECT.
|
| 130 |
+
|
| 131 |
+
remove_section(section)
|
| 132 |
+
Remove the given file section and all its options.
|
| 133 |
+
|
| 134 |
+
remove_option(section, option)
|
| 135 |
+
Remove the given option from the given section.
|
| 136 |
+
|
| 137 |
+
set(section, option, value)
|
| 138 |
+
Set the given option.
|
| 139 |
+
|
| 140 |
+
write(fp, space_around_delimiters=True)
|
| 141 |
+
Write the configuration state in .ini format. If
|
| 142 |
+
`space_around_delimiters` is True (the default), delimiters
|
| 143 |
+
between keys and values are surrounded by spaces.
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
# Do not import dataclasses; overhead is unacceptable (gh-117703)
|
| 147 |
+
|
| 148 |
+
from collections.abc import Iterable, MutableMapping
|
| 149 |
+
from collections import ChainMap as _ChainMap
|
| 150 |
+
import contextlib
|
| 151 |
+
import functools
|
| 152 |
+
import io
|
| 153 |
+
import itertools
|
| 154 |
+
import os
|
| 155 |
+
import re
|
| 156 |
+
import sys
|
| 157 |
+
|
| 158 |
+
__all__ = ("NoSectionError", "DuplicateOptionError", "DuplicateSectionError",
|
| 159 |
+
"NoOptionError", "InterpolationError", "InterpolationDepthError",
|
| 160 |
+
"InterpolationMissingOptionError", "InterpolationSyntaxError",
|
| 161 |
+
"ParsingError", "MissingSectionHeaderError",
|
| 162 |
+
"MultilineContinuationError", "UnnamedSectionDisabledError",
|
| 163 |
+
"InvalidWriteError", "ConfigParser", "RawConfigParser",
|
| 164 |
+
"Interpolation", "BasicInterpolation", "ExtendedInterpolation",
|
| 165 |
+
"SectionProxy", "ConverterMapping",
|
| 166 |
+
"DEFAULTSECT", "MAX_INTERPOLATION_DEPTH", "UNNAMED_SECTION")
|
| 167 |
+
|
| 168 |
+
_default_dict = dict
|
| 169 |
+
DEFAULTSECT = "DEFAULT"
|
| 170 |
+
|
| 171 |
+
MAX_INTERPOLATION_DEPTH = 10
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# exception classes
|
| 176 |
+
class Error(Exception):
|
| 177 |
+
"""Base class for ConfigParser exceptions."""
|
| 178 |
+
|
| 179 |
+
def __init__(self, msg=''):
|
| 180 |
+
self.message = msg
|
| 181 |
+
Exception.__init__(self, msg)
|
| 182 |
+
|
| 183 |
+
def __repr__(self):
|
| 184 |
+
return self.message
|
| 185 |
+
|
| 186 |
+
__str__ = __repr__
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class NoSectionError(Error):
|
| 190 |
+
"""Raised when no section matches a requested option."""
|
| 191 |
+
|
| 192 |
+
def __init__(self, section):
|
| 193 |
+
Error.__init__(self, 'No section: %r' % (section,))
|
| 194 |
+
self.section = section
|
| 195 |
+
self.args = (section, )
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class DuplicateSectionError(Error):
|
| 199 |
+
"""Raised when a section is repeated in an input source.
|
| 200 |
+
|
| 201 |
+
Possible repetitions that raise this exception are: multiple creation
|
| 202 |
+
using the API or in strict parsers when a section is found more than once
|
| 203 |
+
in a single input file, string or dictionary.
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
def __init__(self, section, source=None, lineno=None):
|
| 207 |
+
msg = [repr(section), " already exists"]
|
| 208 |
+
if source is not None:
|
| 209 |
+
message = ["While reading from ", repr(source)]
|
| 210 |
+
if lineno is not None:
|
| 211 |
+
message.append(" [line {0:2d}]".format(lineno))
|
| 212 |
+
message.append(": section ")
|
| 213 |
+
message.extend(msg)
|
| 214 |
+
msg = message
|
| 215 |
+
else:
|
| 216 |
+
msg.insert(0, "Section ")
|
| 217 |
+
Error.__init__(self, "".join(msg))
|
| 218 |
+
self.section = section
|
| 219 |
+
self.source = source
|
| 220 |
+
self.lineno = lineno
|
| 221 |
+
self.args = (section, source, lineno)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
class DuplicateOptionError(Error):
|
| 225 |
+
"""Raised by strict parsers when an option is repeated in an input source.
|
| 226 |
+
|
| 227 |
+
Current implementation raises this exception only when an option is found
|
| 228 |
+
more than once in a single file, string or dictionary.
|
| 229 |
+
"""
|
| 230 |
+
|
| 231 |
+
def __init__(self, section, option, source=None, lineno=None):
|
| 232 |
+
msg = [repr(option), " in section ", repr(section),
|
| 233 |
+
" already exists"]
|
| 234 |
+
if source is not None:
|
| 235 |
+
message = ["While reading from ", repr(source)]
|
| 236 |
+
if lineno is not None:
|
| 237 |
+
message.append(" [line {0:2d}]".format(lineno))
|
| 238 |
+
message.append(": option ")
|
| 239 |
+
message.extend(msg)
|
| 240 |
+
msg = message
|
| 241 |
+
else:
|
| 242 |
+
msg.insert(0, "Option ")
|
| 243 |
+
Error.__init__(self, "".join(msg))
|
| 244 |
+
self.section = section
|
| 245 |
+
self.option = option
|
| 246 |
+
self.source = source
|
| 247 |
+
self.lineno = lineno
|
| 248 |
+
self.args = (section, option, source, lineno)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
class NoOptionError(Error):
|
| 252 |
+
"""A requested option was not found."""
|
| 253 |
+
|
| 254 |
+
def __init__(self, option, section):
|
| 255 |
+
Error.__init__(self, "No option %r in section: %r" %
|
| 256 |
+
(option, section))
|
| 257 |
+
self.option = option
|
| 258 |
+
self.section = section
|
| 259 |
+
self.args = (option, section)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class InterpolationError(Error):
|
| 263 |
+
"""Base class for interpolation-related exceptions."""
|
| 264 |
+
|
| 265 |
+
def __init__(self, option, section, msg):
|
| 266 |
+
Error.__init__(self, msg)
|
| 267 |
+
self.option = option
|
| 268 |
+
self.section = section
|
| 269 |
+
self.args = (option, section, msg)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
class InterpolationMissingOptionError(InterpolationError):
|
| 273 |
+
"""A string substitution required a setting which was not available."""
|
| 274 |
+
|
| 275 |
+
def __init__(self, option, section, rawval, reference):
|
| 276 |
+
msg = ("Bad value substitution: option {!r} in section {!r} contains "
|
| 277 |
+
"an interpolation key {!r} which is not a valid option name. "
|
| 278 |
+
"Raw value: {!r}".format(option, section, reference, rawval))
|
| 279 |
+
InterpolationError.__init__(self, option, section, msg)
|
| 280 |
+
self.reference = reference
|
| 281 |
+
self.args = (option, section, rawval, reference)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
class InterpolationSyntaxError(InterpolationError):
|
| 285 |
+
"""Raised when the source text contains invalid syntax.
|
| 286 |
+
|
| 287 |
+
Current implementation raises this exception when the source text into
|
| 288 |
+
which substitutions are made does not conform to the required syntax.
|
| 289 |
+
"""
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
class InterpolationDepthError(InterpolationError):
|
| 293 |
+
"""Raised when substitutions are nested too deeply."""
|
| 294 |
+
|
| 295 |
+
def __init__(self, option, section, rawval):
|
| 296 |
+
msg = ("Recursion limit exceeded in value substitution: option {!r} "
|
| 297 |
+
"in section {!r} contains an interpolation key which "
|
| 298 |
+
"cannot be substituted in {} steps. Raw value: {!r}"
|
| 299 |
+
"".format(option, section, MAX_INTERPOLATION_DEPTH,
|
| 300 |
+
rawval))
|
| 301 |
+
InterpolationError.__init__(self, option, section, msg)
|
| 302 |
+
self.args = (option, section, rawval)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
class ParsingError(Error):
|
| 306 |
+
"""Raised when a configuration file does not follow legal syntax."""
|
| 307 |
+
|
| 308 |
+
def __init__(self, source, *args):
|
| 309 |
+
super().__init__(f'Source contains parsing errors: {source!r}')
|
| 310 |
+
self.source = source
|
| 311 |
+
self.errors = []
|
| 312 |
+
self.args = (source, )
|
| 313 |
+
if args:
|
| 314 |
+
self.append(*args)
|
| 315 |
+
|
| 316 |
+
def append(self, lineno, line):
|
| 317 |
+
self.errors.append((lineno, line))
|
| 318 |
+
self.message += '\n\t[line %2d]: %s' % (lineno, repr(line))
|
| 319 |
+
|
| 320 |
+
def combine(self, others):
|
| 321 |
+
for other in others:
|
| 322 |
+
for error in other.errors:
|
| 323 |
+
self.append(*error)
|
| 324 |
+
return self
|
| 325 |
+
|
| 326 |
+
@staticmethod
|
| 327 |
+
def _raise_all(exceptions: Iterable['ParsingError']):
|
| 328 |
+
"""
|
| 329 |
+
Combine any number of ParsingErrors into one and raise it.
|
| 330 |
+
"""
|
| 331 |
+
exceptions = iter(exceptions)
|
| 332 |
+
with contextlib.suppress(StopIteration):
|
| 333 |
+
raise next(exceptions).combine(exceptions)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class MissingSectionHeaderError(ParsingError):
|
| 338 |
+
"""Raised when a key-value pair is found before any section header."""
|
| 339 |
+
|
| 340 |
+
def __init__(self, filename, lineno, line):
|
| 341 |
+
Error.__init__(
|
| 342 |
+
self,
|
| 343 |
+
'File contains no section headers.\nfile: %r, line: %d\n%r' %
|
| 344 |
+
(filename, lineno, line))
|
| 345 |
+
self.source = filename
|
| 346 |
+
self.lineno = lineno
|
| 347 |
+
self.line = line
|
| 348 |
+
self.args = (filename, lineno, line)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
class MultilineContinuationError(ParsingError):
|
| 352 |
+
"""Raised when a key without value is followed by continuation line"""
|
| 353 |
+
def __init__(self, filename, lineno, line):
|
| 354 |
+
Error.__init__(
|
| 355 |
+
self,
|
| 356 |
+
"Key without value continued with an indented line.\n"
|
| 357 |
+
"file: %r, line: %d\n%r"
|
| 358 |
+
%(filename, lineno, line))
|
| 359 |
+
self.source = filename
|
| 360 |
+
self.lineno = lineno
|
| 361 |
+
self.line = line
|
| 362 |
+
self.args = (filename, lineno, line)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
class UnnamedSectionDisabledError(Error):
|
| 366 |
+
"""Raised when an attempt to use UNNAMED_SECTION is made with the
|
| 367 |
+
feature disabled."""
|
| 368 |
+
def __init__(self):
|
| 369 |
+
Error.__init__(self, "Support for UNNAMED_SECTION is disabled.")
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
class _UnnamedSection:
|
| 373 |
+
|
| 374 |
+
def __repr__(self):
|
| 375 |
+
return "<UNNAMED_SECTION>"
|
| 376 |
+
|
| 377 |
+
class InvalidWriteError(Error):
|
| 378 |
+
"""Raised when attempting to write data that the parser would read back differently.
|
| 379 |
+
ex: writing a key which begins with the section header pattern would read back as a
|
| 380 |
+
new section """
|
| 381 |
+
|
| 382 |
+
def __init__(self, msg=''):
|
| 383 |
+
Error.__init__(self, msg)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
UNNAMED_SECTION = _UnnamedSection()
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
# Used in parser getters to indicate the default behaviour when a specific
|
| 390 |
+
# option is not found it to raise an exception. Created to enable `None` as
|
| 391 |
+
# a valid fallback value.
|
| 392 |
+
_UNSET = object()
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
class Interpolation:
|
| 396 |
+
"""Dummy interpolation that passes the value through with no changes."""
|
| 397 |
+
|
| 398 |
+
def before_get(self, parser, section, option, value, defaults):
|
| 399 |
+
return value
|
| 400 |
+
|
| 401 |
+
def before_set(self, parser, section, option, value):
|
| 402 |
+
return value
|
| 403 |
+
|
| 404 |
+
def before_read(self, parser, section, option, value):
|
| 405 |
+
return value
|
| 406 |
+
|
| 407 |
+
def before_write(self, parser, section, option, value):
|
| 408 |
+
return value
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
class BasicInterpolation(Interpolation):
|
| 412 |
+
"""Interpolation as implemented in the classic ConfigParser.
|
| 413 |
+
|
| 414 |
+
The option values can contain format strings which refer to other values in
|
| 415 |
+
the same section, or values in the special default section.
|
| 416 |
+
|
| 417 |
+
For example:
|
| 418 |
+
|
| 419 |
+
something: %(dir)s/whatever
|
| 420 |
+
|
| 421 |
+
would resolve the "%(dir)s" to the value of dir. All reference
|
| 422 |
+
expansions are done late, on demand. If a user needs to use a bare % in
|
| 423 |
+
a configuration file, she can escape it by writing %%. Other % usage
|
| 424 |
+
is considered a user error and raises `InterpolationSyntaxError`."""
|
| 425 |
+
|
| 426 |
+
_KEYCRE = re.compile(r"%\(([^)]+)\)s")
|
| 427 |
+
|
| 428 |
+
def before_get(self, parser, section, option, value, defaults):
|
| 429 |
+
L = []
|
| 430 |
+
self._interpolate_some(parser, option, L, value, section, defaults, 1)
|
| 431 |
+
return ''.join(L)
|
| 432 |
+
|
| 433 |
+
def before_set(self, parser, section, option, value):
|
| 434 |
+
tmp_value = value.replace('%%', '') # escaped percent signs
|
| 435 |
+
tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
|
| 436 |
+
if '%' in tmp_value:
|
| 437 |
+
raise ValueError("invalid interpolation syntax in %r at "
|
| 438 |
+
"position %d" % (value, tmp_value.find('%')))
|
| 439 |
+
return value
|
| 440 |
+
|
| 441 |
+
def _interpolate_some(self, parser, option, accum, rest, section, map,
|
| 442 |
+
depth):
|
| 443 |
+
rawval = parser.get(section, option, raw=True, fallback=rest)
|
| 444 |
+
if depth > MAX_INTERPOLATION_DEPTH:
|
| 445 |
+
raise InterpolationDepthError(option, section, rawval)
|
| 446 |
+
while rest:
|
| 447 |
+
p = rest.find("%")
|
| 448 |
+
if p < 0:
|
| 449 |
+
accum.append(rest)
|
| 450 |
+
return
|
| 451 |
+
if p > 0:
|
| 452 |
+
accum.append(rest[:p])
|
| 453 |
+
rest = rest[p:]
|
| 454 |
+
# p is no longer used
|
| 455 |
+
c = rest[1:2]
|
| 456 |
+
if c == "%":
|
| 457 |
+
accum.append("%")
|
| 458 |
+
rest = rest[2:]
|
| 459 |
+
elif c == "(":
|
| 460 |
+
m = self._KEYCRE.match(rest)
|
| 461 |
+
if m is None:
|
| 462 |
+
raise InterpolationSyntaxError(option, section,
|
| 463 |
+
"bad interpolation variable reference %r" % rest)
|
| 464 |
+
var = parser.optionxform(m.group(1))
|
| 465 |
+
rest = rest[m.end():]
|
| 466 |
+
try:
|
| 467 |
+
v = map[var]
|
| 468 |
+
except KeyError:
|
| 469 |
+
raise InterpolationMissingOptionError(
|
| 470 |
+
option, section, rawval, var) from None
|
| 471 |
+
if "%" in v:
|
| 472 |
+
self._interpolate_some(parser, option, accum, v,
|
| 473 |
+
section, map, depth + 1)
|
| 474 |
+
else:
|
| 475 |
+
accum.append(v)
|
| 476 |
+
else:
|
| 477 |
+
raise InterpolationSyntaxError(
|
| 478 |
+
option, section,
|
| 479 |
+
"'%%' must be followed by '%%' or '(', "
|
| 480 |
+
"found: %r" % (rest,))
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
class ExtendedInterpolation(Interpolation):
|
| 484 |
+
"""Advanced variant of interpolation, supports the syntax used by
|
| 485 |
+
`zc.buildout`. Enables interpolation between sections."""
|
| 486 |
+
|
| 487 |
+
_KEYCRE = re.compile(r"\$\{([^}]+)\}")
|
| 488 |
+
|
| 489 |
+
def before_get(self, parser, section, option, value, defaults):
|
| 490 |
+
L = []
|
| 491 |
+
self._interpolate_some(parser, option, L, value, section, defaults, 1)
|
| 492 |
+
return ''.join(L)
|
| 493 |
+
|
| 494 |
+
def before_set(self, parser, section, option, value):
|
| 495 |
+
tmp_value = value.replace('$$', '') # escaped dollar signs
|
| 496 |
+
tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
|
| 497 |
+
if '$' in tmp_value:
|
| 498 |
+
raise ValueError("invalid interpolation syntax in %r at "
|
| 499 |
+
"position %d" % (value, tmp_value.find('$')))
|
| 500 |
+
return value
|
| 501 |
+
|
| 502 |
+
def _interpolate_some(self, parser, option, accum, rest, section, map,
|
| 503 |
+
depth):
|
| 504 |
+
rawval = parser.get(section, option, raw=True, fallback=rest)
|
| 505 |
+
if depth > MAX_INTERPOLATION_DEPTH:
|
| 506 |
+
raise InterpolationDepthError(option, section, rawval)
|
| 507 |
+
while rest:
|
| 508 |
+
p = rest.find("$")
|
| 509 |
+
if p < 0:
|
| 510 |
+
accum.append(rest)
|
| 511 |
+
return
|
| 512 |
+
if p > 0:
|
| 513 |
+
accum.append(rest[:p])
|
| 514 |
+
rest = rest[p:]
|
| 515 |
+
# p is no longer used
|
| 516 |
+
c = rest[1:2]
|
| 517 |
+
if c == "$":
|
| 518 |
+
accum.append("$")
|
| 519 |
+
rest = rest[2:]
|
| 520 |
+
elif c == "{":
|
| 521 |
+
m = self._KEYCRE.match(rest)
|
| 522 |
+
if m is None:
|
| 523 |
+
raise InterpolationSyntaxError(option, section,
|
| 524 |
+
"bad interpolation variable reference %r" % rest)
|
| 525 |
+
path = m.group(1).split(':')
|
| 526 |
+
rest = rest[m.end():]
|
| 527 |
+
sect = section
|
| 528 |
+
opt = option
|
| 529 |
+
try:
|
| 530 |
+
if len(path) == 1:
|
| 531 |
+
opt = parser.optionxform(path[0])
|
| 532 |
+
v = map[opt]
|
| 533 |
+
elif len(path) == 2:
|
| 534 |
+
sect = path[0]
|
| 535 |
+
opt = parser.optionxform(path[1])
|
| 536 |
+
v = parser.get(sect, opt, raw=True)
|
| 537 |
+
else:
|
| 538 |
+
raise InterpolationSyntaxError(
|
| 539 |
+
option, section,
|
| 540 |
+
"More than one ':' found: %r" % (rest,))
|
| 541 |
+
except (KeyError, NoSectionError, NoOptionError):
|
| 542 |
+
raise InterpolationMissingOptionError(
|
| 543 |
+
option, section, rawval, ":".join(path)) from None
|
| 544 |
+
if v is None:
|
| 545 |
+
continue
|
| 546 |
+
if "$" in v:
|
| 547 |
+
self._interpolate_some(parser, opt, accum, v, sect,
|
| 548 |
+
dict(parser.items(sect, raw=True)),
|
| 549 |
+
depth + 1)
|
| 550 |
+
else:
|
| 551 |
+
accum.append(v)
|
| 552 |
+
else:
|
| 553 |
+
raise InterpolationSyntaxError(
|
| 554 |
+
option, section,
|
| 555 |
+
"'$' must be followed by '$' or '{', "
|
| 556 |
+
"found: %r" % (rest,))
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
class _ReadState:
|
| 560 |
+
elements_added : set[str]
|
| 561 |
+
cursect : dict[str, str] | None = None
|
| 562 |
+
sectname : str | None = None
|
| 563 |
+
optname : str | None = None
|
| 564 |
+
lineno : int = 0
|
| 565 |
+
indent_level : int = 0
|
| 566 |
+
errors : list[ParsingError]
|
| 567 |
+
|
| 568 |
+
def __init__(self):
|
| 569 |
+
self.elements_added = set()
|
| 570 |
+
self.errors = list()
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
class _Line(str):
|
| 574 |
+
__slots__ = 'clean', 'has_comments'
|
| 575 |
+
|
| 576 |
+
def __new__(cls, val, *args, **kwargs):
|
| 577 |
+
return super().__new__(cls, val)
|
| 578 |
+
|
| 579 |
+
def __init__(self, val, comments):
|
| 580 |
+
trimmed = val.strip()
|
| 581 |
+
self.clean = comments.strip(trimmed)
|
| 582 |
+
self.has_comments = trimmed != self.clean
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
class _CommentSpec:
|
| 586 |
+
def __init__(self, full_prefixes, inline_prefixes):
|
| 587 |
+
full_patterns = (
|
| 588 |
+
# prefix at the beginning of a line
|
| 589 |
+
fr'^({re.escape(prefix)}).*'
|
| 590 |
+
for prefix in full_prefixes
|
| 591 |
+
)
|
| 592 |
+
inline_patterns = (
|
| 593 |
+
# prefix at the beginning of the line or following a space
|
| 594 |
+
fr'(^|\s)({re.escape(prefix)}.*)'
|
| 595 |
+
for prefix in inline_prefixes
|
| 596 |
+
)
|
| 597 |
+
self.pattern = re.compile('|'.join(itertools.chain(full_patterns, inline_patterns)))
|
| 598 |
+
|
| 599 |
+
def strip(self, text):
|
| 600 |
+
return self.pattern.sub('', text).rstrip()
|
| 601 |
+
|
| 602 |
+
def wrap(self, text):
|
| 603 |
+
return _Line(text, self)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
class RawConfigParser(MutableMapping):
|
| 607 |
+
"""ConfigParser that does not do interpolation."""
|
| 608 |
+
|
| 609 |
+
# Regular expressions for parsing section headers and options
|
| 610 |
+
_SECT_TMPL = r"""
|
| 611 |
+
\[ # [
|
| 612 |
+
(?P<header>.+) # very permissive!
|
| 613 |
+
\] # ]
|
| 614 |
+
"""
|
| 615 |
+
_OPT_TMPL = r"""
|
| 616 |
+
(?P<option>.*?) # very permissive!
|
| 617 |
+
\s*(?P<vi>{delim})\s* # any number of space/tab,
|
| 618 |
+
# followed by any of the
|
| 619 |
+
# allowed delimiters,
|
| 620 |
+
# followed by any space/tab
|
| 621 |
+
(?P<value>.*)$ # everything up to eol
|
| 622 |
+
"""
|
| 623 |
+
_OPT_NV_TMPL = r"""
|
| 624 |
+
(?P<option>.*?) # very permissive!
|
| 625 |
+
\s*(?: # any number of space/tab,
|
| 626 |
+
(?P<vi>{delim})\s* # optionally followed by
|
| 627 |
+
# any of the allowed
|
| 628 |
+
# delimiters, followed by any
|
| 629 |
+
# space/tab
|
| 630 |
+
(?P<value>.*))?$ # everything up to eol
|
| 631 |
+
"""
|
| 632 |
+
# Interpolation algorithm to be used if the user does not specify another
|
| 633 |
+
_DEFAULT_INTERPOLATION = Interpolation()
|
| 634 |
+
# Compiled regular expression for matching sections
|
| 635 |
+
SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)
|
| 636 |
+
# Compiled regular expression for matching options with typical separators
|
| 637 |
+
OPTCRE = re.compile(_OPT_TMPL.format(delim="=|:"), re.VERBOSE)
|
| 638 |
+
# Compiled regular expression for matching options with optional values
|
| 639 |
+
# delimited using typical separators
|
| 640 |
+
OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|:"), re.VERBOSE)
|
| 641 |
+
# Compiled regular expression for matching leading whitespace in a line
|
| 642 |
+
NONSPACECRE = re.compile(r"\S")
|
| 643 |
+
# Possible boolean values in the configuration.
|
| 644 |
+
BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True,
|
| 645 |
+
'0': False, 'no': False, 'false': False, 'off': False}
|
| 646 |
+
|
| 647 |
+
def __init__(self, defaults=None, dict_type=_default_dict,
|
| 648 |
+
allow_no_value=False, *, delimiters=('=', ':'),
|
| 649 |
+
comment_prefixes=('#', ';'), inline_comment_prefixes=None,
|
| 650 |
+
strict=True, empty_lines_in_values=True,
|
| 651 |
+
default_section=DEFAULTSECT,
|
| 652 |
+
interpolation=_UNSET, converters=_UNSET,
|
| 653 |
+
allow_unnamed_section=False,):
|
| 654 |
+
|
| 655 |
+
self._dict = dict_type
|
| 656 |
+
self._sections = self._dict()
|
| 657 |
+
self._defaults = self._dict()
|
| 658 |
+
self._converters = ConverterMapping(self)
|
| 659 |
+
self._proxies = self._dict()
|
| 660 |
+
self._proxies[default_section] = SectionProxy(self, default_section)
|
| 661 |
+
self._delimiters = tuple(delimiters)
|
| 662 |
+
if delimiters == ('=', ':'):
|
| 663 |
+
self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
|
| 664 |
+
else:
|
| 665 |
+
d = "|".join(re.escape(d) for d in delimiters)
|
| 666 |
+
if allow_no_value:
|
| 667 |
+
self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
|
| 668 |
+
re.VERBOSE)
|
| 669 |
+
else:
|
| 670 |
+
self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
|
| 671 |
+
re.VERBOSE)
|
| 672 |
+
self._comments = _CommentSpec(comment_prefixes or (), inline_comment_prefixes or ())
|
| 673 |
+
self._strict = strict
|
| 674 |
+
self._allow_no_value = allow_no_value
|
| 675 |
+
self._empty_lines_in_values = empty_lines_in_values
|
| 676 |
+
self.default_section=default_section
|
| 677 |
+
self._interpolation = interpolation
|
| 678 |
+
if self._interpolation is _UNSET:
|
| 679 |
+
self._interpolation = self._DEFAULT_INTERPOLATION
|
| 680 |
+
if self._interpolation is None:
|
| 681 |
+
self._interpolation = Interpolation()
|
| 682 |
+
if not isinstance(self._interpolation, Interpolation):
|
| 683 |
+
raise TypeError(
|
| 684 |
+
f"interpolation= must be None or an instance of Interpolation;"
|
| 685 |
+
f" got an object of type {type(self._interpolation)}"
|
| 686 |
+
)
|
| 687 |
+
if converters is not _UNSET:
|
| 688 |
+
self._converters.update(converters)
|
| 689 |
+
if defaults:
|
| 690 |
+
self._read_defaults(defaults)
|
| 691 |
+
self._allow_unnamed_section = allow_unnamed_section
|
| 692 |
+
|
| 693 |
+
def defaults(self):
|
| 694 |
+
return self._defaults
|
| 695 |
+
|
| 696 |
+
def sections(self):
|
| 697 |
+
"""Return a list of section names, excluding [DEFAULT]"""
|
| 698 |
+
# self._sections will never have [DEFAULT] in it
|
| 699 |
+
return list(self._sections.keys())
|
| 700 |
+
|
| 701 |
+
def add_section(self, section):
|
| 702 |
+
"""Create a new section in the configuration.
|
| 703 |
+
|
| 704 |
+
Raise DuplicateSectionError if a section by the specified name
|
| 705 |
+
already exists. Raise ValueError if name is DEFAULT.
|
| 706 |
+
"""
|
| 707 |
+
if section == self.default_section:
|
| 708 |
+
raise ValueError('Invalid section name: %r' % section)
|
| 709 |
+
|
| 710 |
+
if section is UNNAMED_SECTION:
|
| 711 |
+
if not self._allow_unnamed_section:
|
| 712 |
+
raise UnnamedSectionDisabledError
|
| 713 |
+
|
| 714 |
+
if section in self._sections:
|
| 715 |
+
raise DuplicateSectionError(section)
|
| 716 |
+
self._sections[section] = self._dict()
|
| 717 |
+
self._proxies[section] = SectionProxy(self, section)
|
| 718 |
+
|
| 719 |
+
def has_section(self, section):
|
| 720 |
+
"""Indicate whether the named section is present in the configuration.
|
| 721 |
+
|
| 722 |
+
The DEFAULT section is not acknowledged.
|
| 723 |
+
"""
|
| 724 |
+
return section in self._sections
|
| 725 |
+
|
| 726 |
+
def options(self, section):
|
| 727 |
+
"""Return a list of option names for the given section name."""
|
| 728 |
+
try:
|
| 729 |
+
opts = self._sections[section].copy()
|
| 730 |
+
except KeyError:
|
| 731 |
+
raise NoSectionError(section) from None
|
| 732 |
+
opts.update(self._defaults)
|
| 733 |
+
return list(opts.keys())
|
| 734 |
+
|
| 735 |
+
def read(self, filenames, encoding=None):
|
| 736 |
+
"""Read and parse a filename or an iterable of filenames.
|
| 737 |
+
|
| 738 |
+
Files that cannot be opened are silently ignored; this is
|
| 739 |
+
designed so that you can specify an iterable of potential
|
| 740 |
+
configuration file locations (e.g. current directory, user's
|
| 741 |
+
home directory, systemwide directory), and all existing
|
| 742 |
+
configuration files in the iterable will be read. A single
|
| 743 |
+
filename may also be given.
|
| 744 |
+
|
| 745 |
+
Return list of successfully read files.
|
| 746 |
+
"""
|
| 747 |
+
if isinstance(filenames, (str, bytes, os.PathLike)):
|
| 748 |
+
filenames = [filenames]
|
| 749 |
+
encoding = io.text_encoding(encoding)
|
| 750 |
+
read_ok = []
|
| 751 |
+
for filename in filenames:
|
| 752 |
+
try:
|
| 753 |
+
with open(filename, encoding=encoding) as fp:
|
| 754 |
+
self._read(fp, filename)
|
| 755 |
+
except OSError:
|
| 756 |
+
continue
|
| 757 |
+
if isinstance(filename, os.PathLike):
|
| 758 |
+
filename = os.fspath(filename)
|
| 759 |
+
read_ok.append(filename)
|
| 760 |
+
return read_ok
|
| 761 |
+
|
| 762 |
+
def read_file(self, f, source=None):
|
| 763 |
+
"""Like read() but the argument must be a file-like object.
|
| 764 |
+
|
| 765 |
+
The `f` argument must be iterable, returning one line at a time.
|
| 766 |
+
Optional second argument is the `source` specifying the name of the
|
| 767 |
+
file being read. If not given, it is taken from f.name. If `f` has no
|
| 768 |
+
`name` attribute, `<???>` is used.
|
| 769 |
+
"""
|
| 770 |
+
if source is None:
|
| 771 |
+
try:
|
| 772 |
+
source = f.name
|
| 773 |
+
except AttributeError:
|
| 774 |
+
source = '<???>'
|
| 775 |
+
self._read(f, source)
|
| 776 |
+
|
| 777 |
+
def read_string(self, string, source='<string>'):
|
| 778 |
+
"""Read configuration from a given string."""
|
| 779 |
+
sfile = io.StringIO(string)
|
| 780 |
+
self.read_file(sfile, source)
|
| 781 |
+
|
| 782 |
+
def read_dict(self, dictionary, source='<dict>'):
|
| 783 |
+
"""Read configuration from a dictionary.
|
| 784 |
+
|
| 785 |
+
Keys are section names, values are dictionaries with keys and values
|
| 786 |
+
that should be present in the section. If the used dictionary type
|
| 787 |
+
preserves order, sections and their keys will be added in order.
|
| 788 |
+
|
| 789 |
+
All types held in the dictionary are converted to strings during
|
| 790 |
+
reading, including section names, option names and keys.
|
| 791 |
+
|
| 792 |
+
Optional second argument is the `source` specifying the name of the
|
| 793 |
+
dictionary being read.
|
| 794 |
+
"""
|
| 795 |
+
elements_added = set()
|
| 796 |
+
for section, keys in dictionary.items():
|
| 797 |
+
if section is not UNNAMED_SECTION:
|
| 798 |
+
section = str(section)
|
| 799 |
+
try:
|
| 800 |
+
self.add_section(section)
|
| 801 |
+
except (DuplicateSectionError, ValueError):
|
| 802 |
+
if self._strict and section in elements_added:
|
| 803 |
+
raise
|
| 804 |
+
elements_added.add(section)
|
| 805 |
+
for key, value in keys.items():
|
| 806 |
+
key = self.optionxform(str(key))
|
| 807 |
+
if value is not None:
|
| 808 |
+
value = str(value)
|
| 809 |
+
if self._strict and (section, key) in elements_added:
|
| 810 |
+
raise DuplicateOptionError(section, key, source)
|
| 811 |
+
elements_added.add((section, key))
|
| 812 |
+
self.set(section, key, value)
|
| 813 |
+
|
| 814 |
+
def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
|
| 815 |
+
"""Get an option value for a given section.
|
| 816 |
+
|
| 817 |
+
If `vars` is provided, it must be a dictionary. The option is looked up
|
| 818 |
+
in `vars` (if provided), `section`, and in `DEFAULTSECT` in that order.
|
| 819 |
+
If the key is not found and `fallback` is provided, it is used as
|
| 820 |
+
a fallback value. `None` can be provided as a `fallback` value.
|
| 821 |
+
|
| 822 |
+
If interpolation is enabled and the optional argument `raw` is False,
|
| 823 |
+
all interpolations are expanded in the return values.
|
| 824 |
+
|
| 825 |
+
Arguments `raw`, `vars`, and `fallback` are keyword only.
|
| 826 |
+
|
| 827 |
+
The section DEFAULT is special.
|
| 828 |
+
"""
|
| 829 |
+
try:
|
| 830 |
+
d = self._unify_values(section, vars)
|
| 831 |
+
except NoSectionError:
|
| 832 |
+
if fallback is _UNSET:
|
| 833 |
+
raise
|
| 834 |
+
else:
|
| 835 |
+
return fallback
|
| 836 |
+
option = self.optionxform(option)
|
| 837 |
+
try:
|
| 838 |
+
value = d[option]
|
| 839 |
+
except KeyError:
|
| 840 |
+
if fallback is _UNSET:
|
| 841 |
+
raise NoOptionError(option, section)
|
| 842 |
+
else:
|
| 843 |
+
return fallback
|
| 844 |
+
|
| 845 |
+
if raw or value is None:
|
| 846 |
+
return value
|
| 847 |
+
else:
|
| 848 |
+
return self._interpolation.before_get(self, section, option, value,
|
| 849 |
+
d)
|
| 850 |
+
|
| 851 |
+
def _get(self, section, conv, option, **kwargs):
|
| 852 |
+
return conv(self.get(section, option, **kwargs))
|
| 853 |
+
|
| 854 |
+
def _get_conv(self, section, option, conv, *, raw=False, vars=None,
|
| 855 |
+
fallback=_UNSET, **kwargs):
|
| 856 |
+
try:
|
| 857 |
+
return self._get(section, conv, option, raw=raw, vars=vars,
|
| 858 |
+
**kwargs)
|
| 859 |
+
except (NoSectionError, NoOptionError):
|
| 860 |
+
if fallback is _UNSET:
|
| 861 |
+
raise
|
| 862 |
+
return fallback
|
| 863 |
+
|
| 864 |
+
# getint, getfloat and getboolean provided directly for backwards compat
|
| 865 |
+
def getint(self, section, option, *, raw=False, vars=None,
|
| 866 |
+
fallback=_UNSET, **kwargs):
|
| 867 |
+
return self._get_conv(section, option, int, raw=raw, vars=vars,
|
| 868 |
+
fallback=fallback, **kwargs)
|
| 869 |
+
|
| 870 |
+
def getfloat(self, section, option, *, raw=False, vars=None,
|
| 871 |
+
fallback=_UNSET, **kwargs):
|
| 872 |
+
return self._get_conv(section, option, float, raw=raw, vars=vars,
|
| 873 |
+
fallback=fallback, **kwargs)
|
| 874 |
+
|
| 875 |
+
def getboolean(self, section, option, *, raw=False, vars=None,
|
| 876 |
+
fallback=_UNSET, **kwargs):
|
| 877 |
+
return self._get_conv(section, option, self._convert_to_boolean,
|
| 878 |
+
raw=raw, vars=vars, fallback=fallback, **kwargs)
|
| 879 |
+
|
| 880 |
+
def items(self, section=_UNSET, raw=False, vars=None):
|
| 881 |
+
"""Return a list of (name, value) tuples for each option in a section.
|
| 882 |
+
|
| 883 |
+
All % interpolations are expanded in the return values, based on the
|
| 884 |
+
defaults passed into the constructor, unless the optional argument
|
| 885 |
+
`raw` is true. Additional substitutions may be provided using the
|
| 886 |
+
`vars` argument, which must be a dictionary whose contents overrides
|
| 887 |
+
any pre-existing defaults.
|
| 888 |
+
|
| 889 |
+
The section DEFAULT is special.
|
| 890 |
+
"""
|
| 891 |
+
if section is _UNSET:
|
| 892 |
+
return super().items()
|
| 893 |
+
d = self._defaults.copy()
|
| 894 |
+
try:
|
| 895 |
+
d.update(self._sections[section])
|
| 896 |
+
except KeyError:
|
| 897 |
+
if section != self.default_section:
|
| 898 |
+
raise NoSectionError(section)
|
| 899 |
+
orig_keys = list(d.keys())
|
| 900 |
+
# Update with the entry specific variables
|
| 901 |
+
if vars:
|
| 902 |
+
for key, value in vars.items():
|
| 903 |
+
d[self.optionxform(key)] = value
|
| 904 |
+
value_getter = lambda option: self._interpolation.before_get(self,
|
| 905 |
+
section, option, d[option], d)
|
| 906 |
+
if raw:
|
| 907 |
+
value_getter = lambda option: d[option]
|
| 908 |
+
return [(option, value_getter(option)) for option in orig_keys]
|
| 909 |
+
|
| 910 |
+
def popitem(self):
|
| 911 |
+
"""Remove a section from the parser and return it as
|
| 912 |
+
a (section_name, section_proxy) tuple. If no section is present, raise
|
| 913 |
+
KeyError.
|
| 914 |
+
|
| 915 |
+
The section DEFAULT is never returned because it cannot be removed.
|
| 916 |
+
"""
|
| 917 |
+
for key in self.sections():
|
| 918 |
+
value = self[key]
|
| 919 |
+
del self[key]
|
| 920 |
+
return key, value
|
| 921 |
+
raise KeyError
|
| 922 |
+
|
| 923 |
+
def optionxform(self, optionstr):
|
| 924 |
+
return optionstr.lower()
|
| 925 |
+
|
| 926 |
+
def has_option(self, section, option):
|
| 927 |
+
"""Check for the existence of a given option in a given section.
|
| 928 |
+
If the specified `section` is None or an empty string, DEFAULT is
|
| 929 |
+
assumed. If the specified `section` does not exist, returns False."""
|
| 930 |
+
if not section or section == self.default_section:
|
| 931 |
+
option = self.optionxform(option)
|
| 932 |
+
return option in self._defaults
|
| 933 |
+
elif section not in self._sections:
|
| 934 |
+
return False
|
| 935 |
+
else:
|
| 936 |
+
option = self.optionxform(option)
|
| 937 |
+
return (option in self._sections[section]
|
| 938 |
+
or option in self._defaults)
|
| 939 |
+
|
| 940 |
+
def set(self, section, option, value=None):
|
| 941 |
+
"""Set an option."""
|
| 942 |
+
if value:
|
| 943 |
+
value = self._interpolation.before_set(self, section, option,
|
| 944 |
+
value)
|
| 945 |
+
if not section or section == self.default_section:
|
| 946 |
+
sectdict = self._defaults
|
| 947 |
+
else:
|
| 948 |
+
try:
|
| 949 |
+
sectdict = self._sections[section]
|
| 950 |
+
except KeyError:
|
| 951 |
+
raise NoSectionError(section) from None
|
| 952 |
+
sectdict[self.optionxform(option)] = value
|
| 953 |
+
|
| 954 |
+
def write(self, fp, space_around_delimiters=True):
|
| 955 |
+
"""Write an .ini-format representation of the configuration state.
|
| 956 |
+
|
| 957 |
+
If `space_around_delimiters` is True (the default), delimiters
|
| 958 |
+
between keys and values are surrounded by spaces.
|
| 959 |
+
|
| 960 |
+
Please note that comments in the original configuration file are not
|
| 961 |
+
preserved when writing the configuration back.
|
| 962 |
+
"""
|
| 963 |
+
if space_around_delimiters:
|
| 964 |
+
d = " {} ".format(self._delimiters[0])
|
| 965 |
+
else:
|
| 966 |
+
d = self._delimiters[0]
|
| 967 |
+
if self._defaults:
|
| 968 |
+
self._write_section(fp, self.default_section,
|
| 969 |
+
self._defaults.items(), d)
|
| 970 |
+
if UNNAMED_SECTION in self._sections and self._sections[UNNAMED_SECTION]:
|
| 971 |
+
self._write_section(fp, UNNAMED_SECTION, self._sections[UNNAMED_SECTION].items(), d, unnamed=True)
|
| 972 |
+
|
| 973 |
+
for section in self._sections:
|
| 974 |
+
if section is UNNAMED_SECTION:
|
| 975 |
+
continue
|
| 976 |
+
self._write_section(fp, section,
|
| 977 |
+
self._sections[section].items(), d)
|
| 978 |
+
|
| 979 |
+
def _write_section(self, fp, section_name, section_items, delimiter, unnamed=False):
|
| 980 |
+
"""Write a single section to the specified 'fp'."""
|
| 981 |
+
if not unnamed:
|
| 982 |
+
fp.write("[{}]\n".format(section_name))
|
| 983 |
+
for key, value in section_items:
|
| 984 |
+
self._validate_key_contents(key)
|
| 985 |
+
value = self._interpolation.before_write(self, section_name, key,
|
| 986 |
+
value)
|
| 987 |
+
if value is not None or not self._allow_no_value:
|
| 988 |
+
value = delimiter + str(value).replace('\n', '\n\t')
|
| 989 |
+
else:
|
| 990 |
+
value = ""
|
| 991 |
+
fp.write("{}{}\n".format(key, value))
|
| 992 |
+
fp.write("\n")
|
| 993 |
+
|
| 994 |
+
def remove_option(self, section, option):
|
| 995 |
+
"""Remove an option."""
|
| 996 |
+
if not section or section == self.default_section:
|
| 997 |
+
sectdict = self._defaults
|
| 998 |
+
else:
|
| 999 |
+
try:
|
| 1000 |
+
sectdict = self._sections[section]
|
| 1001 |
+
except KeyError:
|
| 1002 |
+
raise NoSectionError(section) from None
|
| 1003 |
+
option = self.optionxform(option)
|
| 1004 |
+
existed = option in sectdict
|
| 1005 |
+
if existed:
|
| 1006 |
+
del sectdict[option]
|
| 1007 |
+
return existed
|
| 1008 |
+
|
| 1009 |
+
def remove_section(self, section):
|
| 1010 |
+
"""Remove a file section."""
|
| 1011 |
+
existed = section in self._sections
|
| 1012 |
+
if existed:
|
| 1013 |
+
del self._sections[section]
|
| 1014 |
+
del self._proxies[section]
|
| 1015 |
+
return existed
|
| 1016 |
+
|
| 1017 |
+
def __getitem__(self, key):
|
| 1018 |
+
if key != self.default_section and not self.has_section(key):
|
| 1019 |
+
raise KeyError(key)
|
| 1020 |
+
return self._proxies[key]
|
| 1021 |
+
|
| 1022 |
+
def __setitem__(self, key, value):
|
| 1023 |
+
# To conform with the mapping protocol, overwrites existing values in
|
| 1024 |
+
# the section.
|
| 1025 |
+
if key in self and self[key] is value:
|
| 1026 |
+
return
|
| 1027 |
+
# XXX this is not atomic if read_dict fails at any point. Then again,
|
| 1028 |
+
# no update method in configparser is atomic in this implementation.
|
| 1029 |
+
if key == self.default_section:
|
| 1030 |
+
self._defaults.clear()
|
| 1031 |
+
elif key in self._sections:
|
| 1032 |
+
self._sections[key].clear()
|
| 1033 |
+
self.read_dict({key: value})
|
| 1034 |
+
|
| 1035 |
+
def __delitem__(self, key):
|
| 1036 |
+
if key == self.default_section:
|
| 1037 |
+
raise ValueError("Cannot remove the default section.")
|
| 1038 |
+
if not self.has_section(key):
|
| 1039 |
+
raise KeyError(key)
|
| 1040 |
+
self.remove_section(key)
|
| 1041 |
+
|
| 1042 |
+
def __contains__(self, key):
|
| 1043 |
+
return key == self.default_section or self.has_section(key)
|
| 1044 |
+
|
| 1045 |
+
def __len__(self):
|
| 1046 |
+
return len(self._sections) + 1 # the default section
|
| 1047 |
+
|
| 1048 |
+
def __iter__(self):
|
| 1049 |
+
# XXX does it break when underlying container state changed?
|
| 1050 |
+
return itertools.chain((self.default_section,), self._sections.keys())
|
| 1051 |
+
|
| 1052 |
+
def _read(self, fp, fpname):
|
| 1053 |
+
"""Parse a sectioned configuration file.
|
| 1054 |
+
|
| 1055 |
+
Each section in a configuration file contains a header, indicated by
|
| 1056 |
+
a name in square brackets (`[]`), plus key/value options, indicated by
|
| 1057 |
+
`name` and `value` delimited with a specific substring (`=` or `:` by
|
| 1058 |
+
default).
|
| 1059 |
+
|
| 1060 |
+
Values can span multiple lines, as long as they are indented deeper
|
| 1061 |
+
than the first line of the value. Depending on the parser's mode, blank
|
| 1062 |
+
lines may be treated as parts of multiline values or ignored.
|
| 1063 |
+
|
| 1064 |
+
Configuration files may include comments, prefixed by specific
|
| 1065 |
+
characters (`#` and `;` by default). Comments may appear on their own
|
| 1066 |
+
in an otherwise empty line or may be entered in lines holding values or
|
| 1067 |
+
section names. Please note that comments get stripped off when reading configuration files.
|
| 1068 |
+
"""
|
| 1069 |
+
try:
|
| 1070 |
+
ParsingError._raise_all(self._read_inner(fp, fpname))
|
| 1071 |
+
finally:
|
| 1072 |
+
self._join_multiline_values()
|
| 1073 |
+
|
| 1074 |
+
def _read_inner(self, fp, fpname):
|
| 1075 |
+
st = _ReadState()
|
| 1076 |
+
|
| 1077 |
+
for st.lineno, line in enumerate(map(self._comments.wrap, fp), start=1):
|
| 1078 |
+
if not line.clean:
|
| 1079 |
+
if self._empty_lines_in_values:
|
| 1080 |
+
# add empty line to the value, but only if there was no
|
| 1081 |
+
# comment on the line
|
| 1082 |
+
if (not line.has_comments and
|
| 1083 |
+
st.cursect is not None and
|
| 1084 |
+
st.optname and
|
| 1085 |
+
st.cursect[st.optname] is not None):
|
| 1086 |
+
st.cursect[st.optname].append('') # newlines added at join
|
| 1087 |
+
else:
|
| 1088 |
+
# empty line marks end of value
|
| 1089 |
+
st.indent_level = sys.maxsize
|
| 1090 |
+
continue
|
| 1091 |
+
|
| 1092 |
+
first_nonspace = self.NONSPACECRE.search(line)
|
| 1093 |
+
st.cur_indent_level = first_nonspace.start() if first_nonspace else 0
|
| 1094 |
+
|
| 1095 |
+
if self._handle_continuation_line(st, line, fpname):
|
| 1096 |
+
continue
|
| 1097 |
+
|
| 1098 |
+
self._handle_rest(st, line, fpname)
|
| 1099 |
+
|
| 1100 |
+
return st.errors
|
| 1101 |
+
|
| 1102 |
+
def _handle_continuation_line(self, st, line, fpname):
|
| 1103 |
+
# continuation line?
|
| 1104 |
+
is_continue = (st.cursect is not None and st.optname and
|
| 1105 |
+
st.cur_indent_level > st.indent_level)
|
| 1106 |
+
if is_continue:
|
| 1107 |
+
if st.cursect[st.optname] is None:
|
| 1108 |
+
raise MultilineContinuationError(fpname, st.lineno, line)
|
| 1109 |
+
st.cursect[st.optname].append(line.clean)
|
| 1110 |
+
return is_continue
|
| 1111 |
+
|
| 1112 |
+
def _handle_rest(self, st, line, fpname):
|
| 1113 |
+
# a section header or option header?
|
| 1114 |
+
if self._allow_unnamed_section and st.cursect is None:
|
| 1115 |
+
self._handle_header(st, UNNAMED_SECTION, fpname)
|
| 1116 |
+
|
| 1117 |
+
st.indent_level = st.cur_indent_level
|
| 1118 |
+
# is it a section header?
|
| 1119 |
+
mo = self.SECTCRE.match(line.clean)
|
| 1120 |
+
|
| 1121 |
+
if not mo and st.cursect is None:
|
| 1122 |
+
raise MissingSectionHeaderError(fpname, st.lineno, line)
|
| 1123 |
+
|
| 1124 |
+
self._handle_header(st, mo.group('header'), fpname) if mo else self._handle_option(st, line, fpname)
|
| 1125 |
+
|
| 1126 |
+
def _handle_header(self, st, sectname, fpname):
|
| 1127 |
+
st.sectname = sectname
|
| 1128 |
+
if st.sectname in self._sections:
|
| 1129 |
+
if self._strict and st.sectname in st.elements_added:
|
| 1130 |
+
raise DuplicateSectionError(st.sectname, fpname,
|
| 1131 |
+
st.lineno)
|
| 1132 |
+
st.cursect = self._sections[st.sectname]
|
| 1133 |
+
st.elements_added.add(st.sectname)
|
| 1134 |
+
elif st.sectname == self.default_section:
|
| 1135 |
+
st.cursect = self._defaults
|
| 1136 |
+
else:
|
| 1137 |
+
st.cursect = self._dict()
|
| 1138 |
+
self._sections[st.sectname] = st.cursect
|
| 1139 |
+
self._proxies[st.sectname] = SectionProxy(self, st.sectname)
|
| 1140 |
+
st.elements_added.add(st.sectname)
|
| 1141 |
+
# So sections can't start with a continuation line
|
| 1142 |
+
st.optname = None
|
| 1143 |
+
|
| 1144 |
+
def _handle_option(self, st, line, fpname):
|
| 1145 |
+
# an option line?
|
| 1146 |
+
st.indent_level = st.cur_indent_level
|
| 1147 |
+
|
| 1148 |
+
mo = self._optcre.match(line.clean)
|
| 1149 |
+
if not mo:
|
| 1150 |
+
# a non-fatal parsing error occurred. set up the
|
| 1151 |
+
# exception but keep going. the exception will be
|
| 1152 |
+
# raised at the end of the file and will contain a
|
| 1153 |
+
# list of all bogus lines
|
| 1154 |
+
st.errors.append(ParsingError(fpname, st.lineno, line))
|
| 1155 |
+
return
|
| 1156 |
+
|
| 1157 |
+
st.optname, vi, optval = mo.group('option', 'vi', 'value')
|
| 1158 |
+
if not st.optname:
|
| 1159 |
+
st.errors.append(ParsingError(fpname, st.lineno, line))
|
| 1160 |
+
st.optname = self.optionxform(st.optname.rstrip())
|
| 1161 |
+
if (self._strict and
|
| 1162 |
+
(st.sectname, st.optname) in st.elements_added):
|
| 1163 |
+
raise DuplicateOptionError(st.sectname, st.optname,
|
| 1164 |
+
fpname, st.lineno)
|
| 1165 |
+
st.elements_added.add((st.sectname, st.optname))
|
| 1166 |
+
# This check is fine because the OPTCRE cannot
|
| 1167 |
+
# match if it would set optval to None
|
| 1168 |
+
if optval is not None:
|
| 1169 |
+
optval = optval.strip()
|
| 1170 |
+
st.cursect[st.optname] = [optval]
|
| 1171 |
+
else:
|
| 1172 |
+
# valueless option handling
|
| 1173 |
+
st.cursect[st.optname] = None
|
| 1174 |
+
|
| 1175 |
+
def _join_multiline_values(self):
|
| 1176 |
+
defaults = self.default_section, self._defaults
|
| 1177 |
+
all_sections = itertools.chain((defaults,),
|
| 1178 |
+
self._sections.items())
|
| 1179 |
+
for section, options in all_sections:
|
| 1180 |
+
for name, val in options.items():
|
| 1181 |
+
if isinstance(val, list):
|
| 1182 |
+
val = '\n'.join(val).rstrip()
|
| 1183 |
+
options[name] = self._interpolation.before_read(self,
|
| 1184 |
+
section,
|
| 1185 |
+
name, val)
|
| 1186 |
+
|
| 1187 |
+
def _read_defaults(self, defaults):
|
| 1188 |
+
"""Read the defaults passed in the initializer.
|
| 1189 |
+
Note: values can be non-string."""
|
| 1190 |
+
for key, value in defaults.items():
|
| 1191 |
+
self._defaults[self.optionxform(key)] = value
|
| 1192 |
+
|
| 1193 |
+
def _unify_values(self, section, vars):
|
| 1194 |
+
"""Create a sequence of lookups with 'vars' taking priority over
|
| 1195 |
+
the 'section' which takes priority over the DEFAULTSECT.
|
| 1196 |
+
|
| 1197 |
+
"""
|
| 1198 |
+
sectiondict = {}
|
| 1199 |
+
try:
|
| 1200 |
+
sectiondict = self._sections[section]
|
| 1201 |
+
except KeyError:
|
| 1202 |
+
if section != self.default_section:
|
| 1203 |
+
raise NoSectionError(section) from None
|
| 1204 |
+
# Update with the entry specific variables
|
| 1205 |
+
vardict = {}
|
| 1206 |
+
if vars:
|
| 1207 |
+
for key, value in vars.items():
|
| 1208 |
+
if value is not None:
|
| 1209 |
+
value = str(value)
|
| 1210 |
+
vardict[self.optionxform(key)] = value
|
| 1211 |
+
return _ChainMap(vardict, sectiondict, self._defaults)
|
| 1212 |
+
|
| 1213 |
+
def _convert_to_boolean(self, value):
|
| 1214 |
+
"""Return a boolean value translating from other types if necessary.
|
| 1215 |
+
"""
|
| 1216 |
+
if value.lower() not in self.BOOLEAN_STATES:
|
| 1217 |
+
raise ValueError('Not a boolean: %s' % value)
|
| 1218 |
+
return self.BOOLEAN_STATES[value.lower()]
|
| 1219 |
+
|
| 1220 |
+
def _validate_key_contents(self, key):
|
| 1221 |
+
"""Raises an InvalidWriteError for any keys containing
|
| 1222 |
+
delimiters or that begins with the section header pattern"""
|
| 1223 |
+
if re.match(self.SECTCRE, key):
|
| 1224 |
+
raise InvalidWriteError(
|
| 1225 |
+
f"Cannot write key {key}; begins with section pattern")
|
| 1226 |
+
for delim in self._delimiters:
|
| 1227 |
+
if delim in key:
|
| 1228 |
+
raise InvalidWriteError(
|
| 1229 |
+
f"Cannot write key {key}; contains delimiter {delim}")
|
| 1230 |
+
|
| 1231 |
+
def _validate_value_types(self, *, section="", option="", value=""):
|
| 1232 |
+
"""Raises a TypeError for illegal non-string values.
|
| 1233 |
+
|
| 1234 |
+
Legal non-string values are UNNAMED_SECTION and falsey values if
|
| 1235 |
+
they are allowed.
|
| 1236 |
+
|
| 1237 |
+
For compatibility reasons this method is not used in classic set()
|
| 1238 |
+
for RawConfigParsers. It is invoked in every case for mapping protocol
|
| 1239 |
+
access and in ConfigParser.set().
|
| 1240 |
+
"""
|
| 1241 |
+
if section is UNNAMED_SECTION:
|
| 1242 |
+
if not self._allow_unnamed_section:
|
| 1243 |
+
raise UnnamedSectionDisabledError
|
| 1244 |
+
elif not isinstance(section, str):
|
| 1245 |
+
raise TypeError("section names must be strings or UNNAMED_SECTION")
|
| 1246 |
+
if not isinstance(option, str):
|
| 1247 |
+
raise TypeError("option keys must be strings")
|
| 1248 |
+
if not self._allow_no_value or value:
|
| 1249 |
+
if not isinstance(value, str):
|
| 1250 |
+
raise TypeError("option values must be strings")
|
| 1251 |
+
|
| 1252 |
+
@property
|
| 1253 |
+
def converters(self):
|
| 1254 |
+
return self._converters
|
| 1255 |
+
|
| 1256 |
+
|
| 1257 |
+
class ConfigParser(RawConfigParser):
|
| 1258 |
+
"""ConfigParser implementing interpolation."""
|
| 1259 |
+
|
| 1260 |
+
_DEFAULT_INTERPOLATION = BasicInterpolation()
|
| 1261 |
+
|
| 1262 |
+
def set(self, section, option, value=None):
|
| 1263 |
+
"""Set an option. Extends RawConfigParser.set by validating type and
|
| 1264 |
+
interpolation syntax on the value."""
|
| 1265 |
+
self._validate_value_types(option=option, value=value)
|
| 1266 |
+
super().set(section, option, value)
|
| 1267 |
+
|
| 1268 |
+
def add_section(self, section):
|
| 1269 |
+
"""Create a new section in the configuration. Extends
|
| 1270 |
+
RawConfigParser.add_section by validating if the section name is
|
| 1271 |
+
a string."""
|
| 1272 |
+
self._validate_value_types(section=section)
|
| 1273 |
+
super().add_section(section)
|
| 1274 |
+
|
| 1275 |
+
def _read_defaults(self, defaults):
|
| 1276 |
+
"""Reads the defaults passed in the initializer, implicitly converting
|
| 1277 |
+
values to strings like the rest of the API.
|
| 1278 |
+
|
| 1279 |
+
Does not perform interpolation for backwards compatibility.
|
| 1280 |
+
"""
|
| 1281 |
+
try:
|
| 1282 |
+
hold_interpolation = self._interpolation
|
| 1283 |
+
self._interpolation = Interpolation()
|
| 1284 |
+
self.read_dict({self.default_section: defaults})
|
| 1285 |
+
finally:
|
| 1286 |
+
self._interpolation = hold_interpolation
|
| 1287 |
+
|
| 1288 |
+
|
| 1289 |
+
class SectionProxy(MutableMapping):
|
| 1290 |
+
"""A proxy for a single section from a parser."""
|
| 1291 |
+
|
| 1292 |
+
def __init__(self, parser, name):
|
| 1293 |
+
"""Creates a view on a section of the specified `name` in `parser`."""
|
| 1294 |
+
self._parser = parser
|
| 1295 |
+
self._name = name
|
| 1296 |
+
for conv in parser.converters:
|
| 1297 |
+
key = 'get' + conv
|
| 1298 |
+
getter = functools.partial(self.get, _impl=getattr(parser, key))
|
| 1299 |
+
setattr(self, key, getter)
|
| 1300 |
+
|
| 1301 |
+
def __repr__(self):
|
| 1302 |
+
return '<Section: {}>'.format(self._name)
|
| 1303 |
+
|
| 1304 |
+
def __getitem__(self, key):
|
| 1305 |
+
if not self._parser.has_option(self._name, key):
|
| 1306 |
+
raise KeyError(key)
|
| 1307 |
+
return self._parser.get(self._name, key)
|
| 1308 |
+
|
| 1309 |
+
def __setitem__(self, key, value):
|
| 1310 |
+
self._parser._validate_value_types(option=key, value=value)
|
| 1311 |
+
return self._parser.set(self._name, key, value)
|
| 1312 |
+
|
| 1313 |
+
def __delitem__(self, key):
|
| 1314 |
+
if not (self._parser.has_option(self._name, key) and
|
| 1315 |
+
self._parser.remove_option(self._name, key)):
|
| 1316 |
+
raise KeyError(key)
|
| 1317 |
+
|
| 1318 |
+
def __contains__(self, key):
|
| 1319 |
+
return self._parser.has_option(self._name, key)
|
| 1320 |
+
|
| 1321 |
+
def __len__(self):
|
| 1322 |
+
return len(self._options())
|
| 1323 |
+
|
| 1324 |
+
def __iter__(self):
|
| 1325 |
+
return self._options().__iter__()
|
| 1326 |
+
|
| 1327 |
+
def _options(self):
|
| 1328 |
+
if self._name != self._parser.default_section:
|
| 1329 |
+
return self._parser.options(self._name)
|
| 1330 |
+
else:
|
| 1331 |
+
return self._parser.defaults()
|
| 1332 |
+
|
| 1333 |
+
@property
|
| 1334 |
+
def parser(self):
|
| 1335 |
+
# The parser object of the proxy is read-only.
|
| 1336 |
+
return self._parser
|
| 1337 |
+
|
| 1338 |
+
@property
|
| 1339 |
+
def name(self):
|
| 1340 |
+
# The name of the section on a proxy is read-only.
|
| 1341 |
+
return self._name
|
| 1342 |
+
|
| 1343 |
+
def get(self, option, fallback=None, *, raw=False, vars=None,
|
| 1344 |
+
_impl=None, **kwargs):
|
| 1345 |
+
"""Get an option value.
|
| 1346 |
+
|
| 1347 |
+
Unless `fallback` is provided, `None` will be returned if the option
|
| 1348 |
+
is not found.
|
| 1349 |
+
|
| 1350 |
+
"""
|
| 1351 |
+
# If `_impl` is provided, it should be a getter method on the parser
|
| 1352 |
+
# object that provides the desired type conversion.
|
| 1353 |
+
if not _impl:
|
| 1354 |
+
_impl = self._parser.get
|
| 1355 |
+
return _impl(self._name, option, raw=raw, vars=vars,
|
| 1356 |
+
fallback=fallback, **kwargs)
|
| 1357 |
+
|
| 1358 |
+
|
| 1359 |
+
class ConverterMapping(MutableMapping):
|
| 1360 |
+
"""Enables reuse of get*() methods between the parser and section proxies.
|
| 1361 |
+
|
| 1362 |
+
If a parser class implements a getter directly, the value for the given
|
| 1363 |
+
key will be ``None``. The presence of the converter name here enables
|
| 1364 |
+
section proxies to find and use the implementation on the parser class.
|
| 1365 |
+
"""
|
| 1366 |
+
|
| 1367 |
+
GETTERCRE = re.compile(r"^get(?P<name>.+)$")
|
| 1368 |
+
|
| 1369 |
+
def __init__(self, parser):
|
| 1370 |
+
self._parser = parser
|
| 1371 |
+
self._data = {}
|
| 1372 |
+
for getter in dir(self._parser):
|
| 1373 |
+
m = self.GETTERCRE.match(getter)
|
| 1374 |
+
if not m or not callable(getattr(self._parser, getter)):
|
| 1375 |
+
continue
|
| 1376 |
+
self._data[m.group('name')] = None # See class docstring.
|
| 1377 |
+
|
| 1378 |
+
def __getitem__(self, key):
|
| 1379 |
+
return self._data[key]
|
| 1380 |
+
|
| 1381 |
+
def __setitem__(self, key, value):
|
| 1382 |
+
try:
|
| 1383 |
+
k = 'get' + key
|
| 1384 |
+
except TypeError:
|
| 1385 |
+
raise ValueError('Incompatible key: {} (type: {})'
|
| 1386 |
+
''.format(key, type(key)))
|
| 1387 |
+
if k == 'get':
|
| 1388 |
+
raise ValueError('Incompatible key: cannot use "" as a name')
|
| 1389 |
+
self._data[key] = value
|
| 1390 |
+
func = functools.partial(self._parser._get_conv, conv=value)
|
| 1391 |
+
func.converter = value
|
| 1392 |
+
setattr(self._parser, k, func)
|
| 1393 |
+
for proxy in self._parser.values():
|
| 1394 |
+
getter = functools.partial(proxy.get, _impl=func)
|
| 1395 |
+
setattr(proxy, k, getter)
|
| 1396 |
+
|
| 1397 |
+
def __delitem__(self, key):
|
| 1398 |
+
try:
|
| 1399 |
+
k = 'get' + (key or None)
|
| 1400 |
+
except TypeError:
|
| 1401 |
+
raise KeyError(key)
|
| 1402 |
+
del self._data[key]
|
| 1403 |
+
for inst in itertools.chain((self._parser,), self._parser.values()):
|
| 1404 |
+
try:
|
| 1405 |
+
delattr(inst, k)
|
| 1406 |
+
except AttributeError:
|
| 1407 |
+
# don't raise since the entry was present in _data, silently
|
| 1408 |
+
# clean up
|
| 1409 |
+
continue
|
| 1410 |
+
|
| 1411 |
+
def __iter__(self):
|
| 1412 |
+
return iter(self._data)
|
| 1413 |
+
|
| 1414 |
+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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utilities for with-statement contexts. See PEP 343."""
|
| 2 |
+
import abc
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
import _collections_abc
|
| 6 |
+
from collections import deque
|
| 7 |
+
from functools import wraps
|
| 8 |
+
from types import MethodType, GenericAlias
|
| 9 |
+
|
| 10 |
+
__all__ = ["asynccontextmanager", "contextmanager", "closing", "nullcontext",
|
| 11 |
+
"AbstractContextManager", "AbstractAsyncContextManager",
|
| 12 |
+
"AsyncExitStack", "ContextDecorator", "ExitStack",
|
| 13 |
+
"redirect_stdout", "redirect_stderr", "suppress", "aclosing",
|
| 14 |
+
"chdir"]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class AbstractContextManager(abc.ABC):
|
| 18 |
+
|
| 19 |
+
"""An abstract base class for context managers."""
|
| 20 |
+
|
| 21 |
+
__class_getitem__ = classmethod(GenericAlias)
|
| 22 |
+
|
| 23 |
+
__slots__ = ()
|
| 24 |
+
|
| 25 |
+
def __enter__(self):
|
| 26 |
+
"""Return `self` upon entering the runtime context."""
|
| 27 |
+
return self
|
| 28 |
+
|
| 29 |
+
@abc.abstractmethod
|
| 30 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
| 31 |
+
"""Raise any exception triggered within the runtime context."""
|
| 32 |
+
return None
|
| 33 |
+
|
| 34 |
+
@classmethod
|
| 35 |
+
def __subclasshook__(cls, C):
|
| 36 |
+
if cls is AbstractContextManager:
|
| 37 |
+
return _collections_abc._check_methods(C, "__enter__", "__exit__")
|
| 38 |
+
return NotImplemented
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class AbstractAsyncContextManager(abc.ABC):
|
| 42 |
+
|
| 43 |
+
"""An abstract base class for asynchronous context managers."""
|
| 44 |
+
|
| 45 |
+
__class_getitem__ = classmethod(GenericAlias)
|
| 46 |
+
|
| 47 |
+
__slots__ = ()
|
| 48 |
+
|
| 49 |
+
async def __aenter__(self):
|
| 50 |
+
"""Return `self` upon entering the runtime context."""
|
| 51 |
+
return self
|
| 52 |
+
|
| 53 |
+
@abc.abstractmethod
|
| 54 |
+
async def __aexit__(self, exc_type, exc_value, traceback):
|
| 55 |
+
"""Raise any exception triggered within the runtime context."""
|
| 56 |
+
return None
|
| 57 |
+
|
| 58 |
+
@classmethod
|
| 59 |
+
def __subclasshook__(cls, C):
|
| 60 |
+
if cls is AbstractAsyncContextManager:
|
| 61 |
+
return _collections_abc._check_methods(C, "__aenter__",
|
| 62 |
+
"__aexit__")
|
| 63 |
+
return NotImplemented
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class ContextDecorator(object):
|
| 67 |
+
"A base class or mixin that enables context managers to work as decorators."
|
| 68 |
+
|
| 69 |
+
def _recreate_cm(self):
|
| 70 |
+
"""Return a recreated instance of self.
|
| 71 |
+
|
| 72 |
+
Allows an otherwise one-shot context manager like
|
| 73 |
+
_GeneratorContextManager to support use as
|
| 74 |
+
a decorator via implicit recreation.
|
| 75 |
+
|
| 76 |
+
This is a private interface just for _GeneratorContextManager.
|
| 77 |
+
See issue #11647 for details.
|
| 78 |
+
"""
|
| 79 |
+
return self
|
| 80 |
+
|
| 81 |
+
def __call__(self, func):
|
| 82 |
+
@wraps(func)
|
| 83 |
+
def inner(*args, **kwds):
|
| 84 |
+
with self._recreate_cm():
|
| 85 |
+
return func(*args, **kwds)
|
| 86 |
+
return inner
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class AsyncContextDecorator(object):
|
| 90 |
+
"A base class or mixin that enables async context managers to work as decorators."
|
| 91 |
+
|
| 92 |
+
def _recreate_cm(self):
|
| 93 |
+
"""Return a recreated instance of self.
|
| 94 |
+
"""
|
| 95 |
+
return self
|
| 96 |
+
|
| 97 |
+
def __call__(self, func):
|
| 98 |
+
@wraps(func)
|
| 99 |
+
async def inner(*args, **kwds):
|
| 100 |
+
async with self._recreate_cm():
|
| 101 |
+
return await func(*args, **kwds)
|
| 102 |
+
return inner
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class _GeneratorContextManagerBase:
|
| 106 |
+
"""Shared functionality for @contextmanager and @asynccontextmanager."""
|
| 107 |
+
|
| 108 |
+
def __init__(self, func, args, kwds):
|
| 109 |
+
self.gen = func(*args, **kwds)
|
| 110 |
+
self.func, self.args, self.kwds = func, args, kwds
|
| 111 |
+
# Issue 19330: ensure context manager instances have good docstrings
|
| 112 |
+
doc = getattr(func, "__doc__", None)
|
| 113 |
+
if doc is None:
|
| 114 |
+
doc = type(self).__doc__
|
| 115 |
+
self.__doc__ = doc
|
| 116 |
+
# Unfortunately, this still doesn't provide good help output when
|
| 117 |
+
# inspecting the created context manager instances, since pydoc
|
| 118 |
+
# currently bypasses the instance docstring and shows the docstring
|
| 119 |
+
# for the class instead.
|
| 120 |
+
# See http://bugs.python.org/issue19404 for more details.
|
| 121 |
+
|
| 122 |
+
def _recreate_cm(self):
|
| 123 |
+
# _GCMB instances are one-shot context managers, so the
|
| 124 |
+
# CM must be recreated each time a decorated function is
|
| 125 |
+
# called
|
| 126 |
+
return self.__class__(self.func, self.args, self.kwds)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class _GeneratorContextManager(
|
| 130 |
+
_GeneratorContextManagerBase,
|
| 131 |
+
AbstractContextManager,
|
| 132 |
+
ContextDecorator,
|
| 133 |
+
):
|
| 134 |
+
"""Helper for @contextmanager decorator."""
|
| 135 |
+
|
| 136 |
+
def __enter__(self):
|
| 137 |
+
# do not keep args and kwds alive unnecessarily
|
| 138 |
+
# they are only needed for recreation, which is not possible anymore
|
| 139 |
+
del self.args, self.kwds, self.func
|
| 140 |
+
try:
|
| 141 |
+
return next(self.gen)
|
| 142 |
+
except StopIteration:
|
| 143 |
+
raise RuntimeError("generator didn't yield") from None
|
| 144 |
+
|
| 145 |
+
def __exit__(self, typ, value, traceback):
|
| 146 |
+
if typ is None:
|
| 147 |
+
try:
|
| 148 |
+
next(self.gen)
|
| 149 |
+
except StopIteration:
|
| 150 |
+
return False
|
| 151 |
+
else:
|
| 152 |
+
try:
|
| 153 |
+
raise RuntimeError("generator didn't stop")
|
| 154 |
+
finally:
|
| 155 |
+
self.gen.close()
|
| 156 |
+
else:
|
| 157 |
+
if value is None:
|
| 158 |
+
# Need to force instantiation so we can reliably
|
| 159 |
+
# tell if we get the same exception back
|
| 160 |
+
value = typ()
|
| 161 |
+
try:
|
| 162 |
+
self.gen.throw(value)
|
| 163 |
+
except StopIteration as exc:
|
| 164 |
+
# Suppress StopIteration *unless* it's the same exception that
|
| 165 |
+
# was passed to throw(). This prevents a StopIteration
|
| 166 |
+
# raised inside the "with" statement from being suppressed.
|
| 167 |
+
return exc is not value
|
| 168 |
+
except RuntimeError as exc:
|
| 169 |
+
# Don't re-raise the passed in exception. (issue27122)
|
| 170 |
+
if exc is value:
|
| 171 |
+
exc.__traceback__ = traceback
|
| 172 |
+
return False
|
| 173 |
+
# Avoid suppressing if a StopIteration exception
|
| 174 |
+
# was passed to throw() and later wrapped into a RuntimeError
|
| 175 |
+
# (see PEP 479 for sync generators; async generators also
|
| 176 |
+
# have this behavior). But do this only if the exception wrapped
|
| 177 |
+
# by the RuntimeError is actually Stop(Async)Iteration (see
|
| 178 |
+
# issue29692).
|
| 179 |
+
if (
|
| 180 |
+
isinstance(value, StopIteration)
|
| 181 |
+
and exc.__cause__ is value
|
| 182 |
+
):
|
| 183 |
+
value.__traceback__ = traceback
|
| 184 |
+
return False
|
| 185 |
+
raise
|
| 186 |
+
except BaseException as exc:
|
| 187 |
+
# only re-raise if it's *not* the exception that was
|
| 188 |
+
# passed to throw(), because __exit__() must not raise
|
| 189 |
+
# an exception unless __exit__() itself failed. But throw()
|
| 190 |
+
# has to raise the exception to signal propagation, so this
|
| 191 |
+
# fixes the impedance mismatch between the throw() protocol
|
| 192 |
+
# and the __exit__() protocol.
|
| 193 |
+
if exc is not value:
|
| 194 |
+
raise
|
| 195 |
+
exc.__traceback__ = traceback
|
| 196 |
+
return False
|
| 197 |
+
try:
|
| 198 |
+
raise RuntimeError("generator didn't stop after throw()")
|
| 199 |
+
finally:
|
| 200 |
+
self.gen.close()
|
| 201 |
+
|
| 202 |
+
class _AsyncGeneratorContextManager(
|
| 203 |
+
_GeneratorContextManagerBase,
|
| 204 |
+
AbstractAsyncContextManager,
|
| 205 |
+
AsyncContextDecorator,
|
| 206 |
+
):
|
| 207 |
+
"""Helper for @asynccontextmanager decorator."""
|
| 208 |
+
|
| 209 |
+
async def __aenter__(self):
|
| 210 |
+
# do not keep args and kwds alive unnecessarily
|
| 211 |
+
# they are only needed for recreation, which is not possible anymore
|
| 212 |
+
del self.args, self.kwds, self.func
|
| 213 |
+
try:
|
| 214 |
+
return await anext(self.gen)
|
| 215 |
+
except StopAsyncIteration:
|
| 216 |
+
raise RuntimeError("generator didn't yield") from None
|
| 217 |
+
|
| 218 |
+
async def __aexit__(self, typ, value, traceback):
|
| 219 |
+
if typ is None:
|
| 220 |
+
try:
|
| 221 |
+
await anext(self.gen)
|
| 222 |
+
except StopAsyncIteration:
|
| 223 |
+
return False
|
| 224 |
+
else:
|
| 225 |
+
try:
|
| 226 |
+
raise RuntimeError("generator didn't stop")
|
| 227 |
+
finally:
|
| 228 |
+
await self.gen.aclose()
|
| 229 |
+
else:
|
| 230 |
+
if value is None:
|
| 231 |
+
# Need to force instantiation so we can reliably
|
| 232 |
+
# tell if we get the same exception back
|
| 233 |
+
value = typ()
|
| 234 |
+
try:
|
| 235 |
+
await self.gen.athrow(value)
|
| 236 |
+
except StopAsyncIteration as exc:
|
| 237 |
+
# Suppress StopIteration *unless* it's the same exception that
|
| 238 |
+
# was passed to throw(). This prevents a StopIteration
|
| 239 |
+
# raised inside the "with" statement from being suppressed.
|
| 240 |
+
return exc is not value
|
| 241 |
+
except RuntimeError as exc:
|
| 242 |
+
# Don't re-raise the passed in exception. (issue27122)
|
| 243 |
+
if exc is value:
|
| 244 |
+
exc.__traceback__ = traceback
|
| 245 |
+
return False
|
| 246 |
+
# Avoid suppressing if a Stop(Async)Iteration exception
|
| 247 |
+
# was passed to athrow() and later wrapped into a RuntimeError
|
| 248 |
+
# (see PEP 479 for sync generators; async generators also
|
| 249 |
+
# have this behavior). But do this only if the exception wrapped
|
| 250 |
+
# by the RuntimeError is actually Stop(Async)Iteration (see
|
| 251 |
+
# issue29692).
|
| 252 |
+
if (
|
| 253 |
+
isinstance(value, (StopIteration, StopAsyncIteration))
|
| 254 |
+
and exc.__cause__ is value
|
| 255 |
+
):
|
| 256 |
+
value.__traceback__ = traceback
|
| 257 |
+
return False
|
| 258 |
+
raise
|
| 259 |
+
except BaseException as exc:
|
| 260 |
+
# only re-raise if it's *not* the exception that was
|
| 261 |
+
# passed to throw(), because __exit__() must not raise
|
| 262 |
+
# an exception unless __exit__() itself failed. But throw()
|
| 263 |
+
# has to raise the exception to signal propagation, so this
|
| 264 |
+
# fixes the impedance mismatch between the throw() protocol
|
| 265 |
+
# and the __exit__() protocol.
|
| 266 |
+
if exc is not value:
|
| 267 |
+
raise
|
| 268 |
+
exc.__traceback__ = traceback
|
| 269 |
+
return False
|
| 270 |
+
try:
|
| 271 |
+
raise RuntimeError("generator didn't stop after athrow()")
|
| 272 |
+
finally:
|
| 273 |
+
await self.gen.aclose()
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def contextmanager(func):
|
| 277 |
+
"""@contextmanager decorator.
|
| 278 |
+
|
| 279 |
+
Typical usage:
|
| 280 |
+
|
| 281 |
+
@contextmanager
|
| 282 |
+
def some_generator(<arguments>):
|
| 283 |
+
<setup>
|
| 284 |
+
try:
|
| 285 |
+
yield <value>
|
| 286 |
+
finally:
|
| 287 |
+
<cleanup>
|
| 288 |
+
|
| 289 |
+
This makes this:
|
| 290 |
+
|
| 291 |
+
with some_generator(<arguments>) as <variable>:
|
| 292 |
+
<body>
|
| 293 |
+
|
| 294 |
+
equivalent to this:
|
| 295 |
+
|
| 296 |
+
<setup>
|
| 297 |
+
try:
|
| 298 |
+
<variable> = <value>
|
| 299 |
+
<body>
|
| 300 |
+
finally:
|
| 301 |
+
<cleanup>
|
| 302 |
+
"""
|
| 303 |
+
@wraps(func)
|
| 304 |
+
def helper(*args, **kwds):
|
| 305 |
+
return _GeneratorContextManager(func, args, kwds)
|
| 306 |
+
return helper
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def asynccontextmanager(func):
|
| 310 |
+
"""@asynccontextmanager decorator.
|
| 311 |
+
|
| 312 |
+
Typical usage:
|
| 313 |
+
|
| 314 |
+
@asynccontextmanager
|
| 315 |
+
async def some_async_generator(<arguments>):
|
| 316 |
+
<setup>
|
| 317 |
+
try:
|
| 318 |
+
yield <value>
|
| 319 |
+
finally:
|
| 320 |
+
<cleanup>
|
| 321 |
+
|
| 322 |
+
This makes this:
|
| 323 |
+
|
| 324 |
+
async with some_async_generator(<arguments>) as <variable>:
|
| 325 |
+
<body>
|
| 326 |
+
|
| 327 |
+
equivalent to this:
|
| 328 |
+
|
| 329 |
+
<setup>
|
| 330 |
+
try:
|
| 331 |
+
<variable> = <value>
|
| 332 |
+
<body>
|
| 333 |
+
finally:
|
| 334 |
+
<cleanup>
|
| 335 |
+
"""
|
| 336 |
+
@wraps(func)
|
| 337 |
+
def helper(*args, **kwds):
|
| 338 |
+
return _AsyncGeneratorContextManager(func, args, kwds)
|
| 339 |
+
return helper
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
class closing(AbstractContextManager):
|
| 343 |
+
"""Context to automatically close something at the end of a block.
|
| 344 |
+
|
| 345 |
+
Code like this:
|
| 346 |
+
|
| 347 |
+
with closing(<module>.open(<arguments>)) as f:
|
| 348 |
+
<block>
|
| 349 |
+
|
| 350 |
+
is equivalent to this:
|
| 351 |
+
|
| 352 |
+
f = <module>.open(<arguments>)
|
| 353 |
+
try:
|
| 354 |
+
<block>
|
| 355 |
+
finally:
|
| 356 |
+
f.close()
|
| 357 |
+
|
| 358 |
+
"""
|
| 359 |
+
def __init__(self, thing):
|
| 360 |
+
self.thing = thing
|
| 361 |
+
def __enter__(self):
|
| 362 |
+
return self.thing
|
| 363 |
+
def __exit__(self, *exc_info):
|
| 364 |
+
self.thing.close()
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
class aclosing(AbstractAsyncContextManager):
|
| 368 |
+
"""Async context manager for safely finalizing an asynchronously cleaned-up
|
| 369 |
+
resource such as an async generator, calling its ``aclose()`` method.
|
| 370 |
+
|
| 371 |
+
Code like this:
|
| 372 |
+
|
| 373 |
+
async with aclosing(<module>.fetch(<arguments>)) as agen:
|
| 374 |
+
<block>
|
| 375 |
+
|
| 376 |
+
is equivalent to this:
|
| 377 |
+
|
| 378 |
+
agen = <module>.fetch(<arguments>)
|
| 379 |
+
try:
|
| 380 |
+
<block>
|
| 381 |
+
finally:
|
| 382 |
+
await agen.aclose()
|
| 383 |
+
|
| 384 |
+
"""
|
| 385 |
+
def __init__(self, thing):
|
| 386 |
+
self.thing = thing
|
| 387 |
+
async def __aenter__(self):
|
| 388 |
+
return self.thing
|
| 389 |
+
async def __aexit__(self, *exc_info):
|
| 390 |
+
await self.thing.aclose()
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
class _RedirectStream(AbstractContextManager):
|
| 394 |
+
|
| 395 |
+
_stream = None
|
| 396 |
+
|
| 397 |
+
def __init__(self, new_target):
|
| 398 |
+
self._new_target = new_target
|
| 399 |
+
# We use a list of old targets to make this CM re-entrant
|
| 400 |
+
self._old_targets = []
|
| 401 |
+
|
| 402 |
+
def __enter__(self):
|
| 403 |
+
self._old_targets.append(getattr(sys, self._stream))
|
| 404 |
+
setattr(sys, self._stream, self._new_target)
|
| 405 |
+
return self._new_target
|
| 406 |
+
|
| 407 |
+
def __exit__(self, exctype, excinst, exctb):
|
| 408 |
+
setattr(sys, self._stream, self._old_targets.pop())
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
class redirect_stdout(_RedirectStream):
|
| 412 |
+
"""Context manager for temporarily redirecting stdout to another file.
|
| 413 |
+
|
| 414 |
+
# How to send help() to stderr
|
| 415 |
+
with redirect_stdout(sys.stderr):
|
| 416 |
+
help(dir)
|
| 417 |
+
|
| 418 |
+
# How to write help() to a file
|
| 419 |
+
with open('help.txt', 'w') as f:
|
| 420 |
+
with redirect_stdout(f):
|
| 421 |
+
help(pow)
|
| 422 |
+
"""
|
| 423 |
+
|
| 424 |
+
_stream = "stdout"
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
class redirect_stderr(_RedirectStream):
|
| 428 |
+
"""Context manager for temporarily redirecting stderr to another file."""
|
| 429 |
+
|
| 430 |
+
_stream = "stderr"
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
class suppress(AbstractContextManager):
|
| 434 |
+
"""Context manager to suppress specified exceptions
|
| 435 |
+
|
| 436 |
+
After the exception is suppressed, execution proceeds with the next
|
| 437 |
+
statement following the with statement.
|
| 438 |
+
|
| 439 |
+
with suppress(FileNotFoundError):
|
| 440 |
+
os.remove(somefile)
|
| 441 |
+
# Execution still resumes here if the file was already removed
|
| 442 |
+
"""
|
| 443 |
+
|
| 444 |
+
def __init__(self, *exceptions):
|
| 445 |
+
self._exceptions = exceptions
|
| 446 |
+
|
| 447 |
+
def __enter__(self):
|
| 448 |
+
pass
|
| 449 |
+
|
| 450 |
+
def __exit__(self, exctype, excinst, exctb):
|
| 451 |
+
# Unlike isinstance and issubclass, CPython exception handling
|
| 452 |
+
# currently only looks at the concrete type hierarchy (ignoring
|
| 453 |
+
# the instance and subclass checking hooks). While Guido considers
|
| 454 |
+
# that a bug rather than a feature, it's a fairly hard one to fix
|
| 455 |
+
# due to various internal implementation details. suppress provides
|
| 456 |
+
# the simpler issubclass based semantics, rather than trying to
|
| 457 |
+
# exactly reproduce the limitations of the CPython interpreter.
|
| 458 |
+
#
|
| 459 |
+
# See http://bugs.python.org/issue12029 for more details
|
| 460 |
+
if exctype is None:
|
| 461 |
+
return
|
| 462 |
+
if issubclass(exctype, self._exceptions):
|
| 463 |
+
return True
|
| 464 |
+
if issubclass(exctype, BaseExceptionGroup):
|
| 465 |
+
match, rest = excinst.split(self._exceptions)
|
| 466 |
+
if rest is None:
|
| 467 |
+
return True
|
| 468 |
+
raise rest
|
| 469 |
+
return False
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
class _BaseExitStack:
|
| 473 |
+
"""A base class for ExitStack and AsyncExitStack."""
|
| 474 |
+
|
| 475 |
+
@staticmethod
|
| 476 |
+
def _create_exit_wrapper(cm, cm_exit):
|
| 477 |
+
return MethodType(cm_exit, cm)
|
| 478 |
+
|
| 479 |
+
@staticmethod
|
| 480 |
+
def _create_cb_wrapper(callback, /, *args, **kwds):
|
| 481 |
+
def _exit_wrapper(exc_type, exc, tb):
|
| 482 |
+
callback(*args, **kwds)
|
| 483 |
+
return _exit_wrapper
|
| 484 |
+
|
| 485 |
+
def __init__(self):
|
| 486 |
+
self._exit_callbacks = deque()
|
| 487 |
+
|
| 488 |
+
def pop_all(self):
|
| 489 |
+
"""Preserve the context stack by transferring it to a new instance."""
|
| 490 |
+
new_stack = type(self)()
|
| 491 |
+
new_stack._exit_callbacks = self._exit_callbacks
|
| 492 |
+
self._exit_callbacks = deque()
|
| 493 |
+
return new_stack
|
| 494 |
+
|
| 495 |
+
def push(self, exit):
|
| 496 |
+
"""Registers a callback with the standard __exit__ method signature.
|
| 497 |
+
|
| 498 |
+
Can suppress exceptions the same way __exit__ method can.
|
| 499 |
+
Also accepts any object with an __exit__ method (registering a call
|
| 500 |
+
to the method instead of the object itself).
|
| 501 |
+
"""
|
| 502 |
+
# We use an unbound method rather than a bound method to follow
|
| 503 |
+
# the standard lookup behaviour for special methods.
|
| 504 |
+
_cb_type = type(exit)
|
| 505 |
+
|
| 506 |
+
try:
|
| 507 |
+
exit_method = _cb_type.__exit__
|
| 508 |
+
except AttributeError:
|
| 509 |
+
# Not a context manager, so assume it's a callable.
|
| 510 |
+
self._push_exit_callback(exit)
|
| 511 |
+
else:
|
| 512 |
+
self._push_cm_exit(exit, exit_method)
|
| 513 |
+
return exit # Allow use as a decorator.
|
| 514 |
+
|
| 515 |
+
def enter_context(self, cm):
|
| 516 |
+
"""Enters the supplied context manager.
|
| 517 |
+
|
| 518 |
+
If successful, also pushes its __exit__ method as a callback and
|
| 519 |
+
returns the result of the __enter__ method.
|
| 520 |
+
"""
|
| 521 |
+
# We look up the special methods on the type to match the with
|
| 522 |
+
# statement.
|
| 523 |
+
cls = type(cm)
|
| 524 |
+
try:
|
| 525 |
+
_enter = cls.__enter__
|
| 526 |
+
_exit = cls.__exit__
|
| 527 |
+
except AttributeError:
|
| 528 |
+
raise TypeError(f"'{cls.__module__}.{cls.__qualname__}' object does "
|
| 529 |
+
f"not support the context manager protocol") from None
|
| 530 |
+
result = _enter(cm)
|
| 531 |
+
self._push_cm_exit(cm, _exit)
|
| 532 |
+
return result
|
| 533 |
+
|
| 534 |
+
def callback(self, callback, /, *args, **kwds):
|
| 535 |
+
"""Registers an arbitrary callback and arguments.
|
| 536 |
+
|
| 537 |
+
Cannot suppress exceptions.
|
| 538 |
+
"""
|
| 539 |
+
_exit_wrapper = self._create_cb_wrapper(callback, *args, **kwds)
|
| 540 |
+
|
| 541 |
+
# We changed the signature, so using @wraps is not appropriate, but
|
| 542 |
+
# setting __wrapped__ may still help with introspection.
|
| 543 |
+
_exit_wrapper.__wrapped__ = callback
|
| 544 |
+
self._push_exit_callback(_exit_wrapper)
|
| 545 |
+
return callback # Allow use as a decorator
|
| 546 |
+
|
| 547 |
+
def _push_cm_exit(self, cm, cm_exit):
|
| 548 |
+
"""Helper to correctly register callbacks to __exit__ methods."""
|
| 549 |
+
_exit_wrapper = self._create_exit_wrapper(cm, cm_exit)
|
| 550 |
+
self._push_exit_callback(_exit_wrapper, True)
|
| 551 |
+
|
| 552 |
+
def _push_exit_callback(self, callback, is_sync=True):
|
| 553 |
+
self._exit_callbacks.append((is_sync, callback))
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
# Inspired by discussions on http://bugs.python.org/issue13585
|
| 557 |
+
class ExitStack(_BaseExitStack, AbstractContextManager):
|
| 558 |
+
"""Context manager for dynamic management of a stack of exit callbacks.
|
| 559 |
+
|
| 560 |
+
For example:
|
| 561 |
+
with ExitStack() as stack:
|
| 562 |
+
files = [stack.enter_context(open(fname)) for fname in filenames]
|
| 563 |
+
# All opened files will automatically be closed at the end of
|
| 564 |
+
# the with statement, even if attempts to open files later
|
| 565 |
+
# in the list raise an exception.
|
| 566 |
+
"""
|
| 567 |
+
|
| 568 |
+
def __enter__(self):
|
| 569 |
+
return self
|
| 570 |
+
|
| 571 |
+
def __exit__(self, *exc_details):
|
| 572 |
+
exc = exc_details[1]
|
| 573 |
+
received_exc = exc is not None
|
| 574 |
+
|
| 575 |
+
# We manipulate the exception state so it behaves as though
|
| 576 |
+
# we were actually nesting multiple with statements
|
| 577 |
+
frame_exc = sys.exception()
|
| 578 |
+
def _fix_exception_context(new_exc, old_exc):
|
| 579 |
+
# Context may not be correct, so find the end of the chain
|
| 580 |
+
while 1:
|
| 581 |
+
exc_context = new_exc.__context__
|
| 582 |
+
if exc_context is None or exc_context is old_exc:
|
| 583 |
+
# Context is already set correctly (see issue 20317)
|
| 584 |
+
return
|
| 585 |
+
if exc_context is frame_exc:
|
| 586 |
+
break
|
| 587 |
+
new_exc = exc_context
|
| 588 |
+
# Change the end of the chain to point to the exception
|
| 589 |
+
# we expect it to reference
|
| 590 |
+
new_exc.__context__ = old_exc
|
| 591 |
+
|
| 592 |
+
# Callbacks are invoked in LIFO order to match the behaviour of
|
| 593 |
+
# nested context managers
|
| 594 |
+
suppressed_exc = False
|
| 595 |
+
pending_raise = False
|
| 596 |
+
while self._exit_callbacks:
|
| 597 |
+
is_sync, cb = self._exit_callbacks.pop()
|
| 598 |
+
assert is_sync
|
| 599 |
+
try:
|
| 600 |
+
if exc is None:
|
| 601 |
+
exc_details = None, None, None
|
| 602 |
+
else:
|
| 603 |
+
exc_details = type(exc), exc, exc.__traceback__
|
| 604 |
+
if cb(*exc_details):
|
| 605 |
+
suppressed_exc = True
|
| 606 |
+
pending_raise = False
|
| 607 |
+
exc = None
|
| 608 |
+
except BaseException as new_exc:
|
| 609 |
+
# simulate the stack of exceptions by setting the context
|
| 610 |
+
_fix_exception_context(new_exc, exc)
|
| 611 |
+
pending_raise = True
|
| 612 |
+
exc = new_exc
|
| 613 |
+
|
| 614 |
+
if pending_raise:
|
| 615 |
+
try:
|
| 616 |
+
# bare "raise exc" replaces our carefully
|
| 617 |
+
# set-up context
|
| 618 |
+
fixed_ctx = exc.__context__
|
| 619 |
+
raise exc
|
| 620 |
+
except BaseException:
|
| 621 |
+
exc.__context__ = fixed_ctx
|
| 622 |
+
raise
|
| 623 |
+
return received_exc and suppressed_exc
|
| 624 |
+
|
| 625 |
+
def close(self):
|
| 626 |
+
"""Immediately unwind the context stack."""
|
| 627 |
+
self.__exit__(None, None, None)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
# Inspired by discussions on https://bugs.python.org/issue29302
|
| 631 |
+
class AsyncExitStack(_BaseExitStack, AbstractAsyncContextManager):
|
| 632 |
+
"""Async context manager for dynamic management of a stack of exit
|
| 633 |
+
callbacks.
|
| 634 |
+
|
| 635 |
+
For example:
|
| 636 |
+
async with AsyncExitStack() as stack:
|
| 637 |
+
connections = [await stack.enter_async_context(get_connection())
|
| 638 |
+
for i in range(5)]
|
| 639 |
+
# All opened connections will automatically be released at the
|
| 640 |
+
# end of the async with statement, even if attempts to open a
|
| 641 |
+
# connection later in the list raise an exception.
|
| 642 |
+
"""
|
| 643 |
+
|
| 644 |
+
@staticmethod
|
| 645 |
+
def _create_async_exit_wrapper(cm, cm_exit):
|
| 646 |
+
return MethodType(cm_exit, cm)
|
| 647 |
+
|
| 648 |
+
@staticmethod
|
| 649 |
+
def _create_async_cb_wrapper(callback, /, *args, **kwds):
|
| 650 |
+
async def _exit_wrapper(exc_type, exc, tb):
|
| 651 |
+
await callback(*args, **kwds)
|
| 652 |
+
return _exit_wrapper
|
| 653 |
+
|
| 654 |
+
async def enter_async_context(self, cm):
|
| 655 |
+
"""Enters the supplied async context manager.
|
| 656 |
+
|
| 657 |
+
If successful, also pushes its __aexit__ method as a callback and
|
| 658 |
+
returns the result of the __aenter__ method.
|
| 659 |
+
"""
|
| 660 |
+
cls = type(cm)
|
| 661 |
+
try:
|
| 662 |
+
_enter = cls.__aenter__
|
| 663 |
+
_exit = cls.__aexit__
|
| 664 |
+
except AttributeError:
|
| 665 |
+
raise TypeError(f"'{cls.__module__}.{cls.__qualname__}' object does "
|
| 666 |
+
f"not support the asynchronous context manager protocol"
|
| 667 |
+
) from None
|
| 668 |
+
result = await _enter(cm)
|
| 669 |
+
self._push_async_cm_exit(cm, _exit)
|
| 670 |
+
return result
|
| 671 |
+
|
| 672 |
+
def push_async_exit(self, exit):
|
| 673 |
+
"""Registers a coroutine function with the standard __aexit__ method
|
| 674 |
+
signature.
|
| 675 |
+
|
| 676 |
+
Can suppress exceptions the same way __aexit__ method can.
|
| 677 |
+
Also accepts any object with an __aexit__ method (registering a call
|
| 678 |
+
to the method instead of the object itself).
|
| 679 |
+
"""
|
| 680 |
+
_cb_type = type(exit)
|
| 681 |
+
try:
|
| 682 |
+
exit_method = _cb_type.__aexit__
|
| 683 |
+
except AttributeError:
|
| 684 |
+
# Not an async context manager, so assume it's a coroutine function
|
| 685 |
+
self._push_exit_callback(exit, False)
|
| 686 |
+
else:
|
| 687 |
+
self._push_async_cm_exit(exit, exit_method)
|
| 688 |
+
return exit # Allow use as a decorator
|
| 689 |
+
|
| 690 |
+
def push_async_callback(self, callback, /, *args, **kwds):
|
| 691 |
+
"""Registers an arbitrary coroutine function and arguments.
|
| 692 |
+
|
| 693 |
+
Cannot suppress exceptions.
|
| 694 |
+
"""
|
| 695 |
+
_exit_wrapper = self._create_async_cb_wrapper(callback, *args, **kwds)
|
| 696 |
+
|
| 697 |
+
# We changed the signature, so using @wraps is not appropriate, but
|
| 698 |
+
# setting __wrapped__ may still help with introspection.
|
| 699 |
+
_exit_wrapper.__wrapped__ = callback
|
| 700 |
+
self._push_exit_callback(_exit_wrapper, False)
|
| 701 |
+
return callback # Allow use as a decorator
|
| 702 |
+
|
| 703 |
+
async def aclose(self):
|
| 704 |
+
"""Immediately unwind the context stack."""
|
| 705 |
+
await self.__aexit__(None, None, None)
|
| 706 |
+
|
| 707 |
+
def _push_async_cm_exit(self, cm, cm_exit):
|
| 708 |
+
"""Helper to correctly register coroutine function to __aexit__
|
| 709 |
+
method."""
|
| 710 |
+
_exit_wrapper = self._create_async_exit_wrapper(cm, cm_exit)
|
| 711 |
+
self._push_exit_callback(_exit_wrapper, False)
|
| 712 |
+
|
| 713 |
+
async def __aenter__(self):
|
| 714 |
+
return self
|
| 715 |
+
|
| 716 |
+
async def __aexit__(self, *exc_details):
|
| 717 |
+
exc = exc_details[1]
|
| 718 |
+
received_exc = exc is not None
|
| 719 |
+
|
| 720 |
+
# We manipulate the exception state so it behaves as though
|
| 721 |
+
# we were actually nesting multiple with statements
|
| 722 |
+
frame_exc = sys.exception()
|
| 723 |
+
def _fix_exception_context(new_exc, old_exc):
|
| 724 |
+
# Context may not be correct, so find the end of the chain
|
| 725 |
+
while 1:
|
| 726 |
+
exc_context = new_exc.__context__
|
| 727 |
+
if exc_context is None or exc_context is old_exc:
|
| 728 |
+
# Context is already set correctly (see issue 20317)
|
| 729 |
+
return
|
| 730 |
+
if exc_context is frame_exc:
|
| 731 |
+
break
|
| 732 |
+
new_exc = exc_context
|
| 733 |
+
# Change the end of the chain to point to the exception
|
| 734 |
+
# we expect it to reference
|
| 735 |
+
new_exc.__context__ = old_exc
|
| 736 |
+
|
| 737 |
+
# Callbacks are invoked in LIFO order to match the behaviour of
|
| 738 |
+
# nested context managers
|
| 739 |
+
suppressed_exc = False
|
| 740 |
+
pending_raise = False
|
| 741 |
+
while self._exit_callbacks:
|
| 742 |
+
is_sync, cb = self._exit_callbacks.pop()
|
| 743 |
+
try:
|
| 744 |
+
if exc is None:
|
| 745 |
+
exc_details = None, None, None
|
| 746 |
+
else:
|
| 747 |
+
exc_details = type(exc), exc, exc.__traceback__
|
| 748 |
+
if is_sync:
|
| 749 |
+
cb_suppress = cb(*exc_details)
|
| 750 |
+
else:
|
| 751 |
+
cb_suppress = await cb(*exc_details)
|
| 752 |
+
|
| 753 |
+
if cb_suppress:
|
| 754 |
+
suppressed_exc = True
|
| 755 |
+
pending_raise = False
|
| 756 |
+
exc = None
|
| 757 |
+
except BaseException as new_exc:
|
| 758 |
+
# simulate the stack of exceptions by setting the context
|
| 759 |
+
_fix_exception_context(new_exc, exc)
|
| 760 |
+
pending_raise = True
|
| 761 |
+
exc = new_exc
|
| 762 |
+
|
| 763 |
+
if pending_raise:
|
| 764 |
+
try:
|
| 765 |
+
# bare "raise exc" replaces our carefully
|
| 766 |
+
# set-up context
|
| 767 |
+
fixed_ctx = exc.__context__
|
| 768 |
+
raise exc
|
| 769 |
+
except BaseException:
|
| 770 |
+
exc.__context__ = fixed_ctx
|
| 771 |
+
raise
|
| 772 |
+
return received_exc and suppressed_exc
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
class nullcontext(AbstractContextManager, AbstractAsyncContextManager):
|
| 776 |
+
"""Context manager that does no additional processing.
|
| 777 |
+
|
| 778 |
+
Used as a stand-in for a normal context manager, when a particular
|
| 779 |
+
block of code is only sometimes used with a normal context manager:
|
| 780 |
+
|
| 781 |
+
cm = optional_cm if condition else nullcontext()
|
| 782 |
+
with cm:
|
| 783 |
+
# Perform operation, using optional_cm if condition is True
|
| 784 |
+
"""
|
| 785 |
+
|
| 786 |
+
def __init__(self, enter_result=None):
|
| 787 |
+
self.enter_result = enter_result
|
| 788 |
+
|
| 789 |
+
def __enter__(self):
|
| 790 |
+
return self.enter_result
|
| 791 |
+
|
| 792 |
+
def __exit__(self, *excinfo):
|
| 793 |
+
pass
|
| 794 |
+
|
| 795 |
+
async def __aenter__(self):
|
| 796 |
+
return self.enter_result
|
| 797 |
+
|
| 798 |
+
async def __aexit__(self, *excinfo):
|
| 799 |
+
pass
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
class chdir(AbstractContextManager):
|
| 803 |
+
"""Non thread-safe context manager to change the current working directory."""
|
| 804 |
+
|
| 805 |
+
def __init__(self, path):
|
| 806 |
+
self.path = path
|
| 807 |
+
self._old_cwd = []
|
| 808 |
+
|
| 809 |
+
def __enter__(self):
|
| 810 |
+
self._old_cwd.append(os.getcwd())
|
| 811 |
+
os.chdir(self.path)
|
| 812 |
+
|
| 813 |
+
def __exit__(self, *excinfo):
|
| 814 |
+
os.chdir(self._old_cwd.pop())
|
micromamba_root/envs/hf_sync/Lib/contextvars.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import _collections_abc
|
| 2 |
+
from _contextvars import Context, ContextVar, Token, copy_context
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
__all__ = ('Context', 'ContextVar', 'Token', 'copy_context')
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
_collections_abc.Mapping.register(Context)
|
micromamba_root/envs/hf_sync/Lib/copy.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generic (shallow and deep) copying operations.
|
| 2 |
+
|
| 3 |
+
Interface summary:
|
| 4 |
+
|
| 5 |
+
import copy
|
| 6 |
+
|
| 7 |
+
x = copy.copy(y) # make a shallow copy of y
|
| 8 |
+
x = copy.deepcopy(y) # make a deep copy of y
|
| 9 |
+
x = copy.replace(y, a=1, b=2) # new object with fields replaced, as defined by `__replace__`
|
| 10 |
+
|
| 11 |
+
For module specific errors, copy.Error is raised.
|
| 12 |
+
|
| 13 |
+
The difference between shallow and deep copying is only relevant for
|
| 14 |
+
compound objects (objects that contain other objects, like lists or
|
| 15 |
+
class instances).
|
| 16 |
+
|
| 17 |
+
- A shallow copy constructs a new compound object and then (to the
|
| 18 |
+
extent possible) inserts *the same objects* into it that the
|
| 19 |
+
original contains.
|
| 20 |
+
|
| 21 |
+
- A deep copy constructs a new compound object and then, recursively,
|
| 22 |
+
inserts *copies* into it of the objects found in the original.
|
| 23 |
+
|
| 24 |
+
Two problems often exist with deep copy operations that don't exist
|
| 25 |
+
with shallow copy operations:
|
| 26 |
+
|
| 27 |
+
a) recursive objects (compound objects that, directly or indirectly,
|
| 28 |
+
contain a reference to themselves) may cause a recursive loop
|
| 29 |
+
|
| 30 |
+
b) because deep copy copies *everything* it may copy too much, e.g.
|
| 31 |
+
administrative data structures that should be shared even between
|
| 32 |
+
copies
|
| 33 |
+
|
| 34 |
+
Python's deep copy operation avoids these problems by:
|
| 35 |
+
|
| 36 |
+
a) keeping a table of objects already copied during the current
|
| 37 |
+
copying pass
|
| 38 |
+
|
| 39 |
+
b) letting user-defined classes override the copying operation or the
|
| 40 |
+
set of components copied
|
| 41 |
+
|
| 42 |
+
This version does not copy types like module, class, function, method,
|
| 43 |
+
nor stack trace, stack frame, nor file, socket, window, nor any
|
| 44 |
+
similar types.
|
| 45 |
+
|
| 46 |
+
Classes can use the same interfaces to control copying that they use
|
| 47 |
+
to control pickling: they can define methods called __getinitargs__(),
|
| 48 |
+
__getstate__() and __setstate__(). See the documentation for module
|
| 49 |
+
"pickle" for information on these methods.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
import types
|
| 53 |
+
import weakref
|
| 54 |
+
from copyreg import dispatch_table
|
| 55 |
+
|
| 56 |
+
class Error(Exception):
|
| 57 |
+
pass
|
| 58 |
+
error = Error # backward compatibility
|
| 59 |
+
|
| 60 |
+
__all__ = ["Error", "copy", "deepcopy", "replace"]
|
| 61 |
+
|
| 62 |
+
def copy(x):
|
| 63 |
+
"""Shallow copy operation on arbitrary Python objects.
|
| 64 |
+
|
| 65 |
+
See the module's __doc__ string for more info.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
cls = type(x)
|
| 69 |
+
|
| 70 |
+
if cls in _copy_atomic_types:
|
| 71 |
+
return x
|
| 72 |
+
if cls in _copy_builtin_containers:
|
| 73 |
+
return cls.copy(x)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
if issubclass(cls, type):
|
| 77 |
+
# treat it as a regular class:
|
| 78 |
+
return x
|
| 79 |
+
|
| 80 |
+
copier = getattr(cls, "__copy__", None)
|
| 81 |
+
if copier is not None:
|
| 82 |
+
return copier(x)
|
| 83 |
+
|
| 84 |
+
reductor = dispatch_table.get(cls)
|
| 85 |
+
if reductor is not None:
|
| 86 |
+
rv = reductor(x)
|
| 87 |
+
else:
|
| 88 |
+
reductor = getattr(x, "__reduce_ex__", None)
|
| 89 |
+
if reductor is not None:
|
| 90 |
+
rv = reductor(4)
|
| 91 |
+
else:
|
| 92 |
+
reductor = getattr(x, "__reduce__", None)
|
| 93 |
+
if reductor:
|
| 94 |
+
rv = reductor()
|
| 95 |
+
else:
|
| 96 |
+
raise Error("un(shallow)copyable object of type %s" % cls)
|
| 97 |
+
|
| 98 |
+
if isinstance(rv, str):
|
| 99 |
+
return x
|
| 100 |
+
return _reconstruct(x, None, *rv)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
_copy_atomic_types = {types.NoneType, int, float, bool, complex, str, tuple,
|
| 104 |
+
bytes, frozenset, type, range, slice, property,
|
| 105 |
+
types.BuiltinFunctionType, types.EllipsisType,
|
| 106 |
+
types.NotImplementedType, types.FunctionType, types.CodeType,
|
| 107 |
+
weakref.ref, super}
|
| 108 |
+
_copy_builtin_containers = {list, dict, set, bytearray}
|
| 109 |
+
|
| 110 |
+
def deepcopy(x, memo=None, _nil=[]):
|
| 111 |
+
"""Deep copy operation on arbitrary Python objects.
|
| 112 |
+
|
| 113 |
+
See the module's __doc__ string for more info.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
cls = type(x)
|
| 117 |
+
|
| 118 |
+
if cls in _atomic_types:
|
| 119 |
+
return x
|
| 120 |
+
|
| 121 |
+
d = id(x)
|
| 122 |
+
if memo is None:
|
| 123 |
+
memo = {}
|
| 124 |
+
else:
|
| 125 |
+
y = memo.get(d, _nil)
|
| 126 |
+
if y is not _nil:
|
| 127 |
+
return y
|
| 128 |
+
|
| 129 |
+
copier = _deepcopy_dispatch.get(cls)
|
| 130 |
+
if copier is not None:
|
| 131 |
+
y = copier(x, memo)
|
| 132 |
+
else:
|
| 133 |
+
if issubclass(cls, type):
|
| 134 |
+
y = x # atomic copy
|
| 135 |
+
else:
|
| 136 |
+
copier = getattr(x, "__deepcopy__", None)
|
| 137 |
+
if copier is not None:
|
| 138 |
+
y = copier(memo)
|
| 139 |
+
else:
|
| 140 |
+
reductor = dispatch_table.get(cls)
|
| 141 |
+
if reductor:
|
| 142 |
+
rv = reductor(x)
|
| 143 |
+
else:
|
| 144 |
+
reductor = getattr(x, "__reduce_ex__", None)
|
| 145 |
+
if reductor is not None:
|
| 146 |
+
rv = reductor(4)
|
| 147 |
+
else:
|
| 148 |
+
reductor = getattr(x, "__reduce__", None)
|
| 149 |
+
if reductor:
|
| 150 |
+
rv = reductor()
|
| 151 |
+
else:
|
| 152 |
+
raise Error(
|
| 153 |
+
"un(deep)copyable object of type %s" % cls)
|
| 154 |
+
if isinstance(rv, str):
|
| 155 |
+
y = x
|
| 156 |
+
else:
|
| 157 |
+
y = _reconstruct(x, memo, *rv)
|
| 158 |
+
|
| 159 |
+
# If is its own copy, don't memoize.
|
| 160 |
+
if y is not x:
|
| 161 |
+
memo[d] = y
|
| 162 |
+
_keep_alive(x, memo) # Make sure x lives at least as long as d
|
| 163 |
+
return y
|
| 164 |
+
|
| 165 |
+
_atomic_types = {types.NoneType, types.EllipsisType, types.NotImplementedType,
|
| 166 |
+
int, float, bool, complex, bytes, str, types.CodeType, type, range,
|
| 167 |
+
types.BuiltinFunctionType, types.FunctionType, weakref.ref, property}
|
| 168 |
+
|
| 169 |
+
_deepcopy_dispatch = d = {}
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _deepcopy_list(x, memo, deepcopy=deepcopy):
|
| 173 |
+
y = []
|
| 174 |
+
memo[id(x)] = y
|
| 175 |
+
append = y.append
|
| 176 |
+
for a in x:
|
| 177 |
+
append(deepcopy(a, memo))
|
| 178 |
+
return y
|
| 179 |
+
d[list] = _deepcopy_list
|
| 180 |
+
|
| 181 |
+
def _deepcopy_tuple(x, memo, deepcopy=deepcopy):
|
| 182 |
+
y = [deepcopy(a, memo) for a in x]
|
| 183 |
+
# We're not going to put the tuple in the memo, but it's still important we
|
| 184 |
+
# check for it, in case the tuple contains recursive mutable structures.
|
| 185 |
+
try:
|
| 186 |
+
return memo[id(x)]
|
| 187 |
+
except KeyError:
|
| 188 |
+
pass
|
| 189 |
+
for k, j in zip(x, y):
|
| 190 |
+
if k is not j:
|
| 191 |
+
y = tuple(y)
|
| 192 |
+
break
|
| 193 |
+
else:
|
| 194 |
+
y = x
|
| 195 |
+
return y
|
| 196 |
+
d[tuple] = _deepcopy_tuple
|
| 197 |
+
|
| 198 |
+
def _deepcopy_dict(x, memo, deepcopy=deepcopy):
|
| 199 |
+
y = {}
|
| 200 |
+
memo[id(x)] = y
|
| 201 |
+
for key, value in x.items():
|
| 202 |
+
y[deepcopy(key, memo)] = deepcopy(value, memo)
|
| 203 |
+
return y
|
| 204 |
+
d[dict] = _deepcopy_dict
|
| 205 |
+
|
| 206 |
+
def _deepcopy_method(x, memo): # Copy instance methods
|
| 207 |
+
return type(x)(x.__func__, deepcopy(x.__self__, memo))
|
| 208 |
+
d[types.MethodType] = _deepcopy_method
|
| 209 |
+
|
| 210 |
+
del d
|
| 211 |
+
|
| 212 |
+
def _keep_alive(x, memo):
|
| 213 |
+
"""Keeps a reference to the object x in the memo.
|
| 214 |
+
|
| 215 |
+
Because we remember objects by their id, we have
|
| 216 |
+
to assure that possibly temporary objects are kept
|
| 217 |
+
alive by referencing them.
|
| 218 |
+
We store a reference at the id of the memo, which should
|
| 219 |
+
normally not be used unless someone tries to deepcopy
|
| 220 |
+
the memo itself...
|
| 221 |
+
"""
|
| 222 |
+
try:
|
| 223 |
+
memo[id(memo)].append(x)
|
| 224 |
+
except KeyError:
|
| 225 |
+
# aha, this is the first one :-)
|
| 226 |
+
memo[id(memo)]=[x]
|
| 227 |
+
|
| 228 |
+
def _reconstruct(x, memo, func, args,
|
| 229 |
+
state=None, listiter=None, dictiter=None,
|
| 230 |
+
*, deepcopy=deepcopy):
|
| 231 |
+
deep = memo is not None
|
| 232 |
+
if deep and args:
|
| 233 |
+
args = (deepcopy(arg, memo) for arg in args)
|
| 234 |
+
y = func(*args)
|
| 235 |
+
if deep:
|
| 236 |
+
memo[id(x)] = y
|
| 237 |
+
|
| 238 |
+
if state is not None:
|
| 239 |
+
if deep:
|
| 240 |
+
state = deepcopy(state, memo)
|
| 241 |
+
if hasattr(y, '__setstate__'):
|
| 242 |
+
y.__setstate__(state)
|
| 243 |
+
else:
|
| 244 |
+
if isinstance(state, tuple) and len(state) == 2:
|
| 245 |
+
state, slotstate = state
|
| 246 |
+
else:
|
| 247 |
+
slotstate = None
|
| 248 |
+
if state is not None:
|
| 249 |
+
y.__dict__.update(state)
|
| 250 |
+
if slotstate is not None:
|
| 251 |
+
for key, value in slotstate.items():
|
| 252 |
+
setattr(y, key, value)
|
| 253 |
+
|
| 254 |
+
if listiter is not None:
|
| 255 |
+
if deep:
|
| 256 |
+
for item in listiter:
|
| 257 |
+
item = deepcopy(item, memo)
|
| 258 |
+
y.append(item)
|
| 259 |
+
else:
|
| 260 |
+
for item in listiter:
|
| 261 |
+
y.append(item)
|
| 262 |
+
if dictiter is not None:
|
| 263 |
+
if deep:
|
| 264 |
+
for key, value in dictiter:
|
| 265 |
+
key = deepcopy(key, memo)
|
| 266 |
+
value = deepcopy(value, memo)
|
| 267 |
+
y[key] = value
|
| 268 |
+
else:
|
| 269 |
+
for key, value in dictiter:
|
| 270 |
+
y[key] = value
|
| 271 |
+
return y
|
| 272 |
+
|
| 273 |
+
del types, weakref
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def replace(obj, /, **changes):
|
| 277 |
+
"""Return a new object replacing specified fields with new values.
|
| 278 |
+
|
| 279 |
+
This is especially useful for immutable objects, like named tuples or
|
| 280 |
+
frozen dataclasses.
|
| 281 |
+
"""
|
| 282 |
+
cls = obj.__class__
|
| 283 |
+
func = getattr(cls, '__replace__', None)
|
| 284 |
+
if func is None:
|
| 285 |
+
raise TypeError(f"replace() does not support {cls.__name__} objects")
|
| 286 |
+
return func(obj, **changes)
|
micromamba_root/envs/hf_sync/Lib/copyreg.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 1 |
+
"""Helper to provide extensibility for pickle.
|
| 2 |
+
|
| 3 |
+
This is only useful to add pickle support for extension types defined in
|
| 4 |
+
C, not for instances of user-defined classes.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
__all__ = ["pickle", "constructor",
|
| 8 |
+
"add_extension", "remove_extension", "clear_extension_cache"]
|
| 9 |
+
|
| 10 |
+
dispatch_table = {}
|
| 11 |
+
|
| 12 |
+
def pickle(ob_type, pickle_function, constructor_ob=None):
|
| 13 |
+
if not callable(pickle_function):
|
| 14 |
+
raise TypeError("reduction functions must be callable")
|
| 15 |
+
dispatch_table[ob_type] = pickle_function
|
| 16 |
+
|
| 17 |
+
# The constructor_ob function is a vestige of safe for unpickling.
|
| 18 |
+
# There is no reason for the caller to pass it anymore.
|
| 19 |
+
if constructor_ob is not None:
|
| 20 |
+
constructor(constructor_ob)
|
| 21 |
+
|
| 22 |
+
def constructor(object):
|
| 23 |
+
if not callable(object):
|
| 24 |
+
raise TypeError("constructors must be callable")
|
| 25 |
+
|
| 26 |
+
# Example: provide pickling support for complex numbers.
|
| 27 |
+
|
| 28 |
+
def pickle_complex(c):
|
| 29 |
+
return complex, (c.real, c.imag)
|
| 30 |
+
|
| 31 |
+
pickle(complex, pickle_complex, complex)
|
| 32 |
+
|
| 33 |
+
def pickle_union(obj):
|
| 34 |
+
import typing, operator
|
| 35 |
+
return operator.getitem, (typing.Union, obj.__args__)
|
| 36 |
+
|
| 37 |
+
pickle(type(int | str), pickle_union)
|
| 38 |
+
|
| 39 |
+
def pickle_super(obj):
|
| 40 |
+
return super, (obj.__thisclass__, obj.__self__)
|
| 41 |
+
|
| 42 |
+
pickle(super, pickle_super)
|
| 43 |
+
|
| 44 |
+
# Support for pickling new-style objects
|
| 45 |
+
|
| 46 |
+
def _reconstructor(cls, base, state):
|
| 47 |
+
if base is object:
|
| 48 |
+
obj = object.__new__(cls)
|
| 49 |
+
else:
|
| 50 |
+
obj = base.__new__(cls, state)
|
| 51 |
+
if base.__init__ != object.__init__:
|
| 52 |
+
base.__init__(obj, state)
|
| 53 |
+
return obj
|
| 54 |
+
|
| 55 |
+
_HEAPTYPE = 1<<9
|
| 56 |
+
_new_type = type(int.__new__)
|
| 57 |
+
|
| 58 |
+
# Python code for object.__reduce_ex__ for protocols 0 and 1
|
| 59 |
+
|
| 60 |
+
def _reduce_ex(self, proto):
|
| 61 |
+
assert proto < 2
|
| 62 |
+
cls = self.__class__
|
| 63 |
+
for base in cls.__mro__:
|
| 64 |
+
if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE:
|
| 65 |
+
break
|
| 66 |
+
new = base.__new__
|
| 67 |
+
if isinstance(new, _new_type) and new.__self__ is base:
|
| 68 |
+
break
|
| 69 |
+
else:
|
| 70 |
+
base = object # not really reachable
|
| 71 |
+
if base is object:
|
| 72 |
+
state = None
|
| 73 |
+
else:
|
| 74 |
+
if base is cls:
|
| 75 |
+
raise TypeError(f"cannot pickle {cls.__name__!r} object")
|
| 76 |
+
state = base(self)
|
| 77 |
+
args = (cls, base, state)
|
| 78 |
+
try:
|
| 79 |
+
getstate = self.__getstate__
|
| 80 |
+
except AttributeError:
|
| 81 |
+
if getattr(self, "__slots__", None):
|
| 82 |
+
raise TypeError(f"cannot pickle {cls.__name__!r} object: "
|
| 83 |
+
f"a class that defines __slots__ without "
|
| 84 |
+
f"defining __getstate__ cannot be pickled "
|
| 85 |
+
f"with protocol {proto}") from None
|
| 86 |
+
try:
|
| 87 |
+
dict = self.__dict__
|
| 88 |
+
except AttributeError:
|
| 89 |
+
dict = None
|
| 90 |
+
else:
|
| 91 |
+
if (type(self).__getstate__ is object.__getstate__ and
|
| 92 |
+
getattr(self, "__slots__", None)):
|
| 93 |
+
raise TypeError("a class that defines __slots__ without "
|
| 94 |
+
"defining __getstate__ cannot be pickled")
|
| 95 |
+
dict = getstate()
|
| 96 |
+
if dict:
|
| 97 |
+
return _reconstructor, args, dict
|
| 98 |
+
else:
|
| 99 |
+
return _reconstructor, args
|
| 100 |
+
|
| 101 |
+
# Helper for __reduce_ex__ protocol 2
|
| 102 |
+
|
| 103 |
+
def __newobj__(cls, *args):
|
| 104 |
+
return cls.__new__(cls, *args)
|
| 105 |
+
|
| 106 |
+
def __newobj_ex__(cls, args, kwargs):
|
| 107 |
+
"""Used by pickle protocol 4, instead of __newobj__ to allow classes with
|
| 108 |
+
keyword-only arguments to be pickled correctly.
|
| 109 |
+
"""
|
| 110 |
+
return cls.__new__(cls, *args, **kwargs)
|
| 111 |
+
|
| 112 |
+
def _slotnames(cls):
|
| 113 |
+
"""Return a list of slot names for a given class.
|
| 114 |
+
|
| 115 |
+
This needs to find slots defined by the class and its bases, so we
|
| 116 |
+
can't simply return the __slots__ attribute. We must walk down
|
| 117 |
+
the Method Resolution Order and concatenate the __slots__ of each
|
| 118 |
+
class found there. (This assumes classes don't modify their
|
| 119 |
+
__slots__ attribute to misrepresent their slots after the class is
|
| 120 |
+
defined.)
|
| 121 |
+
"""
|
| 122 |
+
|
| 123 |
+
# Get the value from a cache in the class if possible
|
| 124 |
+
names = cls.__dict__.get("__slotnames__")
|
| 125 |
+
if names is not None:
|
| 126 |
+
return names
|
| 127 |
+
|
| 128 |
+
# Not cached -- calculate the value
|
| 129 |
+
names = []
|
| 130 |
+
if not hasattr(cls, "__slots__"):
|
| 131 |
+
# This class has no slots
|
| 132 |
+
pass
|
| 133 |
+
else:
|
| 134 |
+
# Slots found -- gather slot names from all base classes
|
| 135 |
+
for c in cls.__mro__:
|
| 136 |
+
if "__slots__" in c.__dict__:
|
| 137 |
+
slots = c.__dict__['__slots__']
|
| 138 |
+
# if class has a single slot, it can be given as a string
|
| 139 |
+
if isinstance(slots, str):
|
| 140 |
+
slots = (slots,)
|
| 141 |
+
for name in slots:
|
| 142 |
+
# special descriptors
|
| 143 |
+
if name in ("__dict__", "__weakref__"):
|
| 144 |
+
continue
|
| 145 |
+
# mangled names
|
| 146 |
+
elif name.startswith('__') and not name.endswith('__'):
|
| 147 |
+
stripped = c.__name__.lstrip('_')
|
| 148 |
+
if stripped:
|
| 149 |
+
names.append('_%s%s' % (stripped, name))
|
| 150 |
+
else:
|
| 151 |
+
names.append(name)
|
| 152 |
+
else:
|
| 153 |
+
names.append(name)
|
| 154 |
+
|
| 155 |
+
# Cache the outcome in the class if at all possible
|
| 156 |
+
try:
|
| 157 |
+
cls.__slotnames__ = names
|
| 158 |
+
except:
|
| 159 |
+
pass # But don't die if we can't
|
| 160 |
+
|
| 161 |
+
return names
|
| 162 |
+
|
| 163 |
+
# A registry of extension codes. This is an ad-hoc compression
|
| 164 |
+
# mechanism. Whenever a global reference to <module>, <name> is about
|
| 165 |
+
# to be pickled, the (<module>, <name>) tuple is looked up here to see
|
| 166 |
+
# if it is a registered extension code for it. Extension codes are
|
| 167 |
+
# universal, so that the meaning of a pickle does not depend on
|
| 168 |
+
# context. (There are also some codes reserved for local use that
|
| 169 |
+
# don't have this restriction.) Codes are positive ints; 0 is
|
| 170 |
+
# reserved.
|
| 171 |
+
|
| 172 |
+
_extension_registry = {} # key -> code
|
| 173 |
+
_inverted_registry = {} # code -> key
|
| 174 |
+
_extension_cache = {} # code -> object
|
| 175 |
+
# Don't ever rebind those names: pickling grabs a reference to them when
|
| 176 |
+
# it's initialized, and won't see a rebinding.
|
| 177 |
+
|
| 178 |
+
def add_extension(module, name, code):
|
| 179 |
+
"""Register an extension code."""
|
| 180 |
+
code = int(code)
|
| 181 |
+
if not 1 <= code <= 0x7fffffff:
|
| 182 |
+
raise ValueError("code out of range")
|
| 183 |
+
key = (module, name)
|
| 184 |
+
if (_extension_registry.get(key) == code and
|
| 185 |
+
_inverted_registry.get(code) == key):
|
| 186 |
+
return # Redundant registrations are benign
|
| 187 |
+
if key in _extension_registry:
|
| 188 |
+
raise ValueError("key %s is already registered with code %s" %
|
| 189 |
+
(key, _extension_registry[key]))
|
| 190 |
+
if code in _inverted_registry:
|
| 191 |
+
raise ValueError("code %s is already in use for key %s" %
|
| 192 |
+
(code, _inverted_registry[code]))
|
| 193 |
+
_extension_registry[key] = code
|
| 194 |
+
_inverted_registry[code] = key
|
| 195 |
+
|
| 196 |
+
def remove_extension(module, name, code):
|
| 197 |
+
"""Unregister an extension code. For testing only."""
|
| 198 |
+
key = (module, name)
|
| 199 |
+
if (_extension_registry.get(key) != code or
|
| 200 |
+
_inverted_registry.get(code) != key):
|
| 201 |
+
raise ValueError("key %s is not registered with code %s" %
|
| 202 |
+
(key, code))
|
| 203 |
+
del _extension_registry[key]
|
| 204 |
+
del _inverted_registry[code]
|
| 205 |
+
if code in _extension_cache:
|
| 206 |
+
del _extension_cache[code]
|
| 207 |
+
|
| 208 |
+
def clear_extension_cache():
|
| 209 |
+
_extension_cache.clear()
|
| 210 |
+
|
| 211 |
+
# Standard extension code assignments
|
| 212 |
+
|
| 213 |
+
# Reserved ranges
|
| 214 |
+
|
| 215 |
+
# First Last Count Purpose
|
| 216 |
+
# 1 127 127 Reserved for Python standard library
|
| 217 |
+
# 128 191 64 Reserved for Zope
|
| 218 |
+
# 192 239 48 Reserved for 3rd parties
|
| 219 |
+
# 240 255 16 Reserved for private use (will never be assigned)
|
| 220 |
+
# 256 Inf Inf Reserved for future assignment
|
| 221 |
+
|
| 222 |
+
# Extension codes are assigned by the Python Software Foundation.
|