.
+
+ # kw_only validation and assignment.
+ if f._field_type in (_FIELD, _FIELD_INITVAR):
+ # For real and InitVar fields, if kw_only wasn't specified use the
+ # default value.
+ if f.kw_only is MISSING:
+ f.kw_only = default_kw_only
+ else:
+ # Make sure kw_only isn't set for ClassVars
+ assert f._field_type is _FIELD_CLASSVAR
+ if f.kw_only is not MISSING:
+ raise TypeError(f'field {f.name} is a ClassVar but specifies '
+ 'kw_only')
+
+ # For real fields, disallow mutable defaults. Use unhashable as a proxy
+ # indicator for mutability. Read the __hash__ attribute from the class,
+ # not the instance.
+ if f._field_type is _FIELD and f.default.__class__.__hash__ is None:
+ raise ValueError(f'mutable default {type(f.default)} for field '
+ f'{f.name} is not allowed: use default_factory')
+
+ return f
+
+def _set_new_attribute(cls, name, value):
+ # Never overwrites an existing attribute. Returns True if the
+ # attribute already exists.
+ if name in cls.__dict__:
+ return True
+ setattr(cls, name, value)
+ return False
+
+
+# Decide if/how we're going to create a hash function. Key is
+# (unsafe_hash, eq, frozen, does-hash-exist). Value is the action to
+# take. The common case is to do nothing, so instead of providing a
+# function that is a no-op, use None to signify that.
+
+def _hash_set_none(cls, fields, func_builder):
+ # It's sort of a hack that I'm setting this here, instead of at
+ # func_builder.add_fns_to_class time, but since this is an exceptional case
+ # (it's not setting an attribute to a function, but to a scalar value),
+ # just do it directly here. I might come to regret this.
+ cls.__hash__ = None
+
+def _hash_add(cls, fields, func_builder):
+ flds = [f for f in fields if (f.compare if f.hash is None else f.hash)]
+ self_tuple = _tuple_str('self', flds)
+ func_builder.add_fn('__hash__',
+ ('self',),
+ [f' return hash({self_tuple})'],
+ unconditional_add=True)
+
+def _hash_exception(cls, fields, func_builder):
+ # Raise an exception.
+ raise TypeError(f'Cannot overwrite attribute __hash__ '
+ f'in class {cls.__name__}')
+
+#
+# +-------------------------------------- unsafe_hash?
+# | +------------------------------- eq?
+# | | +------------------------ frozen?
+# | | | +---------------- has-explicit-hash?
+# | | | |
+# | | | | +------- action
+# | | | | |
+# v v v v v
+_hash_action = {(False, False, False, False): None,
+ (False, False, False, True ): None,
+ (False, False, True, False): None,
+ (False, False, True, True ): None,
+ (False, True, False, False): _hash_set_none,
+ (False, True, False, True ): None,
+ (False, True, True, False): _hash_add,
+ (False, True, True, True ): None,
+ (True, False, False, False): _hash_add,
+ (True, False, False, True ): _hash_exception,
+ (True, False, True, False): _hash_add,
+ (True, False, True, True ): _hash_exception,
+ (True, True, False, False): _hash_add,
+ (True, True, False, True ): _hash_exception,
+ (True, True, True, False): _hash_add,
+ (True, True, True, True ): _hash_exception,
+ }
+# See https://bugs.python.org/issue32929#msg312829 for an if-statement
+# version of this table.
+
+
+def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen,
+ match_args, kw_only, slots, weakref_slot):
+ # Now that dicts retain insertion order, there's no reason to use
+ # an ordered dict. I am leveraging that ordering here, because
+ # derived class fields overwrite base class fields, but the order
+ # is defined by the base class, which is found first.
+ fields = {}
+
+ if cls.__module__ in sys.modules:
+ globals = sys.modules[cls.__module__].__dict__
+ else:
+ # Theoretically this can happen if someone writes
+ # a custom string to cls.__module__. In which case
+ # such dataclass won't be fully introspectable
+ # (w.r.t. typing.get_type_hints) but will still function
+ # correctly.
+ globals = {}
+
+ setattr(cls, _PARAMS, _DataclassParams(init, repr, eq, order,
+ unsafe_hash, frozen,
+ match_args, kw_only,
+ slots, weakref_slot))
+
+ # Find our base classes in reverse MRO order, and exclude
+ # ourselves. In reversed order so that more derived classes
+ # override earlier field definitions in base classes. As long as
+ # we're iterating over them, see if all or any of them are frozen.
+ any_frozen_base = False
+ # By default `all_frozen_bases` is `None` to represent a case,
+ # where some dataclasses does not have any bases with `_FIELDS`
+ all_frozen_bases = None
+ has_dataclass_bases = False
+ for b in cls.__mro__[-1:0:-1]:
+ # Only process classes that have been processed by our
+ # decorator. That is, they have a _FIELDS attribute.
+ base_fields = getattr(b, _FIELDS, None)
+ if base_fields is not None:
+ has_dataclass_bases = True
+ for f in base_fields.values():
+ fields[f.name] = f
+ if all_frozen_bases is None:
+ all_frozen_bases = True
+ current_frozen = getattr(b, _PARAMS).frozen
+ all_frozen_bases = all_frozen_bases and current_frozen
+ any_frozen_base = any_frozen_base or current_frozen
+
+ # Annotations defined specifically in this class (not in base classes).
+ #
+ # Fields are found from cls_annotations, which is guaranteed to be
+ # ordered. Default values are from class attributes, if a field
+ # has a default. If the default value is a Field(), then it
+ # contains additional info beyond (and possibly including) the
+ # actual default value. Pseudo-fields ClassVars and InitVars are
+ # included, despite the fact that they're not real fields. That's
+ # dealt with later.
+ cls_annotations = annotationlib.get_annotations(
+ cls, format=annotationlib.Format.FORWARDREF)
+
+ # Now find fields in our class. While doing so, validate some
+ # things, and set the default values (as class attributes) where
+ # we can.
+ cls_fields = []
+ # Get a reference to this module for the _is_kw_only() test.
+ KW_ONLY_seen = False
+ dataclasses = sys.modules[__name__]
+ for name, type in cls_annotations.items():
+ # See if this is a marker to change the value of kw_only.
+ if (_is_kw_only(type, dataclasses)
+ or (isinstance(type, str)
+ and _is_type(type, cls, dataclasses, dataclasses.KW_ONLY,
+ _is_kw_only))):
+ # Switch the default to kw_only=True, and ignore this
+ # annotation: it's not a real field.
+ if KW_ONLY_seen:
+ raise TypeError(f'{name!r} is KW_ONLY, but KW_ONLY '
+ 'has already been specified')
+ KW_ONLY_seen = True
+ kw_only = True
+ else:
+ # Otherwise it's a field of some type.
+ cls_fields.append(_get_field(cls, name, type, kw_only))
+
+ for f in cls_fields:
+ fields[f.name] = f
+
+ # If the class attribute (which is the default value for this
+ # field) exists and is of type 'Field', replace it with the
+ # real default. This is so that normal class introspection
+ # sees a real default value, not a Field.
+ if isinstance(getattr(cls, f.name, None), Field):
+ if f.default is MISSING:
+ # If there's no default, delete the class attribute.
+ # This happens if we specify field(repr=False), for
+ # example (that is, we specified a field object, but
+ # no default value). Also if we're using a default
+ # factory. The class attribute should not be set at
+ # all in the post-processed class.
+ delattr(cls, f.name)
+ else:
+ setattr(cls, f.name, f.default)
+
+ # Do we have any Field members that don't also have annotations?
+ for name, value in cls.__dict__.items():
+ if isinstance(value, Field) and not name in cls_annotations:
+ raise TypeError(f'{name!r} is a field but has no type annotation')
+
+ # Check rules that apply if we are derived from any dataclasses.
+ if has_dataclass_bases:
+ # Raise an exception if any of our bases are frozen, but we're not.
+ if any_frozen_base and not frozen:
+ raise TypeError('cannot inherit non-frozen dataclass from a '
+ 'frozen one')
+
+ # Raise an exception if we're frozen, but none of our bases are.
+ if all_frozen_bases is False and frozen:
+ raise TypeError('cannot inherit frozen dataclass from a '
+ 'non-frozen one')
+
+ # Remember all of the fields on our class (including bases). This
+ # also marks this class as being a dataclass.
+ setattr(cls, _FIELDS, fields)
+
+ # Was this class defined with an explicit __hash__? Note that if
+ # __eq__ is defined in this class, then python will automatically
+ # set __hash__ to None. This is a heuristic, as it's possible
+ # that such a __hash__ == None was not auto-generated, but it's
+ # close enough.
+ class_hash = cls.__dict__.get('__hash__', MISSING)
+ has_explicit_hash = not (class_hash is MISSING or
+ (class_hash is None and '__eq__' in cls.__dict__))
+
+ # If we're generating ordering methods, we must be generating the
+ # eq methods.
+ if order and not eq:
+ raise ValueError('eq must be true if order is true')
+
+ # Include InitVars and regular fields (so, not ClassVars). This is
+ # initialized here, outside of the "if init:" test, because std_init_fields
+ # is used with match_args, below.
+ all_init_fields = [f for f in fields.values()
+ if f._field_type in (_FIELD, _FIELD_INITVAR)]
+ (std_init_fields,
+ kw_only_init_fields) = _fields_in_init_order(all_init_fields)
+
+ func_builder = _FuncBuilder(globals)
+
+ if init:
+ # Does this class have a post-init function?
+ has_post_init = hasattr(cls, _POST_INIT_NAME)
+
+ _init_fn(all_init_fields,
+ std_init_fields,
+ kw_only_init_fields,
+ frozen,
+ has_post_init,
+ # The name to use for the "self"
+ # param in __init__. Use "self"
+ # if possible.
+ '__dataclass_self__' if 'self' in fields
+ else 'self',
+ func_builder,
+ slots,
+ )
+
+ _set_new_attribute(cls, '__replace__', _replace)
+
+ # Get the fields as a list, and include only real fields. This is
+ # used in all of the following methods.
+ field_list = [f for f in fields.values() if f._field_type is _FIELD]
+
+ if repr:
+ flds = [f for f in field_list if f.repr]
+ func_builder.add_fn('__repr__',
+ ('self',),
+ [' return f"{self.__class__.__qualname__}(' +
+ ', '.join([f"{f.name}={{self.{f.name}!r}}"
+ for f in flds]) + ')"'],
+ locals={'__dataclasses_recursive_repr': recursive_repr},
+ decorator="@__dataclasses_recursive_repr()")
+
+ if eq:
+ # Create __eq__ method. There's no need for a __ne__ method,
+ # since python will call __eq__ and negate it.
+ cmp_fields = (field for field in field_list if field.compare)
+ terms = [f'self.{field.name}==other.{field.name}' for field in cmp_fields]
+ field_comparisons = ' and '.join(terms) or 'True'
+ func_builder.add_fn('__eq__',
+ ('self', 'other'),
+ [ ' if self is other:',
+ ' return True',
+ ' if other.__class__ is self.__class__:',
+ f' return {field_comparisons}',
+ ' return NotImplemented'])
+
+ if order:
+ # Create and set the ordering methods.
+ flds = [f for f in field_list if f.compare]
+ self_tuple = _tuple_str('self', flds)
+ other_tuple = _tuple_str('other', flds)
+ for name, op in [('__lt__', '<'),
+ ('__le__', '<='),
+ ('__gt__', '>'),
+ ('__ge__', '>='),
+ ]:
+ # Create a comparison function. If the fields in the object are
+ # named 'x' and 'y', then self_tuple is the string
+ # '(self.x,self.y)' and other_tuple is the string
+ # '(other.x,other.y)'.
+ func_builder.add_fn(name,
+ ('self', 'other'),
+ [ ' if other.__class__ is self.__class__:',
+ f' return {self_tuple}{op}{other_tuple}',
+ ' return NotImplemented'],
+ overwrite_error='Consider using functools.total_ordering')
+
+ if frozen:
+ _frozen_get_del_attr(cls, field_list, func_builder)
+
+ # Decide if/how we're going to create a hash function.
+ hash_action = _hash_action[bool(unsafe_hash),
+ bool(eq),
+ bool(frozen),
+ has_explicit_hash]
+ if hash_action:
+ cls.__hash__ = hash_action(cls, field_list, func_builder)
+
+ # Generate the methods and add them to the class. This needs to be done
+ # before the __doc__ logic below, since inspect will look at the __init__
+ # signature.
+ func_builder.add_fns_to_class(cls)
+
+ if not getattr(cls, '__doc__'):
+ # Create a class doc-string.
+ try:
+ # In some cases fetching a signature is not possible.
+ # But, we surely should not fail in this case.
+ text_sig = str(inspect.signature(
+ cls,
+ annotation_format=annotationlib.Format.FORWARDREF,
+ )).replace(' -> None', '')
+ except (TypeError, ValueError):
+ text_sig = ''
+ cls.__doc__ = (cls.__name__ + text_sig)
+
+ if match_args:
+ # I could probably compute this once.
+ _set_new_attribute(cls, '__match_args__',
+ tuple(f.name for f in std_init_fields))
+
+ # It's an error to specify weakref_slot if slots is False.
+ if weakref_slot and not slots:
+ raise TypeError('weakref_slot is True but slots is False')
+ if slots:
+ cls = _add_slots(cls, frozen, weakref_slot, fields)
+
+ abc.update_abstractmethods(cls)
+
+ return cls
+
+
+# _dataclass_getstate and _dataclass_setstate are needed for pickling frozen
+# classes with slots. These could be slightly more performant if we generated
+# the code instead of iterating over fields. But that can be a project for
+# another day, if performance becomes an issue.
+def _dataclass_getstate(self):
+ return [getattr(self, f.name) for f in fields(self)]
+
+
+def _dataclass_setstate(self, state):
+ for field, value in zip(fields(self), state):
+ # use setattr because dataclass may be frozen
+ object.__setattr__(self, field.name, value)
+
+
+def _get_slots(cls):
+ match cls.__dict__.get('__slots__'):
+ # `__dictoffset__` and `__weakrefoffset__` can tell us whether
+ # the base type has dict/weakref slots, in a way that works correctly
+ # for both Python classes and C extension types. Extension types
+ # don't use `__slots__` for slot creation
+ case None:
+ slots = []
+ if getattr(cls, '__weakrefoffset__', -1) != 0:
+ slots.append('__weakref__')
+ if getattr(cls, '__dictoffset__', -1) != 0:
+ slots.append('__dict__')
+ yield from slots
+ case str(slot):
+ yield slot
+ # Slots may be any iterable, but we cannot handle an iterator
+ # because it will already be (partially) consumed.
+ case iterable if not hasattr(iterable, '__next__'):
+ yield from iterable
+ case _:
+ raise TypeError(f"Slots of '{cls.__name__}' cannot be determined")
+
+
+def _update_func_cell_for__class__(f, oldcls, newcls):
+ # Returns True if we update a cell, else False.
+ if f is None:
+ # f will be None in the case of a property where not all of
+ # fget, fset, and fdel are used. Nothing to do in that case.
+ return False
+ try:
+ idx = f.__code__.co_freevars.index("__class__")
+ except ValueError:
+ # This function doesn't reference __class__, so nothing to do.
+ return False
+ # Fix the cell to point to the new class, if it's already pointing
+ # at the old class. I'm not convinced that the "is oldcls" test
+ # is needed, but other than performance can't hurt.
+ closure = f.__closure__[idx]
+ if closure.cell_contents is oldcls:
+ closure.cell_contents = newcls
+ return True
+ return False
+
+
+def _create_slots(defined_fields, inherited_slots, field_names, weakref_slot):
+ # The slots for our class. Remove slots from our base classes. Add
+ # '__weakref__' if weakref_slot was given, unless it is already present.
+ seen_docs = False
+ slots = {}
+ for slot in itertools.filterfalse(
+ inherited_slots.__contains__,
+ itertools.chain(
+ # gh-93521: '__weakref__' also needs to be filtered out if
+ # already present in inherited_slots
+ field_names, ('__weakref__',) if weakref_slot else ()
+ )
+ ):
+ doc = getattr(defined_fields.get(slot), 'doc', None)
+ if doc is not None:
+ seen_docs = True
+ slots[slot] = doc
+
+ # We only return dict if there's at least one doc member,
+ # otherwise we return tuple, which is the old default format.
+ if seen_docs:
+ return slots
+ return tuple(slots)
+
+
+def _add_slots(cls, is_frozen, weakref_slot, defined_fields):
+ # Need to create a new class, since we can't set __slots__ after a
+ # class has been created, and the @dataclass decorator is called
+ # after the class is created.
+
+ # Make sure __slots__ isn't already set.
+ if '__slots__' in cls.__dict__:
+ raise TypeError(f'{cls.__name__} already specifies __slots__')
+
+ # gh-102069: Remove existing __weakref__ descriptor.
+ # gh-135228: Make sure the original class can be garbage collected.
+ sys._clear_type_descriptors(cls)
+
+ # Create a new dict for our new class.
+ cls_dict = dict(cls.__dict__)
+ field_names = tuple(f.name for f in fields(cls))
+ # Make sure slots don't overlap with those in base classes.
+ inherited_slots = set(
+ itertools.chain.from_iterable(map(_get_slots, cls.__mro__[1:-1]))
+ )
+
+ cls_dict["__slots__"] = _create_slots(
+ defined_fields, inherited_slots, field_names, weakref_slot,
+ )
+
+ for field_name in field_names:
+ # Remove our attributes, if present. They'll still be
+ # available in _MARKER.
+ cls_dict.pop(field_name, None)
+
+ # And finally create the class.
+ qualname = getattr(cls, '__qualname__', None)
+ newcls = type(cls)(cls.__name__, cls.__bases__, cls_dict)
+ if qualname is not None:
+ newcls.__qualname__ = qualname
+
+ if is_frozen:
+ # Need this for pickling frozen classes with slots.
+ if '__getstate__' not in cls_dict:
+ newcls.__getstate__ = _dataclass_getstate
+ if '__setstate__' not in cls_dict:
+ newcls.__setstate__ = _dataclass_setstate
+
+ # Fix up any closures which reference __class__. This is used to
+ # fix zero argument super so that it points to the correct class
+ # (the newly created one, which we're returning) and not the
+ # original class. We can break out of this loop as soon as we
+ # make an update, since all closures for a class will share a
+ # given cell.
+ for member in newcls.__dict__.values():
+ # If this is a wrapped function, unwrap it.
+ member = inspect.unwrap(member)
+
+ if isinstance(member, types.FunctionType):
+ if _update_func_cell_for__class__(member, cls, newcls):
+ break
+ elif isinstance(member, property):
+ if (_update_func_cell_for__class__(member.fget, cls, newcls)
+ or _update_func_cell_for__class__(member.fset, cls, newcls)
+ or _update_func_cell_for__class__(member.fdel, cls, newcls)):
+ break
+
+ # Get new annotations to remove references to the original class
+ # in forward references
+ newcls_ann = annotationlib.get_annotations(
+ newcls, format=annotationlib.Format.FORWARDREF)
+
+ # Fix references in dataclass Fields
+ for f in getattr(newcls, _FIELDS).values():
+ try:
+ ann = newcls_ann[f.name]
+ except KeyError:
+ pass
+ else:
+ f.type = ann
+
+ # Fix the class reference in the __annotate__ method
+ init = newcls.__init__
+ if init_annotate := getattr(init, "__annotate__", None):
+ if getattr(init_annotate, "__generated_by_dataclasses__", False):
+ _update_func_cell_for__class__(init_annotate, cls, newcls)
+
+ return newcls
+
+
+def dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False,
+ unsafe_hash=False, frozen=False, match_args=True,
+ kw_only=False, slots=False, weakref_slot=False):
+ """Add dunder methods based on the fields defined in the class.
+
+ Examines PEP 526 __annotations__ to determine fields.
+
+ If init is true, an __init__() method is added to the class. If repr
+ is true, a __repr__() method is added. If order is true, rich
+ comparison dunder methods are added. If unsafe_hash is true, a
+ __hash__() method is added. If frozen is true, fields may not be
+ assigned to after instance creation. If match_args is true, the
+ __match_args__ tuple is added. If kw_only is true, then by default
+ all fields are keyword-only. If slots is true, a new class with a
+ __slots__ attribute is returned.
+ """
+
+ def wrap(cls):
+ return _process_class(cls, init, repr, eq, order, unsafe_hash,
+ frozen, match_args, kw_only, slots,
+ weakref_slot)
+
+ # See if we're being called as @dataclass or @dataclass().
+ if cls is None:
+ # We're called with parens.
+ return wrap
+
+ # We're called as @dataclass without parens.
+ return wrap(cls)
+
+
+def fields(class_or_instance):
+ """Return a tuple describing the fields of this dataclass.
+
+ Accepts a dataclass or an instance of one. Tuple elements are of
+ type Field.
+ """
+
+ # Might it be worth caching this, per class?
+ try:
+ fields = getattr(class_or_instance, _FIELDS)
+ except AttributeError:
+ raise TypeError('must be called with a dataclass type or instance') from None
+
+ # Exclude pseudo-fields. Note that fields is sorted by insertion
+ # order, so the order of the tuple is as the fields were defined.
+ return tuple(f for f in fields.values() if f._field_type is _FIELD)
+
+
+def _is_dataclass_instance(obj):
+ """Returns True if obj is an instance of a dataclass."""
+ return hasattr(type(obj), _FIELDS)
+
+
+def is_dataclass(obj):
+ """Returns True if obj is a dataclass or an instance of a
+ dataclass."""
+ cls = obj if isinstance(obj, type) else type(obj)
+ return hasattr(cls, _FIELDS)
+
+
+def asdict(obj, *, dict_factory=dict):
+ """Return the fields of a dataclass instance as a new dictionary mapping
+ field names to field values.
+
+ Example usage::
+
+ @dataclass
+ class C:
+ x: int
+ y: int
+
+ c = C(1, 2)
+ assert asdict(c) == {'x': 1, 'y': 2}
+
+ If given, 'dict_factory' will be used instead of built-in dict.
+ The function applies recursively to field values that are
+ dataclass instances. This will also look into built-in containers:
+ tuples, lists, and dicts. Other objects are copied with 'copy.deepcopy()'.
+ """
+ if not _is_dataclass_instance(obj):
+ raise TypeError("asdict() should be called on dataclass instances")
+ return _asdict_inner(obj, dict_factory)
+
+
+def _asdict_inner(obj, dict_factory):
+ obj_type = type(obj)
+ if obj_type in _ATOMIC_TYPES:
+ return obj
+ elif hasattr(obj_type, _FIELDS):
+ # dataclass instance: fast path for the common case
+ if dict_factory is dict:
+ return {
+ f.name: _asdict_inner(getattr(obj, f.name), dict)
+ for f in fields(obj)
+ }
+ else:
+ return dict_factory([
+ (f.name, _asdict_inner(getattr(obj, f.name), dict_factory))
+ for f in fields(obj)
+ ])
+ # handle the builtin types first for speed; subclasses handled below
+ elif obj_type is list:
+ return [_asdict_inner(v, dict_factory) for v in obj]
+ elif obj_type is dict:
+ return {
+ _asdict_inner(k, dict_factory): _asdict_inner(v, dict_factory)
+ for k, v in obj.items()
+ }
+ elif obj_type is tuple:
+ return tuple([_asdict_inner(v, dict_factory) for v in obj])
+ elif issubclass(obj_type, tuple):
+ if hasattr(obj, '_fields'):
+ # obj is a namedtuple. Recurse into it, but the returned
+ # object is another namedtuple of the same type. This is
+ # similar to how other list- or tuple-derived classes are
+ # treated (see below), but we just need to create them
+ # differently because a namedtuple's __init__ needs to be
+ # called differently (see bpo-34363).
+
+ # I'm not using namedtuple's _asdict()
+ # method, because:
+ # - it does not recurse in to the namedtuple fields and
+ # convert them to dicts (using dict_factory).
+ # - I don't actually want to return a dict here. The main
+ # use case here is json.dumps, and it handles converting
+ # namedtuples to lists. Admittedly we're losing some
+ # information here when we produce a json list instead of a
+ # dict. Note that if we returned dicts here instead of
+ # namedtuples, we could no longer call asdict() on a data
+ # structure where a namedtuple was used as a dict key.
+ return obj_type(*[_asdict_inner(v, dict_factory) for v in obj])
+ else:
+ return obj_type(_asdict_inner(v, dict_factory) for v in obj)
+ elif issubclass(obj_type, dict):
+ if hasattr(obj_type, 'default_factory'):
+ # obj is a defaultdict, which has a different constructor from
+ # dict as it requires the default_factory as its first arg.
+ result = obj_type(obj.default_factory)
+ for k, v in obj.items():
+ result[_asdict_inner(k, dict_factory)] = _asdict_inner(v, dict_factory)
+ return result
+ return obj_type((_asdict_inner(k, dict_factory),
+ _asdict_inner(v, dict_factory))
+ for k, v in obj.items())
+ elif issubclass(obj_type, list):
+ # Assume we can create an object of this type by passing in a
+ # generator
+ return obj_type(_asdict_inner(v, dict_factory) for v in obj)
+ else:
+ return copy.deepcopy(obj)
+
+
+def astuple(obj, *, tuple_factory=tuple):
+ """Return the fields of a dataclass instance as a new tuple of field values.
+
+ Example usage::
+
+ @dataclass
+ class C:
+ x: int
+ y: int
+
+ c = C(1, 2)
+ assert astuple(c) == (1, 2)
+
+ If given, 'tuple_factory' will be used instead of built-in tuple.
+ The function applies recursively to field values that are
+ dataclass instances. This will also look into built-in containers:
+ tuples, lists, and dicts. Other objects are copied with 'copy.deepcopy()'.
+ """
+
+ if not _is_dataclass_instance(obj):
+ raise TypeError("astuple() should be called on dataclass instances")
+ return _astuple_inner(obj, tuple_factory)
+
+
+def _astuple_inner(obj, tuple_factory):
+ if type(obj) in _ATOMIC_TYPES:
+ return obj
+ elif _is_dataclass_instance(obj):
+ return tuple_factory([
+ _astuple_inner(getattr(obj, f.name), tuple_factory)
+ for f in fields(obj)
+ ])
+ elif isinstance(obj, tuple) and hasattr(obj, '_fields'):
+ # obj is a namedtuple. Recurse into it, but the returned
+ # object is another namedtuple of the same type. This is
+ # similar to how other list- or tuple-derived classes are
+ # treated (see below), but we just need to create them
+ # differently because a namedtuple's __init__ needs to be
+ # called differently (see bpo-34363).
+ return type(obj)(*[_astuple_inner(v, tuple_factory) for v in obj])
+ elif isinstance(obj, (list, tuple)):
+ # Assume we can create an object of this type by passing in a
+ # generator (which is not true for namedtuples, handled
+ # above).
+ return type(obj)(_astuple_inner(v, tuple_factory) for v in obj)
+ elif isinstance(obj, dict):
+ obj_type = type(obj)
+ if hasattr(obj_type, 'default_factory'):
+ # obj is a defaultdict, which has a different constructor from
+ # dict as it requires the default_factory as its first arg.
+ result = obj_type(getattr(obj, 'default_factory'))
+ for k, v in obj.items():
+ result[_astuple_inner(k, tuple_factory)] = _astuple_inner(v, tuple_factory)
+ return result
+ return obj_type((_astuple_inner(k, tuple_factory), _astuple_inner(v, tuple_factory))
+ for k, v in obj.items())
+ else:
+ return copy.deepcopy(obj)
+
+
+def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
+ repr=True, eq=True, order=False, unsafe_hash=False,
+ frozen=False, match_args=True, kw_only=False, slots=False,
+ weakref_slot=False, module=None, decorator=dataclass):
+ """Return a new dynamically created dataclass.
+
+ The dataclass name will be 'cls_name'. 'fields' is an iterable
+ of either (name), (name, type) or (name, type, Field) objects. If type is
+ omitted, use the string 'typing.Any'. Field objects are created by
+ the equivalent of calling 'field(name, type [, Field-info])'.::
+
+ C = make_dataclass('C', ['x', ('y', int), ('z', int, field(init=False))], bases=(Base,))
+
+ is equivalent to::
+
+ @dataclass
+ class C(Base):
+ x: 'typing.Any'
+ y: int
+ z: int = field(init=False)
+
+ For the bases and namespace parameters, see the builtin type() function.
+
+ The parameters init, repr, eq, order, unsafe_hash, frozen, match_args, kw_only,
+ slots, and weakref_slot are passed to dataclass().
+
+ If module parameter is defined, the '__module__' attribute of the dataclass is
+ set to that value.
+ """
+
+ if namespace is None:
+ namespace = {}
+
+ # While we're looking through the field names, validate that they
+ # are identifiers, are not keywords, and not duplicates.
+ seen = set()
+ annotations = {}
+ defaults = {}
+ for item in fields:
+ if isinstance(item, str):
+ name = item
+ tp = _ANY_MARKER
+ elif len(item) == 2:
+ name, tp, = item
+ elif len(item) == 3:
+ name, tp, spec = item
+ defaults[name] = spec
+ else:
+ raise TypeError(f'Invalid field: {item!r}')
+
+ if not isinstance(name, str) or not name.isidentifier():
+ raise TypeError(f'Field names must be valid identifiers: {name!r}')
+ if keyword.iskeyword(name):
+ raise TypeError(f'Field names must not be keywords: {name!r}')
+ if name in seen:
+ raise TypeError(f'Field name duplicated: {name!r}')
+
+ seen.add(name)
+ annotations[name] = tp
+
+ # We initially block the VALUE format, because inside dataclass() we'll
+ # call get_annotations(), which will try the VALUE format first. If we don't
+ # block, that means we'd always end up eagerly importing typing here, which
+ # is what we're trying to avoid.
+ value_blocked = True
+
+ def annotate_method(format):
+ def get_any():
+ match format:
+ case annotationlib.Format.STRING:
+ return 'typing.Any'
+ case annotationlib.Format.FORWARDREF:
+ typing = sys.modules.get("typing")
+ if typing is None:
+ return annotationlib.ForwardRef("Any", module="typing")
+ else:
+ return typing.Any
+ case annotationlib.Format.VALUE:
+ if value_blocked:
+ raise NotImplementedError
+ from typing import Any
+ return Any
+ case _:
+ raise NotImplementedError
+ annos = {
+ ann: get_any() if t is _ANY_MARKER else t
+ for ann, t in annotations.items()
+ }
+ if format == annotationlib.Format.STRING:
+ return annotationlib.annotations_to_string(annos)
+ else:
+ return annos
+
+ # Update 'ns' with the user-supplied namespace plus our calculated values.
+ def exec_body_callback(ns):
+ ns.update(namespace)
+ ns.update(defaults)
+
+ # We use `types.new_class()` instead of simply `type()` to allow dynamic creation
+ # of generic dataclasses.
+ cls = types.new_class(cls_name, bases, {}, exec_body_callback)
+ # For now, set annotations including the _ANY_MARKER.
+ cls.__annotate__ = annotate_method
+
+ # For pickling to work, the __module__ variable needs to be set to the frame
+ # where the dataclass is created.
+ if module is None:
+ try:
+ module = sys._getframemodulename(1) or '__main__'
+ except AttributeError:
+ try:
+ module = sys._getframe(1).f_globals.get('__name__', '__main__')
+ except (AttributeError, ValueError):
+ pass
+ if module is not None:
+ cls.__module__ = module
+
+ # Apply the normal provided decorator.
+ cls = decorator(cls, init=init, repr=repr, eq=eq, order=order,
+ unsafe_hash=unsafe_hash, frozen=frozen,
+ match_args=match_args, kw_only=kw_only, slots=slots,
+ weakref_slot=weakref_slot)
+ # Now that the class is ready, allow the VALUE format.
+ value_blocked = False
+ return cls
+
+
+def replace(obj, /, **changes):
+ """Return a new object replacing specified fields with new values.
+
+ This is especially useful for frozen classes. Example usage::
+
+ @dataclass(frozen=True)
+ class C:
+ x: int
+ y: int
+
+ c = C(1, 2)
+ c1 = replace(c, x=3)
+ assert c1.x == 3 and c1.y == 2
+ """
+ if not _is_dataclass_instance(obj):
+ raise TypeError("replace() should be called on dataclass instances")
+ return _replace(obj, **changes)
+
+
+def _replace(self, /, **changes):
+ # We're going to mutate 'changes', but that's okay because it's a
+ # new dict, even if called with 'replace(self, **my_changes)'.
+
+ # It's an error to have init=False fields in 'changes'.
+ # If a field is not in 'changes', read its value from the provided 'self'.
+
+ for f in getattr(self, _FIELDS).values():
+ # Only consider normal fields or InitVars.
+ if f._field_type is _FIELD_CLASSVAR:
+ continue
+
+ if not f.init:
+ # Error if this field is specified in changes.
+ if f.name in changes:
+ raise TypeError(f'field {f.name} is declared with '
+ f'init=False, it cannot be specified with '
+ f'replace()')
+ continue
+
+ if f.name not in changes:
+ if f._field_type is _FIELD_INITVAR and f.default is MISSING:
+ raise TypeError(f"InitVar {f.name!r} "
+ f'must be specified with replace()')
+ changes[f.name] = getattr(self, f.name)
+
+ # Create the new object, which calls __init__() and
+ # __post_init__() (if defined), using all of the init fields we've
+ # added and/or left in 'changes'. If there are values supplied in
+ # changes that aren't fields, this will correctly raise a
+ # TypeError.
+ return self.__class__(**changes)
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/datetime.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/datetime.py
new file mode 100644
index 0000000000000000000000000000000000000000..14f30556584e32b98bec77922f9fa69af39a87e4
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/datetime.py
@@ -0,0 +1,13 @@
+"""Specific date/time and related types.
+
+See https://data.iana.org/time-zones/tz-link.html for
+time zone and DST data sources.
+"""
+
+try:
+ from _datetime import *
+except ImportError:
+ from _pydatetime import *
+
+__all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo",
+ "MINYEAR", "MAXYEAR", "UTC")
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/decimal.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/decimal.py
new file mode 100644
index 0000000000000000000000000000000000000000..530bdfb38953d995e715f02fca97f9160c4fab2c
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/decimal.py
@@ -0,0 +1,109 @@
+"""Decimal fixed-point and floating-point arithmetic.
+
+This is an implementation of decimal floating-point arithmetic based on
+the General Decimal Arithmetic Specification:
+
+ http://speleotrove.com/decimal/decarith.html
+
+and IEEE standard 854-1987:
+
+ http://en.wikipedia.org/wiki/IEEE_854-1987
+
+Decimal floating point has finite precision with arbitrarily large bounds.
+
+The purpose of this module is to support arithmetic using familiar
+"schoolhouse" rules and to avoid some of the tricky representation
+issues associated with binary floating point. The package is especially
+useful for financial applications or for contexts where users have
+expectations that are at odds with binary floating point (for instance,
+in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
+of 0.0; Decimal('1.00') % Decimal('0.1') returns the expected
+Decimal('0.00')).
+
+Here are some examples of using the decimal module:
+
+>>> from decimal import *
+>>> setcontext(ExtendedContext)
+>>> Decimal(0)
+Decimal('0')
+>>> Decimal('1')
+Decimal('1')
+>>> Decimal('-.0123')
+Decimal('-0.0123')
+>>> Decimal(123456)
+Decimal('123456')
+>>> Decimal('123.45e12345678')
+Decimal('1.2345E+12345680')
+>>> Decimal('1.33') + Decimal('1.27')
+Decimal('2.60')
+>>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
+Decimal('-2.20')
+>>> dig = Decimal(1)
+>>> print(dig / Decimal(3))
+0.333333333
+>>> getcontext().prec = 18
+>>> print(dig / Decimal(3))
+0.333333333333333333
+>>> print(dig.sqrt())
+1
+>>> print(Decimal(3).sqrt())
+1.73205080756887729
+>>> print(Decimal(3) ** 123)
+4.85192780976896427E+58
+>>> inf = Decimal(1) / Decimal(0)
+>>> print(inf)
+Infinity
+>>> neginf = Decimal(-1) / Decimal(0)
+>>> print(neginf)
+-Infinity
+>>> print(neginf + inf)
+NaN
+>>> print(neginf * inf)
+-Infinity
+>>> print(dig / 0)
+Infinity
+>>> getcontext().traps[DivisionByZero] = 1
+>>> print(dig / 0)
+Traceback (most recent call last):
+ ...
+ ...
+ ...
+decimal.DivisionByZero: x / 0
+>>> c = Context()
+>>> c.traps[InvalidOperation] = 0
+>>> print(c.flags[InvalidOperation])
+0
+>>> c.divide(Decimal(0), Decimal(0))
+Decimal('NaN')
+>>> c.traps[InvalidOperation] = 1
+>>> print(c.flags[InvalidOperation])
+1
+>>> c.flags[InvalidOperation] = 0
+>>> print(c.flags[InvalidOperation])
+0
+>>> print(c.divide(Decimal(0), Decimal(0)))
+Traceback (most recent call last):
+ ...
+ ...
+ ...
+decimal.InvalidOperation: 0 / 0
+>>> print(c.flags[InvalidOperation])
+1
+>>> c.flags[InvalidOperation] = 0
+>>> c.traps[InvalidOperation] = 0
+>>> print(c.divide(Decimal(0), Decimal(0)))
+NaN
+>>> print(c.flags[InvalidOperation])
+1
+>>>
+"""
+
+try:
+ from _decimal import *
+ from _decimal import __version__ # noqa: F401
+ from _decimal import __libmpdec_version__ # noqa: F401
+except ImportError:
+ import _pydecimal
+ import sys
+ _pydecimal.__doc__ = __doc__
+ sys.modules[__name__] = _pydecimal
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/difflib.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/difflib.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac1ba4a6e4ee9475ebe75dbf6c955a03dca5c518
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/difflib.py
@@ -0,0 +1,2064 @@
+"""
+Module difflib -- helpers for computing deltas between objects.
+
+Function get_close_matches(word, possibilities, n=3, cutoff=0.6):
+ Use SequenceMatcher to return list of the best "good enough" matches.
+
+Function context_diff(a, b):
+ For two lists of strings, return a delta in context diff format.
+
+Function ndiff(a, b):
+ Return a delta: the difference between `a` and `b` (lists of strings).
+
+Function restore(delta, which):
+ Return one of the two sequences that generated an ndiff delta.
+
+Function unified_diff(a, b):
+ For two lists of strings, return a delta in unified diff format.
+
+Class SequenceMatcher:
+ A flexible class for comparing pairs of sequences of any type.
+
+Class Differ:
+ For producing human-readable deltas from sequences of lines of text.
+
+Class HtmlDiff:
+ For producing HTML side by side comparison with change highlights.
+"""
+
+__all__ = ['get_close_matches', 'ndiff', 'restore', 'SequenceMatcher',
+ 'Differ','IS_CHARACTER_JUNK', 'IS_LINE_JUNK', 'context_diff',
+ 'unified_diff', 'diff_bytes', 'HtmlDiff', 'Match']
+
+from heapq import nlargest as _nlargest
+from collections import namedtuple as _namedtuple
+from types import GenericAlias
+
+Match = _namedtuple('Match', 'a b size')
+
+def _calculate_ratio(matches, length):
+ if length:
+ return 2.0 * matches / length
+ return 1.0
+
+class SequenceMatcher:
+
+ """
+ SequenceMatcher is a flexible class for comparing pairs of sequences of
+ any type, so long as the sequence elements are hashable. The basic
+ algorithm predates, and is a little fancier than, an algorithm
+ published in the late 1980's by Ratcliff and Obershelp under the
+ hyperbolic name "gestalt pattern matching". The basic idea is to find
+ the longest contiguous matching subsequence that contains no "junk"
+ elements (R-O doesn't address junk). The same idea is then applied
+ recursively to the pieces of the sequences to the left and to the right
+ of the matching subsequence. This does not yield minimal edit
+ sequences, but does tend to yield matches that "look right" to people.
+
+ SequenceMatcher tries to compute a "human-friendly diff" between two
+ sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
+ longest *contiguous* & junk-free matching subsequence. That's what
+ catches peoples' eyes. The Windows(tm) windiff has another interesting
+ notion, pairing up elements that appear uniquely in each sequence.
+ That, and the method here, appear to yield more intuitive difference
+ reports than does diff. This method appears to be the least vulnerable
+ to syncing up on blocks of "junk lines", though (like blank lines in
+ ordinary text files, or maybe "" lines in HTML files). That may be
+ because this is the only method of the 3 that has a *concept* of
+ "junk" .
+
+ Example, comparing two strings, and considering blanks to be "junk":
+
+ >>> s = SequenceMatcher(lambda x: x == " ",
+ ... "private Thread currentThread;",
+ ... "private volatile Thread currentThread;")
+ >>>
+
+ .ratio() returns a float in [0, 1], measuring the "similarity" of the
+ sequences. As a rule of thumb, a .ratio() value over 0.6 means the
+ sequences are close matches:
+
+ >>> print(round(s.ratio(), 2))
+ 0.87
+ >>>
+
+ If you're only interested in where the sequences match,
+ .get_matching_blocks() is handy:
+
+ >>> for block in s.get_matching_blocks():
+ ... print("a[%d] and b[%d] match for %d elements" % block)
+ a[0] and b[0] match for 8 elements
+ a[8] and b[17] match for 21 elements
+ a[29] and b[38] match for 0 elements
+
+ Note that the last tuple returned by .get_matching_blocks() is always a
+ dummy, (len(a), len(b), 0), and this is the only case in which the last
+ tuple element (number of elements matched) is 0.
+
+ If you want to know how to change the first sequence into the second,
+ use .get_opcodes():
+
+ >>> for opcode in s.get_opcodes():
+ ... print("%6s a[%d:%d] b[%d:%d]" % opcode)
+ equal a[0:8] b[0:8]
+ insert a[8:8] b[8:17]
+ equal a[8:29] b[17:38]
+
+ See the Differ class for a fancy human-friendly file differencer, which
+ uses SequenceMatcher both to compare sequences of lines, and to compare
+ sequences of characters within similar (near-matching) lines.
+
+ See also function get_close_matches() in this module, which shows how
+ simple code building on SequenceMatcher can be used to do useful work.
+
+ Timing: Basic R-O is cubic time worst case and quadratic time expected
+ case. SequenceMatcher is quadratic time for the worst case and has
+ expected-case behavior dependent in a complicated way on how many
+ elements the sequences have in common; best case time is linear.
+ """
+
+ def __init__(self, isjunk=None, a='', b='', autojunk=True):
+ """Construct a SequenceMatcher.
+
+ Optional arg isjunk is None (the default), or a one-argument
+ function that takes a sequence element and returns true iff the
+ element is junk. None is equivalent to passing "lambda x: 0", i.e.
+ no elements are considered to be junk. For example, pass
+ lambda x: x in " \\t"
+ if you're comparing lines as sequences of characters, and don't
+ want to synch up on blanks or hard tabs.
+
+ Optional arg a is the first of two sequences to be compared. By
+ default, an empty string. The elements of a must be hashable. See
+ also .set_seqs() and .set_seq1().
+
+ Optional arg b is the second of two sequences to be compared. By
+ default, an empty string. The elements of b must be hashable. See
+ also .set_seqs() and .set_seq2().
+
+ Optional arg autojunk should be set to False to disable the
+ "automatic junk heuristic" that treats popular elements as junk
+ (see module documentation for more information).
+ """
+
+ # Members:
+ # a
+ # first sequence
+ # b
+ # second sequence; differences are computed as "what do
+ # we need to do to 'a' to change it into 'b'?"
+ # b2j
+ # for x in b, b2j[x] is a list of the indices (into b)
+ # at which x appears; junk and popular elements do not appear
+ # fullbcount
+ # for x in b, fullbcount[x] == the number of times x
+ # appears in b; only materialized if really needed (used
+ # only for computing quick_ratio())
+ # matching_blocks
+ # a list of (i, j, k) triples, where a[i:i+k] == b[j:j+k];
+ # ascending & non-overlapping in i and in j; terminated by
+ # a dummy (len(a), len(b), 0) sentinel
+ # opcodes
+ # a list of (tag, i1, i2, j1, j2) tuples, where tag is
+ # one of
+ # 'replace' a[i1:i2] should be replaced by b[j1:j2]
+ # 'delete' a[i1:i2] should be deleted
+ # 'insert' b[j1:j2] should be inserted
+ # 'equal' a[i1:i2] == b[j1:j2]
+ # isjunk
+ # a user-supplied function taking a sequence element and
+ # returning true iff the element is "junk" -- this has
+ # subtle but helpful effects on the algorithm, which I'll
+ # get around to writing up someday <0.9 wink>.
+ # DON'T USE! Only __chain_b uses this. Use "in self.bjunk".
+ # bjunk
+ # the items in b for which isjunk is True.
+ # bpopular
+ # nonjunk items in b treated as junk by the heuristic (if used).
+
+ self.isjunk = isjunk
+ self.a = self.b = None
+ self.autojunk = autojunk
+ self.set_seqs(a, b)
+
+ def set_seqs(self, a, b):
+ """Set the two sequences to be compared.
+
+ >>> s = SequenceMatcher()
+ >>> s.set_seqs("abcd", "bcde")
+ >>> s.ratio()
+ 0.75
+ """
+
+ self.set_seq1(a)
+ self.set_seq2(b)
+
+ def set_seq1(self, a):
+ """Set the first sequence to be compared.
+
+ The second sequence to be compared is not changed.
+
+ >>> s = SequenceMatcher(None, "abcd", "bcde")
+ >>> s.ratio()
+ 0.75
+ >>> s.set_seq1("bcde")
+ >>> s.ratio()
+ 1.0
+ >>>
+
+ SequenceMatcher computes and caches detailed information about the
+ second sequence, so if you want to compare one sequence S against
+ many sequences, use .set_seq2(S) once and call .set_seq1(x)
+ repeatedly for each of the other sequences.
+
+ See also set_seqs() and set_seq2().
+ """
+
+ if a is self.a:
+ return
+ self.a = a
+ self.matching_blocks = self.opcodes = None
+
+ def set_seq2(self, b):
+ """Set the second sequence to be compared.
+
+ The first sequence to be compared is not changed.
+
+ >>> s = SequenceMatcher(None, "abcd", "bcde")
+ >>> s.ratio()
+ 0.75
+ >>> s.set_seq2("abcd")
+ >>> s.ratio()
+ 1.0
+ >>>
+
+ SequenceMatcher computes and caches detailed information about the
+ second sequence, so if you want to compare one sequence S against
+ many sequences, use .set_seq2(S) once and call .set_seq1(x)
+ repeatedly for each of the other sequences.
+
+ See also set_seqs() and set_seq1().
+ """
+
+ if b is self.b:
+ return
+ self.b = b
+ self.matching_blocks = self.opcodes = None
+ self.fullbcount = None
+ self.__chain_b()
+
+ # For each element x in b, set b2j[x] to a list of the indices in
+ # b where x appears; the indices are in increasing order; note that
+ # the number of times x appears in b is len(b2j[x]) ...
+ # when self.isjunk is defined, junk elements don't show up in this
+ # map at all, which stops the central find_longest_match method
+ # from starting any matching block at a junk element ...
+ # b2j also does not contain entries for "popular" elements, meaning
+ # elements that account for more than 1 + 1% of the total elements, and
+ # when the sequence is reasonably large (>= 200 elements); this can
+ # be viewed as an adaptive notion of semi-junk, and yields an enormous
+ # speedup when, e.g., comparing program files with hundreds of
+ # instances of "return NULL;" ...
+ # note that this is only called when b changes; so for cross-product
+ # kinds of matches, it's best to call set_seq2 once, then set_seq1
+ # repeatedly
+
+ def __chain_b(self):
+ # Because isjunk is a user-defined (not C) function, and we test
+ # for junk a LOT, it's important to minimize the number of calls.
+ # Before the tricks described here, __chain_b was by far the most
+ # time-consuming routine in the whole module! If anyone sees
+ # Jim Roskind, thank him again for profile.py -- I never would
+ # have guessed that.
+ # The first trick is to build b2j ignoring the possibility
+ # of junk. I.e., we don't call isjunk at all yet. Throwing
+ # out the junk later is much cheaper than building b2j "right"
+ # from the start.
+ b = self.b
+ self.b2j = b2j = {}
+
+ for i, elt in enumerate(b):
+ indices = b2j.setdefault(elt, [])
+ indices.append(i)
+
+ # Purge junk elements
+ self.bjunk = junk = set()
+ isjunk = self.isjunk
+ if isjunk:
+ for elt in b2j.keys():
+ if isjunk(elt):
+ junk.add(elt)
+ for elt in junk: # separate loop avoids separate list of keys
+ del b2j[elt]
+
+ # Purge popular elements that are not junk
+ self.bpopular = popular = set()
+ n = len(b)
+ if self.autojunk and n >= 200:
+ ntest = n // 100 + 1
+ for elt, idxs in b2j.items():
+ if len(idxs) > ntest:
+ popular.add(elt)
+ for elt in popular: # ditto; as fast for 1% deletion
+ del b2j[elt]
+
+ def find_longest_match(self, alo=0, ahi=None, blo=0, bhi=None):
+ """Find longest matching block in a[alo:ahi] and b[blo:bhi].
+
+ By default it will find the longest match in the entirety of a and b.
+
+ If isjunk is not defined:
+
+ Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
+ alo <= i <= i+k <= ahi
+ blo <= j <= j+k <= bhi
+ and for all (i',j',k') meeting those conditions,
+ k >= k'
+ i <= i'
+ and if i == i', j <= j'
+
+ In other words, of all maximal matching blocks, return one that
+ starts earliest in a, and of all those maximal matching blocks that
+ start earliest in a, return the one that starts earliest in b.
+
+ >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
+ >>> s.find_longest_match(0, 5, 0, 9)
+ Match(a=0, b=4, size=5)
+
+ If isjunk is defined, first the longest matching block is
+ determined as above, but with the additional restriction that no
+ junk element appears in the block. Then that block is extended as
+ far as possible by matching (only) junk elements on both sides. So
+ the resulting block never matches on junk except as identical junk
+ happens to be adjacent to an "interesting" match.
+
+ Here's the same example as before, but considering blanks to be
+ junk. That prevents " abcd" from matching the " abcd" at the tail
+ end of the second sequence directly. Instead only the "abcd" can
+ match, and matches the leftmost "abcd" in the second sequence:
+
+ >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
+ >>> s.find_longest_match(0, 5, 0, 9)
+ Match(a=1, b=0, size=4)
+
+ If no blocks match, return (alo, blo, 0).
+
+ >>> s = SequenceMatcher(None, "ab", "c")
+ >>> s.find_longest_match(0, 2, 0, 1)
+ Match(a=0, b=0, size=0)
+ """
+
+ # CAUTION: stripping common prefix or suffix would be incorrect.
+ # E.g.,
+ # ab
+ # acab
+ # Longest matching block is "ab", but if common prefix is
+ # stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
+ # strip, so ends up claiming that ab is changed to acab by
+ # inserting "ca" in the middle. That's minimal but unintuitive:
+ # "it's obvious" that someone inserted "ac" at the front.
+ # Windiff ends up at the same place as diff, but by pairing up
+ # the unique 'b's and then matching the first two 'a's.
+
+ a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.bjunk.__contains__
+ if ahi is None:
+ ahi = len(a)
+ if bhi is None:
+ bhi = len(b)
+ besti, bestj, bestsize = alo, blo, 0
+ # find longest junk-free match
+ # during an iteration of the loop, j2len[j] = length of longest
+ # junk-free match ending with a[i-1] and b[j]
+ j2len = {}
+ nothing = []
+ for i in range(alo, ahi):
+ # look at all instances of a[i] in b; note that because
+ # b2j has no junk keys, the loop is skipped if a[i] is junk
+ j2lenget = j2len.get
+ newj2len = {}
+ for j in b2j.get(a[i], nothing):
+ # a[i] matches b[j]
+ if j < blo:
+ continue
+ if j >= bhi:
+ break
+ k = newj2len[j] = j2lenget(j-1, 0) + 1
+ if k > bestsize:
+ besti, bestj, bestsize = i-k+1, j-k+1, k
+ j2len = newj2len
+
+ # Extend the best by non-junk elements on each end. In particular,
+ # "popular" non-junk elements aren't in b2j, which greatly speeds
+ # the inner loop above, but also means "the best" match so far
+ # doesn't contain any junk *or* popular non-junk elements.
+ while besti > alo and bestj > blo and \
+ not isbjunk(b[bestj-1]) and \
+ a[besti-1] == b[bestj-1]:
+ besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
+ while besti+bestsize < ahi and bestj+bestsize < bhi and \
+ not isbjunk(b[bestj+bestsize]) and \
+ a[besti+bestsize] == b[bestj+bestsize]:
+ bestsize += 1
+
+ # Now that we have a wholly interesting match (albeit possibly
+ # empty!), we may as well suck up the matching junk on each
+ # side of it too. Can't think of a good reason not to, and it
+ # saves post-processing the (possibly considerable) expense of
+ # figuring out what to do with it. In the case of an empty
+ # interesting match, this is clearly the right thing to do,
+ # because no other kind of match is possible in the regions.
+ while besti > alo and bestj > blo and \
+ isbjunk(b[bestj-1]) and \
+ a[besti-1] == b[bestj-1]:
+ besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
+ while besti+bestsize < ahi and bestj+bestsize < bhi and \
+ isbjunk(b[bestj+bestsize]) and \
+ a[besti+bestsize] == b[bestj+bestsize]:
+ bestsize = bestsize + 1
+
+ return Match(besti, bestj, bestsize)
+
+ def get_matching_blocks(self):
+ """Return list of triples describing matching subsequences.
+
+ Each triple is of the form (i, j, n), and means that
+ a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
+ i and in j. New in Python 2.5, it's also guaranteed that if
+ (i, j, n) and (i', j', n') are adjacent triples in the list, and
+ the second is not the last triple in the list, then i+n != i' or
+ j+n != j'. IOW, adjacent triples never describe adjacent equal
+ blocks.
+
+ The last triple is a dummy, (len(a), len(b), 0), and is the only
+ triple with n==0.
+
+ >>> s = SequenceMatcher(None, "abxcd", "abcd")
+ >>> list(s.get_matching_blocks())
+ [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
+ """
+
+ if self.matching_blocks is not None:
+ return self.matching_blocks
+ la, lb = len(self.a), len(self.b)
+
+ # This is most naturally expressed as a recursive algorithm, but
+ # at least one user bumped into extreme use cases that exceeded
+ # the recursion limit on their box. So, now we maintain a list
+ # ('queue`) of blocks we still need to look at, and append partial
+ # results to `matching_blocks` in a loop; the matches are sorted
+ # at the end.
+ queue = [(0, la, 0, lb)]
+ matching_blocks = []
+ while queue:
+ alo, ahi, blo, bhi = queue.pop()
+ i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)
+ # a[alo:i] vs b[blo:j] unknown
+ # a[i:i+k] same as b[j:j+k]
+ # a[i+k:ahi] vs b[j+k:bhi] unknown
+ if k: # if k is 0, there was no matching block
+ matching_blocks.append(x)
+ if alo < i and blo < j:
+ queue.append((alo, i, blo, j))
+ if i+k < ahi and j+k < bhi:
+ queue.append((i+k, ahi, j+k, bhi))
+ matching_blocks.sort()
+
+ # It's possible that we have adjacent equal blocks in the
+ # matching_blocks list now. Starting with 2.5, this code was added
+ # to collapse them.
+ i1 = j1 = k1 = 0
+ non_adjacent = []
+ for i2, j2, k2 in matching_blocks:
+ # Is this block adjacent to i1, j1, k1?
+ if i1 + k1 == i2 and j1 + k1 == j2:
+ # Yes, so collapse them -- this just increases the length of
+ # the first block by the length of the second, and the first
+ # block so lengthened remains the block to compare against.
+ k1 += k2
+ else:
+ # Not adjacent. Remember the first block (k1==0 means it's
+ # the dummy we started with), and make the second block the
+ # new block to compare against.
+ if k1:
+ non_adjacent.append((i1, j1, k1))
+ i1, j1, k1 = i2, j2, k2
+ if k1:
+ non_adjacent.append((i1, j1, k1))
+
+ non_adjacent.append( (la, lb, 0) )
+ self.matching_blocks = list(map(Match._make, non_adjacent))
+ return self.matching_blocks
+
+ def get_opcodes(self):
+ """Return list of 5-tuples describing how to turn a into b.
+
+ Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
+ has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
+ tuple preceding it, and likewise for j1 == the previous j2.
+
+ The tags are strings, with these meanings:
+
+ 'replace': a[i1:i2] should be replaced by b[j1:j2]
+ 'delete': a[i1:i2] should be deleted.
+ Note that j1==j2 in this case.
+ 'insert': b[j1:j2] should be inserted at a[i1:i1].
+ Note that i1==i2 in this case.
+ 'equal': a[i1:i2] == b[j1:j2]
+
+ >>> a = "qabxcd"
+ >>> b = "abycdf"
+ >>> s = SequenceMatcher(None, a, b)
+ >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
+ ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
+ ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))
+ delete a[0:1] (q) b[0:0] ()
+ equal a[1:3] (ab) b[0:2] (ab)
+ replace a[3:4] (x) b[2:3] (y)
+ equal a[4:6] (cd) b[3:5] (cd)
+ insert a[6:6] () b[5:6] (f)
+ """
+
+ if self.opcodes is not None:
+ return self.opcodes
+ i = j = 0
+ self.opcodes = answer = []
+ for ai, bj, size in self.get_matching_blocks():
+ # invariant: we've pumped out correct diffs to change
+ # a[:i] into b[:j], and the next matching block is
+ # a[ai:ai+size] == b[bj:bj+size]. So we need to pump
+ # out a diff to change a[i:ai] into b[j:bj], pump out
+ # the matching block, and move (i,j) beyond the match
+ tag = ''
+ if i < ai and j < bj:
+ tag = 'replace'
+ elif i < ai:
+ tag = 'delete'
+ elif j < bj:
+ tag = 'insert'
+ if tag:
+ answer.append( (tag, i, ai, j, bj) )
+ i, j = ai+size, bj+size
+ # the list of matching blocks is terminated by a
+ # sentinel with size 0
+ if size:
+ answer.append( ('equal', ai, i, bj, j) )
+ return answer
+
+ def get_grouped_opcodes(self, n=3):
+ """ Isolate change clusters by eliminating ranges with no changes.
+
+ Return a generator of groups with up to n lines of context.
+ Each group is in the same format as returned by get_opcodes().
+
+ >>> from pprint import pprint
+ >>> a = list(map(str, range(1,40)))
+ >>> b = a[:]
+ >>> b[8:8] = ['i'] # Make an insertion
+ >>> b[20] += 'x' # Make a replacement
+ >>> b[23:28] = [] # Make a deletion
+ >>> b[30] += 'y' # Make another replacement
+ >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))
+ [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],
+ [('equal', 16, 19, 17, 20),
+ ('replace', 19, 20, 20, 21),
+ ('equal', 20, 22, 21, 23),
+ ('delete', 22, 27, 23, 23),
+ ('equal', 27, 30, 23, 26)],
+ [('equal', 31, 34, 27, 30),
+ ('replace', 34, 35, 30, 31),
+ ('equal', 35, 38, 31, 34)]]
+ """
+
+ codes = self.get_opcodes()
+ if not codes:
+ codes = [("equal", 0, 1, 0, 1)]
+ # Fixup leading and trailing groups if they show no changes.
+ if codes[0][0] == 'equal':
+ tag, i1, i2, j1, j2 = codes[0]
+ codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2
+ if codes[-1][0] == 'equal':
+ tag, i1, i2, j1, j2 = codes[-1]
+ codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)
+
+ nn = n + n
+ group = []
+ for tag, i1, i2, j1, j2 in codes:
+ # End the current group and start a new one whenever
+ # there is a large range with no changes.
+ if tag == 'equal' and i2-i1 > nn:
+ group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))
+ yield group
+ group = []
+ i1, j1 = max(i1, i2-n), max(j1, j2-n)
+ group.append((tag, i1, i2, j1 ,j2))
+ if group and not (len(group)==1 and group[0][0] == 'equal'):
+ yield group
+
+ def ratio(self):
+ """Return a measure of the sequences' similarity (float in [0,1]).
+
+ Where T is the total number of elements in both sequences, and
+ M is the number of matches, this is 2.0*M / T.
+ Note that this is 1 if the sequences are identical, and 0 if
+ they have nothing in common.
+
+ .ratio() is expensive to compute if you haven't already computed
+ .get_matching_blocks() or .get_opcodes(), in which case you may
+ want to try .quick_ratio() or .real_quick_ratio() first to get an
+ upper bound.
+
+ >>> s = SequenceMatcher(None, "abcd", "bcde")
+ >>> s.ratio()
+ 0.75
+ >>> s.quick_ratio()
+ 0.75
+ >>> s.real_quick_ratio()
+ 1.0
+ """
+
+ matches = sum(triple[-1] for triple in self.get_matching_blocks())
+ return _calculate_ratio(matches, len(self.a) + len(self.b))
+
+ def quick_ratio(self):
+ """Return an upper bound on ratio() relatively quickly.
+
+ This isn't defined beyond that it is an upper bound on .ratio(), and
+ is faster to compute.
+ """
+
+ # viewing a and b as multisets, set matches to the cardinality
+ # of their intersection; this counts the number of matches
+ # without regard to order, so is clearly an upper bound
+ if self.fullbcount is None:
+ self.fullbcount = fullbcount = {}
+ for elt in self.b:
+ fullbcount[elt] = fullbcount.get(elt, 0) + 1
+ fullbcount = self.fullbcount
+ # avail[x] is the number of times x appears in 'b' less the
+ # number of times we've seen it in 'a' so far ... kinda
+ avail = {}
+ availhas, matches = avail.__contains__, 0
+ for elt in self.a:
+ if availhas(elt):
+ numb = avail[elt]
+ else:
+ numb = fullbcount.get(elt, 0)
+ avail[elt] = numb - 1
+ if numb > 0:
+ matches = matches + 1
+ return _calculate_ratio(matches, len(self.a) + len(self.b))
+
+ def real_quick_ratio(self):
+ """Return an upper bound on ratio() very quickly.
+
+ This isn't defined beyond that it is an upper bound on .ratio(), and
+ is faster to compute than either .ratio() or .quick_ratio().
+ """
+
+ la, lb = len(self.a), len(self.b)
+ # can't have more matches than the number of elements in the
+ # shorter sequence
+ return _calculate_ratio(min(la, lb), la + lb)
+
+ __class_getitem__ = classmethod(GenericAlias)
+
+
+def get_close_matches(word, possibilities, n=3, cutoff=0.6):
+ """Use SequenceMatcher to return list of the best "good enough" matches.
+
+ word is a sequence for which close matches are desired (typically a
+ string).
+
+ possibilities is a list of sequences against which to match word
+ (typically a list of strings).
+
+ Optional arg n (default 3) is the maximum number of close matches to
+ return. n must be > 0.
+
+ Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
+ that don't score at least that similar to word are ignored.
+
+ The best (no more than n) matches among the possibilities are returned
+ in a list, sorted by similarity score, most similar first.
+
+ >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
+ ['apple', 'ape']
+ >>> import keyword as _keyword
+ >>> get_close_matches("wheel", _keyword.kwlist)
+ ['while']
+ >>> get_close_matches("Apple", _keyword.kwlist)
+ []
+ >>> get_close_matches("accept", _keyword.kwlist)
+ ['except']
+ """
+
+ if not n > 0:
+ raise ValueError("n must be > 0: %r" % (n,))
+ if not 0.0 <= cutoff <= 1.0:
+ raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
+ result = []
+ s = SequenceMatcher()
+ s.set_seq2(word)
+ for x in possibilities:
+ s.set_seq1(x)
+ if s.real_quick_ratio() >= cutoff and \
+ s.quick_ratio() >= cutoff and \
+ s.ratio() >= cutoff:
+ result.append((s.ratio(), x))
+
+ # Move the best scorers to head of list
+ result = _nlargest(n, result)
+ # Strip scores for the best n matches
+ return [x for score, x in result]
+
+
+def _keep_original_ws(s, tag_s):
+ """Replace whitespace with the original whitespace characters in `s`"""
+ return ''.join(
+ c if tag_c == " " and c.isspace() else tag_c
+ for c, tag_c in zip(s, tag_s)
+ )
+
+
+
+class Differ:
+ r"""
+ Differ is a class for comparing sequences of lines of text, and
+ producing human-readable differences or deltas. Differ uses
+ SequenceMatcher both to compare sequences of lines, and to compare
+ sequences of characters within similar (near-matching) lines.
+
+ Each line of a Differ delta begins with a two-letter code:
+
+ '- ' line unique to sequence 1
+ '+ ' line unique to sequence 2
+ ' ' line common to both sequences
+ '? ' line not present in either input sequence
+
+ Lines beginning with '? ' attempt to guide the eye to intraline
+ differences, and were not present in either input sequence. These lines
+ can be confusing if the sequences contain tab characters.
+
+ Note that Differ makes no claim to produce a *minimal* diff. To the
+ contrary, minimal diffs are often counter-intuitive, because they synch
+ up anywhere possible, sometimes accidental matches 100 pages apart.
+ Restricting synch points to contiguous matches preserves some notion of
+ locality, at the occasional cost of producing a longer diff.
+
+ Example: Comparing two texts.
+
+ First we set up the texts, sequences of individual single-line strings
+ ending with newlines (such sequences can also be obtained from the
+ `readlines()` method of file-like objects):
+
+ >>> text1 = ''' 1. Beautiful is better than ugly.
+ ... 2. Explicit is better than implicit.
+ ... 3. Simple is better than complex.
+ ... 4. Complex is better than complicated.
+ ... '''.splitlines(keepends=True)
+ >>> len(text1)
+ 4
+ >>> text1[0][-1]
+ '\n'
+ >>> text2 = ''' 1. Beautiful is better than ugly.
+ ... 3. Simple is better than complex.
+ ... 4. Complicated is better than complex.
+ ... 5. Flat is better than nested.
+ ... '''.splitlines(keepends=True)
+
+ Next we instantiate a Differ object:
+
+ >>> d = Differ()
+
+ Note that when instantiating a Differ object we may pass functions to
+ filter out line and character 'junk'. See Differ.__init__ for details.
+
+ Finally, we compare the two:
+
+ >>> result = list(d.compare(text1, text2))
+
+ 'result' is a list of strings, so let's pretty-print it:
+
+ >>> from pprint import pprint as _pprint
+ >>> _pprint(result)
+ [' 1. Beautiful is better than ugly.\n',
+ '- 2. Explicit is better than implicit.\n',
+ '- 3. Simple is better than complex.\n',
+ '+ 3. Simple is better than complex.\n',
+ '? ++\n',
+ '- 4. Complex is better than complicated.\n',
+ '? ^ ---- ^\n',
+ '+ 4. Complicated is better than complex.\n',
+ '? ++++ ^ ^\n',
+ '+ 5. Flat is better than nested.\n']
+
+ As a single multi-line string it looks like this:
+
+ >>> print(''.join(result), end="")
+ 1. Beautiful is better than ugly.
+ - 2. Explicit is better than implicit.
+ - 3. Simple is better than complex.
+ + 3. Simple is better than complex.
+ ? ++
+ - 4. Complex is better than complicated.
+ ? ^ ---- ^
+ + 4. Complicated is better than complex.
+ ? ++++ ^ ^
+ + 5. Flat is better than nested.
+ """
+
+ def __init__(self, linejunk=None, charjunk=None):
+ """
+ Construct a text differencer, with optional filters.
+
+ The two optional keyword parameters are for filter functions:
+
+ - `linejunk`: A function that should accept a single string argument,
+ and return true iff the string is junk. The module-level function
+ `IS_LINE_JUNK` may be used to filter out lines without visible
+ characters, except for at most one splat ('#'). It is recommended
+ to leave linejunk None; the underlying SequenceMatcher class has
+ an adaptive notion of "noise" lines that's better than any static
+ definition the author has ever been able to craft.
+
+ - `charjunk`: A function that should accept a string of length 1. The
+ module-level function `IS_CHARACTER_JUNK` may be used to filter out
+ whitespace characters (a blank or tab; **note**: bad idea to include
+ newline in this!). Use of IS_CHARACTER_JUNK is recommended.
+ """
+
+ self.linejunk = linejunk
+ self.charjunk = charjunk
+
+ def compare(self, a, b):
+ r"""
+ Compare two sequences of lines; generate the resulting delta.
+
+ Each sequence must contain individual single-line strings ending with
+ newlines. Such sequences can be obtained from the `readlines()` method
+ of file-like objects. The delta generated also consists of newline-
+ terminated strings, ready to be printed as-is via the writelines()
+ method of a file-like object.
+
+ Example:
+
+ >>> print(''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(True),
+ ... 'ore\ntree\nemu\n'.splitlines(True))),
+ ... end="")
+ - one
+ ? ^
+ + ore
+ ? ^
+ - two
+ - three
+ ? -
+ + tree
+ + emu
+ """
+
+ cruncher = SequenceMatcher(self.linejunk, a, b)
+ for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
+ if tag == 'replace':
+ g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
+ elif tag == 'delete':
+ g = self._dump('-', a, alo, ahi)
+ elif tag == 'insert':
+ g = self._dump('+', b, blo, bhi)
+ elif tag == 'equal':
+ g = self._dump(' ', a, alo, ahi)
+ else:
+ raise ValueError('unknown tag %r' % (tag,))
+
+ yield from g
+
+ def _dump(self, tag, x, lo, hi):
+ """Generate comparison results for a same-tagged range."""
+ for i in range(lo, hi):
+ yield '%s %s' % (tag, x[i])
+
+ def _plain_replace(self, a, alo, ahi, b, blo, bhi):
+ assert alo < ahi and blo < bhi
+ # dump the shorter block first -- reduces the burden on short-term
+ # memory if the blocks are of very different sizes
+ if bhi - blo < ahi - alo:
+ first = self._dump('+', b, blo, bhi)
+ second = self._dump('-', a, alo, ahi)
+ else:
+ first = self._dump('-', a, alo, ahi)
+ second = self._dump('+', b, blo, bhi)
+
+ for g in first, second:
+ yield from g
+
+ def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
+ r"""
+ When replacing one block of lines with another, search the blocks
+ for *similar* lines; the best-matching pair (if any) is used as a
+ synch point, and intraline difference marking is done on the
+ similar pair. Lots of work, but often worth it.
+
+ Example:
+
+ >>> d = Differ()
+ >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
+ ... ['abcdefGhijkl\n'], 0, 1)
+ >>> print(''.join(results), end="")
+ - abcDefghiJkl
+ ? ^ ^ ^
+ + abcdefGhijkl
+ ? ^ ^ ^
+ """
+ # Don't synch up unless the lines have a similarity score above
+ # cutoff. Previously only the smallest pair was handled here,
+ # and if there are many pairs with the best ratio, recursion
+ # could grow very deep, and runtime cubic. See:
+ # https://github.com/python/cpython/issues/119105
+ #
+ # Later, more pathological cases prompted removing recursion
+ # entirely.
+ cutoff = 0.74999
+ cruncher = SequenceMatcher(self.charjunk)
+ crqr = cruncher.real_quick_ratio
+ cqr = cruncher.quick_ratio
+ cr = cruncher.ratio
+
+ WINDOW = 10
+ best_i = best_j = None
+ dump_i, dump_j = alo, blo # smallest indices not yet resolved
+ for j in range(blo, bhi):
+ cruncher.set_seq2(b[j])
+ # Search the corresponding i's within WINDOW for rhe highest
+ # ratio greater than `cutoff`.
+ aequiv = alo + (j - blo)
+ arange = range(max(aequiv - WINDOW, dump_i),
+ min(aequiv + WINDOW + 1, ahi))
+ if not arange: # likely exit if `a` is shorter than `b`
+ break
+ best_ratio = cutoff
+ for i in arange:
+ cruncher.set_seq1(a[i])
+ # Ordering by cheapest to most expensive ratio is very
+ # valuable, most often getting out early.
+ if (crqr() > best_ratio
+ and cqr() > best_ratio
+ and cr() > best_ratio):
+ best_i, best_j, best_ratio = i, j, cr()
+
+ if best_i is None:
+ # found nothing to synch on yet - move to next j
+ continue
+
+ # pump out straight replace from before this synch pair
+ yield from self._fancy_helper(a, dump_i, best_i,
+ b, dump_j, best_j)
+ # do intraline marking on the synch pair
+ aelt, belt = a[best_i], b[best_j]
+ if aelt != belt:
+ # pump out a '-', '?', '+', '?' quad for the synched lines
+ atags = btags = ""
+ cruncher.set_seqs(aelt, belt)
+ for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
+ la, lb = ai2 - ai1, bj2 - bj1
+ if tag == 'replace':
+ atags += '^' * la
+ btags += '^' * lb
+ elif tag == 'delete':
+ atags += '-' * la
+ elif tag == 'insert':
+ btags += '+' * lb
+ elif tag == 'equal':
+ atags += ' ' * la
+ btags += ' ' * lb
+ else:
+ raise ValueError('unknown tag %r' % (tag,))
+ yield from self._qformat(aelt, belt, atags, btags)
+ else:
+ # the synch pair is identical
+ yield ' ' + aelt
+ dump_i, dump_j = best_i + 1, best_j + 1
+ best_i = best_j = None
+
+ # pump out straight replace from after the last synch pair
+ yield from self._fancy_helper(a, dump_i, ahi,
+ b, dump_j, bhi)
+
+ def _fancy_helper(self, a, alo, ahi, b, blo, bhi):
+ g = []
+ if alo < ahi:
+ if blo < bhi:
+ g = self._plain_replace(a, alo, ahi, b, blo, bhi)
+ else:
+ g = self._dump('-', a, alo, ahi)
+ elif blo < bhi:
+ g = self._dump('+', b, blo, bhi)
+
+ yield from g
+
+ def _qformat(self, aline, bline, atags, btags):
+ r"""
+ Format "?" output and deal with tabs.
+
+ Example:
+
+ >>> d = Differ()
+ >>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n',
+ ... ' ^ ^ ^ ', ' ^ ^ ^ ')
+ >>> for line in results: print(repr(line))
+ ...
+ '- \tabcDefghiJkl\n'
+ '? \t ^ ^ ^\n'
+ '+ \tabcdefGhijkl\n'
+ '? \t ^ ^ ^\n'
+ """
+ atags = _keep_original_ws(aline, atags).rstrip()
+ btags = _keep_original_ws(bline, btags).rstrip()
+
+ yield "- " + aline
+ if atags:
+ yield f"? {atags}\n"
+
+ yield "+ " + bline
+ if btags:
+ yield f"? {btags}\n"
+
+# With respect to junk, an earlier version of ndiff simply refused to
+# *start* a match with a junk element. The result was cases like this:
+# before: private Thread currentThread;
+# after: private volatile Thread currentThread;
+# If you consider whitespace to be junk, the longest contiguous match
+# not starting with junk is "e Thread currentThread". So ndiff reported
+# that "e volatil" was inserted between the 't' and the 'e' in "private".
+# While an accurate view, to people that's absurd. The current version
+# looks for matching blocks that are entirely junk-free, then extends the
+# longest one of those as far as possible but only with matching junk.
+# So now "currentThread" is matched, then extended to suck up the
+# preceding blank; then "private" is matched, and extended to suck up the
+# following blank; then "Thread" is matched; and finally ndiff reports
+# that "volatile " was inserted before "Thread". The only quibble
+# remaining is that perhaps it was really the case that " volatile"
+# was inserted after "private". I can live with that .
+
+def IS_LINE_JUNK(line, pat=None):
+ r"""
+ Return True for ignorable line: if `line` is blank or contains a single '#'.
+
+ Examples:
+
+ >>> IS_LINE_JUNK('\n')
+ True
+ >>> IS_LINE_JUNK(' # \n')
+ True
+ >>> IS_LINE_JUNK('hello\n')
+ False
+ """
+
+ if pat is None:
+ # Default: match '#' or the empty string
+ return line.strip() in '#'
+ # Previous versions used the undocumented parameter 'pat' as a
+ # match function. Retain this behaviour for compatibility.
+ return pat(line) is not None
+
+def IS_CHARACTER_JUNK(ch, ws=" \t"):
+ r"""
+ Return True for ignorable character: iff `ch` is a space or tab.
+
+ Examples:
+
+ >>> IS_CHARACTER_JUNK(' ')
+ True
+ >>> IS_CHARACTER_JUNK('\t')
+ True
+ >>> IS_CHARACTER_JUNK('\n')
+ False
+ >>> IS_CHARACTER_JUNK('x')
+ False
+ """
+
+ return ch in ws
+
+
+########################################################################
+### Unified Diff
+########################################################################
+
+def _format_range_unified(start, stop):
+ 'Convert range to the "ed" format'
+ # Per the diff spec at http://www.unix.org/single_unix_specification/
+ beginning = start + 1 # lines start numbering with one
+ length = stop - start
+ if length == 1:
+ return '{}'.format(beginning)
+ if not length:
+ beginning -= 1 # empty ranges begin at line just before the range
+ return '{},{}'.format(beginning, length)
+
+def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
+ tofiledate='', n=3, lineterm='\n'):
+ r"""
+ Compare two sequences of lines; generate the delta as a unified diff.
+
+ Unified diffs are a compact way of showing line changes and a few
+ lines of context. The number of context lines is set by 'n' which
+ defaults to three.
+
+ By default, the diff control lines (those with ---, +++, or @@) are
+ created with a trailing newline. This is helpful so that inputs
+ created from file.readlines() result in diffs that are suitable for
+ file.writelines() since both the inputs and outputs have trailing
+ newlines.
+
+ For inputs that do not have trailing newlines, set the lineterm
+ argument to "" so that the output will be uniformly newline free.
+
+ The unidiff format normally has a header for filenames and modification
+ times. Any or all of these may be specified using strings for
+ 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
+ The modification times are normally expressed in the ISO 8601 format.
+
+ Example:
+
+ >>> for line in unified_diff('one two three four'.split(),
+ ... 'zero one tree four'.split(), 'Original', 'Current',
+ ... '2005-01-26 23:30:50', '2010-04-02 10:20:52',
+ ... lineterm=''):
+ ... print(line) # doctest: +NORMALIZE_WHITESPACE
+ --- Original 2005-01-26 23:30:50
+ +++ Current 2010-04-02 10:20:52
+ @@ -1,4 +1,4 @@
+ +zero
+ one
+ -two
+ -three
+ +tree
+ four
+ """
+
+ _check_types(a, b, fromfile, tofile, fromfiledate, tofiledate, lineterm)
+ started = False
+ for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
+ if not started:
+ started = True
+ fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
+ todate = '\t{}'.format(tofiledate) if tofiledate else ''
+ yield '--- {}{}{}'.format(fromfile, fromdate, lineterm)
+ yield '+++ {}{}{}'.format(tofile, todate, lineterm)
+
+ first, last = group[0], group[-1]
+ file1_range = _format_range_unified(first[1], last[2])
+ file2_range = _format_range_unified(first[3], last[4])
+ yield '@@ -{} +{} @@{}'.format(file1_range, file2_range, lineterm)
+
+ for tag, i1, i2, j1, j2 in group:
+ if tag == 'equal':
+ for line in a[i1:i2]:
+ yield ' ' + line
+ continue
+ if tag in {'replace', 'delete'}:
+ for line in a[i1:i2]:
+ yield '-' + line
+ if tag in {'replace', 'insert'}:
+ for line in b[j1:j2]:
+ yield '+' + line
+
+
+########################################################################
+### Context Diff
+########################################################################
+
+def _format_range_context(start, stop):
+ 'Convert range to the "ed" format'
+ # Per the diff spec at http://www.unix.org/single_unix_specification/
+ beginning = start + 1 # lines start numbering with one
+ length = stop - start
+ if not length:
+ beginning -= 1 # empty ranges begin at line just before the range
+ if length <= 1:
+ return '{}'.format(beginning)
+ return '{},{}'.format(beginning, beginning + length - 1)
+
+# See http://www.unix.org/single_unix_specification/
+def context_diff(a, b, fromfile='', tofile='',
+ fromfiledate='', tofiledate='', n=3, lineterm='\n'):
+ r"""
+ Compare two sequences of lines; generate the delta as a context diff.
+
+ Context diffs are a compact way of showing line changes and a few
+ lines of context. The number of context lines is set by 'n' which
+ defaults to three.
+
+ By default, the diff control lines (those with *** or ---) are
+ created with a trailing newline. This is helpful so that inputs
+ created from file.readlines() result in diffs that are suitable for
+ file.writelines() since both the inputs and outputs have trailing
+ newlines.
+
+ For inputs that do not have trailing newlines, set the lineterm
+ argument to "" so that the output will be uniformly newline free.
+
+ The context diff format normally has a header for filenames and
+ modification times. Any or all of these may be specified using
+ strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
+ The modification times are normally expressed in the ISO 8601 format.
+ If not specified, the strings default to blanks.
+
+ Example:
+
+ >>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(True),
+ ... 'zero\none\ntree\nfour\n'.splitlines(True), 'Original', 'Current')),
+ ... end="")
+ *** Original
+ --- Current
+ ***************
+ *** 1,4 ****
+ one
+ ! two
+ ! three
+ four
+ --- 1,4 ----
+ + zero
+ one
+ ! tree
+ four
+ """
+
+ _check_types(a, b, fromfile, tofile, fromfiledate, tofiledate, lineterm)
+ prefix = dict(insert='+ ', delete='- ', replace='! ', equal=' ')
+ started = False
+ for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
+ if not started:
+ started = True
+ fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
+ todate = '\t{}'.format(tofiledate) if tofiledate else ''
+ yield '*** {}{}{}'.format(fromfile, fromdate, lineterm)
+ yield '--- {}{}{}'.format(tofile, todate, lineterm)
+
+ first, last = group[0], group[-1]
+ yield '***************' + lineterm
+
+ file1_range = _format_range_context(first[1], last[2])
+ yield '*** {} ****{}'.format(file1_range, lineterm)
+
+ if any(tag in {'replace', 'delete'} for tag, _, _, _, _ in group):
+ for tag, i1, i2, _, _ in group:
+ if tag != 'insert':
+ for line in a[i1:i2]:
+ yield prefix[tag] + line
+
+ file2_range = _format_range_context(first[3], last[4])
+ yield '--- {} ----{}'.format(file2_range, lineterm)
+
+ if any(tag in {'replace', 'insert'} for tag, _, _, _, _ in group):
+ for tag, _, _, j1, j2 in group:
+ if tag != 'delete':
+ for line in b[j1:j2]:
+ yield prefix[tag] + line
+
+def _check_types(a, b, *args):
+ # Checking types is weird, but the alternative is garbled output when
+ # someone passes mixed bytes and str to {unified,context}_diff(). E.g.
+ # without this check, passing filenames as bytes results in output like
+ # --- b'oldfile.txt'
+ # +++ b'newfile.txt'
+ # because of how str.format() incorporates bytes objects.
+ if a and not isinstance(a[0], str):
+ raise TypeError('lines to compare must be str, not %s (%r)' %
+ (type(a[0]).__name__, a[0]))
+ if b and not isinstance(b[0], str):
+ raise TypeError('lines to compare must be str, not %s (%r)' %
+ (type(b[0]).__name__, b[0]))
+ if isinstance(a, str):
+ raise TypeError('input must be a sequence of strings, not %s' %
+ type(a).__name__)
+ if isinstance(b, str):
+ raise TypeError('input must be a sequence of strings, not %s' %
+ type(b).__name__)
+ for arg in args:
+ if not isinstance(arg, str):
+ raise TypeError('all arguments must be str, not: %r' % (arg,))
+
+def diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'',
+ fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\n'):
+ r"""
+ Compare `a` and `b`, two sequences of lines represented as bytes rather
+ than str. This is a wrapper for `dfunc`, which is typically either
+ unified_diff() or context_diff(). Inputs are losslessly converted to
+ strings so that `dfunc` only has to worry about strings, and encoded
+ back to bytes on return. This is necessary to compare files with
+ unknown or inconsistent encoding. All other inputs (except `n`) must be
+ bytes rather than str.
+ """
+ def decode(s):
+ try:
+ return s.decode('ascii', 'surrogateescape')
+ except AttributeError as err:
+ msg = ('all arguments must be bytes, not %s (%r)' %
+ (type(s).__name__, s))
+ raise TypeError(msg) from err
+ a = list(map(decode, a))
+ b = list(map(decode, b))
+ fromfile = decode(fromfile)
+ tofile = decode(tofile)
+ fromfiledate = decode(fromfiledate)
+ tofiledate = decode(tofiledate)
+ lineterm = decode(lineterm)
+
+ lines = dfunc(a, b, fromfile, tofile, fromfiledate, tofiledate, n, lineterm)
+ for line in lines:
+ yield line.encode('ascii', 'surrogateescape')
+
+def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
+ r"""
+ Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
+
+ Optional keyword parameters `linejunk` and `charjunk` are for filter
+ functions, or can be None:
+
+ - linejunk: A function that should accept a single string argument and
+ return true iff the string is junk. The default is None, and is
+ recommended; the underlying SequenceMatcher class has an adaptive
+ notion of "noise" lines.
+
+ - charjunk: A function that accepts a character (string of length
+ 1), and returns true iff the character is junk. The default is
+ the module-level function IS_CHARACTER_JUNK, which filters out
+ whitespace characters (a blank or tab; note: it's a bad idea to
+ include newline in this!).
+
+ Tools/scripts/ndiff.py is a command-line front-end to this function.
+
+ Example:
+
+ >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
+ ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
+ >>> print(''.join(diff), end="")
+ - one
+ ? ^
+ + ore
+ ? ^
+ - two
+ - three
+ ? -
+ + tree
+ + emu
+ """
+ return Differ(linejunk, charjunk).compare(a, b)
+
+def _mdiff(fromlines, tolines, context=None, linejunk=None,
+ charjunk=IS_CHARACTER_JUNK):
+ r"""Returns generator yielding marked up from/to side by side differences.
+
+ Arguments:
+ fromlines -- list of text lines to compared to tolines
+ tolines -- list of text lines to be compared to fromlines
+ context -- number of context lines to display on each side of difference,
+ if None, all from/to text lines will be generated.
+ linejunk -- passed on to ndiff (see ndiff documentation)
+ charjunk -- passed on to ndiff (see ndiff documentation)
+
+ This function returns an iterator which returns a tuple:
+ (from line tuple, to line tuple, boolean flag)
+
+ from/to line tuple -- (line num, line text)
+ line num -- integer or None (to indicate a context separation)
+ line text -- original line text with following markers inserted:
+ '\0+' -- marks start of added text
+ '\0-' -- marks start of deleted text
+ '\0^' -- marks start of changed text
+ '\1' -- marks end of added/deleted/changed text
+
+ boolean flag -- None indicates context separation, True indicates
+ either "from" or "to" line contains a change, otherwise False.
+
+ This function/iterator was originally developed to generate side by side
+ file difference for making HTML pages (see HtmlDiff class for example
+ usage).
+
+ Note, this function utilizes the ndiff function to generate the side by
+ side difference markup. Optional ndiff arguments may be passed to this
+ function and they in turn will be passed to ndiff.
+ """
+ import re
+
+ # regular expression for finding intraline change indices
+ change_re = re.compile(r'(\++|\-+|\^+)')
+
+ # create the difference iterator to generate the differences
+ diff_lines_iterator = ndiff(fromlines,tolines,linejunk,charjunk)
+
+ def _make_line(lines, format_key, side, num_lines=[0,0]):
+ """Returns line of text with user's change markup and line formatting.
+
+ lines -- list of lines from the ndiff generator to produce a line of
+ text from. When producing the line of text to return, the
+ lines used are removed from this list.
+ format_key -- '+' return first line in list with "add" markup around
+ the entire line.
+ '-' return first line in list with "delete" markup around
+ the entire line.
+ '?' return first line in list with add/delete/change
+ intraline markup (indices obtained from second line)
+ None return first line in list with no markup
+ side -- indice into the num_lines list (0=from,1=to)
+ num_lines -- from/to current line number. This is NOT intended to be a
+ passed parameter. It is present as a keyword argument to
+ maintain memory of the current line numbers between calls
+ of this function.
+
+ Note, this function is purposefully not defined at the module scope so
+ that data it needs from its parent function (within whose context it
+ is defined) does not need to be of module scope.
+ """
+ num_lines[side] += 1
+ # Handle case where no user markup is to be added, just return line of
+ # text with user's line format to allow for usage of the line number.
+ if format_key is None:
+ return (num_lines[side],lines.pop(0)[2:])
+ # Handle case of intraline changes
+ if format_key == '?':
+ text, markers = lines.pop(0), lines.pop(0)
+ # find intraline changes (store change type and indices in tuples)
+ sub_info = []
+ def record_sub_info(match_object,sub_info=sub_info):
+ sub_info.append([match_object.group(1)[0],match_object.span()])
+ return match_object.group(1)
+ change_re.sub(record_sub_info,markers)
+ # process each tuple inserting our special marks that won't be
+ # noticed by an xml/html escaper.
+ for key,(begin,end) in reversed(sub_info):
+ text = text[0:begin]+'\0'+key+text[begin:end]+'\1'+text[end:]
+ text = text[2:]
+ # Handle case of add/delete entire line
+ else:
+ text = lines.pop(0)[2:]
+ # if line of text is just a newline, insert a space so there is
+ # something for the user to highlight and see.
+ if not text:
+ text = ' '
+ # insert marks that won't be noticed by an xml/html escaper.
+ text = '\0' + format_key + text + '\1'
+ # Return line of text, first allow user's line formatter to do its
+ # thing (such as adding the line number) then replace the special
+ # marks with what the user's change markup.
+ return (num_lines[side],text)
+
+ def _line_iterator():
+ """Yields from/to lines of text with a change indication.
+
+ This function is an iterator. It itself pulls lines from a
+ differencing iterator, processes them and yields them. When it can
+ it yields both a "from" and a "to" line, otherwise it will yield one
+ or the other. In addition to yielding the lines of from/to text, a
+ boolean flag is yielded to indicate if the text line(s) have
+ differences in them.
+
+ Note, this function is purposefully not defined at the module scope so
+ that data it needs from its parent function (within whose context it
+ is defined) does not need to be of module scope.
+ """
+ lines = []
+ num_blanks_pending, num_blanks_to_yield = 0, 0
+ while True:
+ # Load up next 4 lines so we can look ahead, create strings which
+ # are a concatenation of the first character of each of the 4 lines
+ # so we can do some very readable comparisons.
+ while len(lines) < 4:
+ lines.append(next(diff_lines_iterator, 'X'))
+ s = ''.join([line[0] for line in lines])
+ if s.startswith('X'):
+ # When no more lines, pump out any remaining blank lines so the
+ # corresponding add/delete lines get a matching blank line so
+ # all line pairs get yielded at the next level.
+ num_blanks_to_yield = num_blanks_pending
+ elif s.startswith('-?+?'):
+ # simple intraline change
+ yield _make_line(lines,'?',0), _make_line(lines,'?',1), True
+ continue
+ elif s.startswith('--++'):
+ # in delete block, add block coming: we do NOT want to get
+ # caught up on blank lines yet, just process the delete line
+ num_blanks_pending -= 1
+ yield _make_line(lines,'-',0), None, True
+ continue
+ elif s.startswith(('--?+', '--+', '- ')):
+ # in delete block and see an intraline change or unchanged line
+ # coming: yield the delete line and then blanks
+ from_line,to_line = _make_line(lines,'-',0), None
+ num_blanks_to_yield,num_blanks_pending = num_blanks_pending-1,0
+ elif s.startswith('-+?'):
+ # intraline change
+ yield _make_line(lines,None,0), _make_line(lines,'?',1), True
+ continue
+ elif s.startswith('-?+'):
+ # intraline change
+ yield _make_line(lines,'?',0), _make_line(lines,None,1), True
+ continue
+ elif s.startswith('-'):
+ # delete FROM line
+ num_blanks_pending -= 1
+ yield _make_line(lines,'-',0), None, True
+ continue
+ elif s.startswith('+--'):
+ # in add block, delete block coming: we do NOT want to get
+ # caught up on blank lines yet, just process the add line
+ num_blanks_pending += 1
+ yield None, _make_line(lines,'+',1), True
+ continue
+ elif s.startswith(('+ ', '+-')):
+ # will be leaving an add block: yield blanks then add line
+ from_line, to_line = None, _make_line(lines,'+',1)
+ num_blanks_to_yield,num_blanks_pending = num_blanks_pending+1,0
+ elif s.startswith('+'):
+ # inside an add block, yield the add line
+ num_blanks_pending += 1
+ yield None, _make_line(lines,'+',1), True
+ continue
+ elif s.startswith(' '):
+ # unchanged text, yield it to both sides
+ yield _make_line(lines[:],None,0),_make_line(lines,None,1),False
+ continue
+ # Catch up on the blank lines so when we yield the next from/to
+ # pair, they are lined up.
+ while(num_blanks_to_yield < 0):
+ num_blanks_to_yield += 1
+ yield None,('','\n'),True
+ while(num_blanks_to_yield > 0):
+ num_blanks_to_yield -= 1
+ yield ('','\n'),None,True
+ if s.startswith('X'):
+ return
+ else:
+ yield from_line,to_line,True
+
+ def _line_pair_iterator():
+ """Yields from/to lines of text with a change indication.
+
+ This function is an iterator. It itself pulls lines from the line
+ iterator. Its difference from that iterator is that this function
+ always yields a pair of from/to text lines (with the change
+ indication). If necessary it will collect single from/to lines
+ until it has a matching pair from/to pair to yield.
+
+ Note, this function is purposefully not defined at the module scope so
+ that data it needs from its parent function (within whose context it
+ is defined) does not need to be of module scope.
+ """
+ line_iterator = _line_iterator()
+ fromlines,tolines=[],[]
+ while True:
+ # Collecting lines of text until we have a from/to pair
+ while (len(fromlines)==0 or len(tolines)==0):
+ try:
+ from_line, to_line, found_diff = next(line_iterator)
+ except StopIteration:
+ return
+ if from_line is not None:
+ fromlines.append((from_line,found_diff))
+ if to_line is not None:
+ tolines.append((to_line,found_diff))
+ # Once we have a pair, remove them from the collection and yield it
+ from_line, fromDiff = fromlines.pop(0)
+ to_line, to_diff = tolines.pop(0)
+ yield (from_line,to_line,fromDiff or to_diff)
+
+ # Handle case where user does not want context differencing, just yield
+ # them up without doing anything else with them.
+ line_pair_iterator = _line_pair_iterator()
+ if context is None:
+ yield from line_pair_iterator
+ # Handle case where user wants context differencing. We must do some
+ # storage of lines until we know for sure that they are to be yielded.
+ else:
+ context += 1
+ lines_to_write = 0
+ while True:
+ # Store lines up until we find a difference, note use of a
+ # circular queue because we only need to keep around what
+ # we need for context.
+ index, contextLines = 0, [None]*(context)
+ found_diff = False
+ while(found_diff is False):
+ try:
+ from_line, to_line, found_diff = next(line_pair_iterator)
+ except StopIteration:
+ return
+ i = index % context
+ contextLines[i] = (from_line, to_line, found_diff)
+ index += 1
+ # Yield lines that we have collected so far, but first yield
+ # the user's separator.
+ if index > context:
+ yield None, None, None
+ lines_to_write = context
+ else:
+ lines_to_write = index
+ index = 0
+ while(lines_to_write):
+ i = index % context
+ index += 1
+ yield contextLines[i]
+ lines_to_write -= 1
+ # Now yield the context lines after the change
+ lines_to_write = context-1
+ try:
+ while(lines_to_write):
+ from_line, to_line, found_diff = next(line_pair_iterator)
+ # If another change within the context, extend the context
+ if found_diff:
+ lines_to_write = context-1
+ else:
+ lines_to_write -= 1
+ yield from_line, to_line, found_diff
+ except StopIteration:
+ # Catch exception from next() and return normally
+ return
+
+
+_file_template = """
+
+
+
+
+
+
+
+
+
+
+
+ %(table)s%(legend)s
+
+
+"""
+
+_styles = """
+ :root {color-scheme: light dark}
+ table.diff {font-family: Menlo, Consolas, Monaco, Liberation Mono, Lucida Console, monospace; border:medium}
+ .diff_header {background-color:#e0e0e0}
+ td.diff_header {text-align:right}
+ .diff_next {background-color:#c0c0c0}
+ .diff_add {background-color:palegreen}
+ .diff_chg {background-color:#ffff77}
+ .diff_sub {background-color:#ffaaaa}
+
+ @media (prefers-color-scheme: dark) {
+ .diff_header {background-color:#666}
+ .diff_next {background-color:#393939}
+ .diff_add {background-color:darkgreen}
+ .diff_chg {background-color:#847415}
+ .diff_sub {background-color:darkred}
+ }"""
+
+_table_template = """
+
+
+
+ %(header_row)s
+
+%(data_rows)s
+
"""
+
+_legend = """
+
+ | Legends |
+
+ | Colors |
+ | Added |
+ | Changed |
+ | Deleted |
+ |
+
+ | Links |
+ | (f)irst change |
+ | (n)ext change |
+ | (t)op |
+ |
+
"""
+
+class HtmlDiff(object):
+ """For producing HTML side by side comparison with change highlights.
+
+ This class can be used to create an HTML table (or a complete HTML file
+ containing the table) showing a side by side, line by line comparison
+ of text with inter-line and intra-line change highlights. The table can
+ be generated in either full or contextual difference mode.
+
+ The following methods are provided for HTML generation:
+
+ make_table -- generates HTML for a single side by side table
+ make_file -- generates complete HTML file with a single side by side table
+
+ See tools/scripts/diff.py for an example usage of this class.
+ """
+
+ _file_template = _file_template
+ _styles = _styles
+ _table_template = _table_template
+ _legend = _legend
+ _default_prefix = 0
+
+ def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None,
+ charjunk=IS_CHARACTER_JUNK):
+ """HtmlDiff instance initializer
+
+ Arguments:
+ tabsize -- tab stop spacing, defaults to 8.
+ wrapcolumn -- column number where lines are broken and wrapped,
+ defaults to None where lines are not wrapped.
+ linejunk,charjunk -- keyword arguments passed into ndiff() (used by
+ HtmlDiff() to generate the side by side HTML differences). See
+ ndiff() documentation for argument default values and descriptions.
+ """
+ self._tabsize = tabsize
+ self._wrapcolumn = wrapcolumn
+ self._linejunk = linejunk
+ self._charjunk = charjunk
+
+ def make_file(self, fromlines, tolines, fromdesc='', todesc='',
+ context=False, numlines=5, *, charset='utf-8'):
+ """Returns HTML file of side by side comparison with change highlights
+
+ Arguments:
+ fromlines -- list of "from" lines
+ tolines -- list of "to" lines
+ fromdesc -- "from" file column header string
+ todesc -- "to" file column header string
+ context -- set to True for contextual differences (defaults to False
+ which shows full differences).
+ numlines -- number of context lines. When context is set True,
+ controls number of lines displayed before and after the change.
+ When context is False, controls the number of lines to place
+ the "next" link anchors before the next change (so click of
+ "next" link jumps to just before the change).
+ charset -- charset of the HTML document
+ """
+
+ return (self._file_template % dict(
+ styles=self._styles,
+ legend=self._legend,
+ table=self.make_table(fromlines, tolines, fromdesc, todesc,
+ context=context, numlines=numlines),
+ charset=charset
+ )).encode(charset, 'xmlcharrefreplace').decode(charset)
+
+ def _tab_newline_replace(self,fromlines,tolines):
+ """Returns from/to line lists with tabs expanded and newlines removed.
+
+ Instead of tab characters being replaced by the number of spaces
+ needed to fill in to the next tab stop, this function will fill
+ the space with tab characters. This is done so that the difference
+ algorithms can identify changes in a file when tabs are replaced by
+ spaces and vice versa. At the end of the HTML generation, the tab
+ characters will be replaced with a nonbreakable space.
+ """
+ def expand_tabs(line):
+ # hide real spaces
+ line = line.replace(' ','\0')
+ # expand tabs into spaces
+ line = line.expandtabs(self._tabsize)
+ # replace spaces from expanded tabs back into tab characters
+ # (we'll replace them with markup after we do differencing)
+ line = line.replace(' ','\t')
+ return line.replace('\0',' ').rstrip('\n')
+ fromlines = [expand_tabs(line) for line in fromlines]
+ tolines = [expand_tabs(line) for line in tolines]
+ return fromlines,tolines
+
+ def _split_line(self,data_list,line_num,text):
+ """Builds list of text lines by splitting text lines at wrap point
+
+ This function will determine if the input text line needs to be
+ wrapped (split) into separate lines. If so, the first wrap point
+ will be determined and the first line appended to the output
+ text line list. This function is used recursively to handle
+ the second part of the split line to further split it.
+ """
+ # if blank line or context separator, just add it to the output list
+ if not line_num:
+ data_list.append((line_num,text))
+ return
+
+ # if line text doesn't need wrapping, just add it to the output list
+ size = len(text)
+ max = self._wrapcolumn
+ if (size <= max) or ((size -(text.count('\0')*3)) <= max):
+ data_list.append((line_num,text))
+ return
+
+ # scan text looking for the wrap point, keeping track if the wrap
+ # point is inside markers
+ i = 0
+ n = 0
+ mark = ''
+ while n < max and i < size:
+ if text[i] == '\0':
+ i += 1
+ mark = text[i]
+ i += 1
+ elif text[i] == '\1':
+ i += 1
+ mark = ''
+ else:
+ i += 1
+ n += 1
+
+ # wrap point is inside text, break it up into separate lines
+ line1 = text[:i]
+ line2 = text[i:]
+
+ # if wrap point is inside markers, place end marker at end of first
+ # line and start marker at beginning of second line because each
+ # line will have its own table tag markup around it.
+ if mark:
+ line1 = line1 + '\1'
+ line2 = '\0' + mark + line2
+
+ # tack on first line onto the output list
+ data_list.append((line_num,line1))
+
+ # use this routine again to wrap the remaining text
+ self._split_line(data_list,'>',line2)
+
+ def _line_wrapper(self,diffs):
+ """Returns iterator that splits (wraps) mdiff text lines"""
+
+ # pull from/to data and flags from mdiff iterator
+ for fromdata,todata,flag in diffs:
+ # check for context separators and pass them through
+ if flag is None:
+ yield fromdata,todata,flag
+ continue
+ (fromline,fromtext),(toline,totext) = fromdata,todata
+ # for each from/to line split it at the wrap column to form
+ # list of text lines.
+ fromlist,tolist = [],[]
+ self._split_line(fromlist,fromline,fromtext)
+ self._split_line(tolist,toline,totext)
+ # yield from/to line in pairs inserting blank lines as
+ # necessary when one side has more wrapped lines
+ while fromlist or tolist:
+ if fromlist:
+ fromdata = fromlist.pop(0)
+ else:
+ fromdata = ('',' ')
+ if tolist:
+ todata = tolist.pop(0)
+ else:
+ todata = ('',' ')
+ yield fromdata,todata,flag
+
+ def _collect_lines(self,diffs):
+ """Collects mdiff output into separate lists
+
+ Before storing the mdiff from/to data into a list, it is converted
+ into a single line of text with HTML markup.
+ """
+
+ fromlist,tolist,flaglist = [],[],[]
+ # pull from/to data and flags from mdiff style iterator
+ for fromdata,todata,flag in diffs:
+ try:
+ # store HTML markup of the lines into the lists
+ fromlist.append(self._format_line(0,flag,*fromdata))
+ tolist.append(self._format_line(1,flag,*todata))
+ except TypeError:
+ # exceptions occur for lines where context separators go
+ fromlist.append(None)
+ tolist.append(None)
+ flaglist.append(flag)
+ return fromlist,tolist,flaglist
+
+ def _format_line(self,side,flag,linenum,text):
+ """Returns HTML markup of "from" / "to" text lines
+
+ side -- 0 or 1 indicating "from" or "to" text
+ flag -- indicates if difference on line
+ linenum -- line number (used for line number column)
+ text -- line text to be marked up
+ """
+ try:
+ linenum = '%d' % linenum
+ id = ' id="%s%s"' % (self._prefix[side],linenum)
+ except TypeError:
+ # handle blank lines where linenum is '>' or ''
+ id = ''
+ # replace those things that would get confused with HTML symbols
+ text=text.replace("&","&").replace(">",">").replace("<","<")
+
+ # make space non-breakable so they don't get compressed or line wrapped
+ text = text.replace(' ',' ').rstrip()
+
+ return '%s | ' \
+ % (id,linenum,text)
+
+ def _make_prefix(self):
+ """Create unique anchor prefixes"""
+
+ # Generate a unique anchor prefix so multiple tables
+ # can exist on the same HTML page without conflicts.
+ fromprefix = "from%d_" % HtmlDiff._default_prefix
+ toprefix = "to%d_" % HtmlDiff._default_prefix
+ HtmlDiff._default_prefix += 1
+ # store prefixes so line format method has access
+ self._prefix = [fromprefix,toprefix]
+
+ def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):
+ """Makes list of "next" links"""
+
+ # all anchor names will be generated using the unique "to" prefix
+ toprefix = self._prefix[1]
+
+ # process change flags, generating middle column of next anchors/links
+ next_id = ['']*len(flaglist)
+ next_href = ['']*len(flaglist)
+ num_chg, in_change = 0, False
+ last = 0
+ for i,flag in enumerate(flaglist):
+ if flag:
+ if not in_change:
+ in_change = True
+ last = i
+ # at the beginning of a change, drop an anchor a few lines
+ # (the context lines) before the change for the previous
+ # link
+ i = max([0,i-numlines])
+ next_id[i] = ' id="difflib_chg_%s_%d"' % (toprefix,num_chg)
+ # at the beginning of a change, drop a link to the next
+ # change
+ num_chg += 1
+ next_href[last] = 'n' % (
+ toprefix,num_chg)
+ else:
+ in_change = False
+ # check for cases where there is no content to avoid exceptions
+ if not flaglist:
+ flaglist = [False]
+ next_id = ['']
+ next_href = ['']
+ last = 0
+ if context:
+ fromlist = [' | No Differences Found | ']
+ tolist = fromlist
+ else:
+ fromlist = tolist = [' | Empty File | ']
+ # if not a change on first line, drop a link
+ if not flaglist[0]:
+ next_href[0] = 'f' % toprefix
+ # redo the last link to link to the top
+ next_href[last] = 't' % (toprefix)
+
+ return fromlist,tolist,flaglist,next_href,next_id
+
+ def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,
+ numlines=5):
+ """Returns HTML table of side by side comparison with change highlights
+
+ Arguments:
+ fromlines -- list of "from" lines
+ tolines -- list of "to" lines
+ fromdesc -- "from" file column header string
+ todesc -- "to" file column header string
+ context -- set to True for contextual differences (defaults to False
+ which shows full differences).
+ numlines -- number of context lines. When context is set True,
+ controls number of lines displayed before and after the change.
+ When context is False, controls the number of lines to place
+ the "next" link anchors before the next change (so click of
+ "next" link jumps to just before the change).
+ """
+
+ # make unique anchor prefixes so that multiple tables may exist
+ # on the same page without conflict.
+ self._make_prefix()
+
+ # change tabs to spaces before it gets more difficult after we insert
+ # markup
+ fromlines,tolines = self._tab_newline_replace(fromlines,tolines)
+
+ # create diffs iterator which generates side by side from/to data
+ if context:
+ context_lines = numlines
+ else:
+ context_lines = None
+ diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,
+ charjunk=self._charjunk)
+
+ # set up iterator to wrap lines that exceed desired width
+ if self._wrapcolumn:
+ diffs = self._line_wrapper(diffs)
+
+ # collect up from/to lines and flags into lists (also format the lines)
+ fromlist,tolist,flaglist = self._collect_lines(diffs)
+
+ # process change flags, generating middle column of next anchors/links
+ fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(
+ fromlist,tolist,flaglist,context,numlines)
+
+ s = []
+ fmt = ' | %s | %s' + \
+ '%s | %s
\n'
+ for i in range(len(flaglist)):
+ if flaglist[i] is None:
+ # mdiff yields None on separator lines skip the bogus ones
+ # generated for the first line
+ if i > 0:
+ s.append(' \n \n')
+ else:
+ s.append( fmt % (next_id[i],next_href[i],fromlist[i],
+ next_href[i],tolist[i]))
+ if fromdesc or todesc:
+ header_row = '%s%s%s%s
' % (
+ '
| ',
+ '' % fromdesc,
+ '
| ',
+ '' % todesc)
+ else:
+ header_row = ''
+
+ table = self._table_template % dict(
+ data_rows=''.join(s),
+ header_row=header_row,
+ prefix=self._prefix[1])
+
+ return table.replace('\0+',''). \
+ replace('\0-',''). \
+ replace('\0^',''). \
+ replace('\1',''). \
+ replace('\t',' ')
+
+
+def restore(delta, which):
+ r"""
+ Generate one of the two sequences that generated a delta.
+
+ Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
+ lines originating from file 1 or 2 (parameter `which`), stripping off line
+ prefixes.
+
+ Examples:
+
+ >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
+ ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
+ >>> diff = list(diff)
+ >>> print(''.join(restore(diff, 1)), end="")
+ one
+ two
+ three
+ >>> print(''.join(restore(diff, 2)), end="")
+ ore
+ tree
+ emu
+ """
+ try:
+ tag = {1: "- ", 2: "+ "}[int(which)]
+ except KeyError:
+ raise ValueError('unknown delta choice (must be 1 or 2): %r'
+ % which) from None
+ prefixes = (" ", tag)
+ for line in delta:
+ if line[:2] in prefixes:
+ yield line[2:]
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/dis.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/dis.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6d2c1386dd7858db7aa00becfc690e7d38146da
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/dis.py
@@ -0,0 +1,1157 @@
+"""Disassembler of Python byte code into mnemonics."""
+
+import sys
+import types
+import collections
+import io
+
+from opcode import *
+from opcode import (
+ __all__ as _opcodes_all,
+ _cache_format,
+ _inline_cache_entries,
+ _nb_ops,
+ _common_constants,
+ _intrinsic_1_descs,
+ _intrinsic_2_descs,
+ _special_method_names,
+ _specializations,
+ _specialized_opmap,
+)
+
+from _opcode import get_executor
+
+__all__ = ["code_info", "dis", "disassemble", "distb", "disco",
+ "findlinestarts", "findlabels", "show_code",
+ "get_instructions", "Instruction", "Bytecode"] + _opcodes_all
+del _opcodes_all
+
+_have_code = (types.MethodType, types.FunctionType, types.CodeType,
+ classmethod, staticmethod, type)
+
+CONVERT_VALUE = opmap['CONVERT_VALUE']
+
+SET_FUNCTION_ATTRIBUTE = opmap['SET_FUNCTION_ATTRIBUTE']
+FUNCTION_ATTR_FLAGS = ('defaults', 'kwdefaults', 'annotations', 'closure', 'annotate')
+
+ENTER_EXECUTOR = opmap['ENTER_EXECUTOR']
+LOAD_GLOBAL = opmap['LOAD_GLOBAL']
+LOAD_SMALL_INT = opmap['LOAD_SMALL_INT']
+BINARY_OP = opmap['BINARY_OP']
+JUMP_BACKWARD = opmap['JUMP_BACKWARD']
+FOR_ITER = opmap['FOR_ITER']
+SEND = opmap['SEND']
+LOAD_ATTR = opmap['LOAD_ATTR']
+LOAD_SUPER_ATTR = opmap['LOAD_SUPER_ATTR']
+CALL_INTRINSIC_1 = opmap['CALL_INTRINSIC_1']
+CALL_INTRINSIC_2 = opmap['CALL_INTRINSIC_2']
+LOAD_COMMON_CONSTANT = opmap['LOAD_COMMON_CONSTANT']
+LOAD_SPECIAL = opmap['LOAD_SPECIAL']
+LOAD_FAST_LOAD_FAST = opmap['LOAD_FAST_LOAD_FAST']
+LOAD_FAST_BORROW_LOAD_FAST_BORROW = opmap['LOAD_FAST_BORROW_LOAD_FAST_BORROW']
+STORE_FAST_LOAD_FAST = opmap['STORE_FAST_LOAD_FAST']
+STORE_FAST_STORE_FAST = opmap['STORE_FAST_STORE_FAST']
+IS_OP = opmap['IS_OP']
+CONTAINS_OP = opmap['CONTAINS_OP']
+END_ASYNC_FOR = opmap['END_ASYNC_FOR']
+
+CACHE = opmap["CACHE"]
+
+_all_opname = list(opname)
+_all_opmap = dict(opmap)
+for name, op in _specialized_opmap.items():
+ # fill opname and opmap
+ assert op < len(_all_opname)
+ _all_opname[op] = name
+ _all_opmap[name] = op
+
+deoptmap = {
+ specialized: base for base, family in _specializations.items() for specialized in family
+}
+
+def _try_compile(source, name):
+ """Attempts to compile the given source, first as an expression and
+ then as a statement if the first approach fails.
+
+ Utility function to accept strings in functions that otherwise
+ expect code objects
+ """
+ try:
+ return compile(source, name, 'eval')
+ except SyntaxError:
+ pass
+ return compile(source, name, 'exec')
+
+def dis(x=None, *, file=None, depth=None, show_caches=False, adaptive=False,
+ show_offsets=False, show_positions=False):
+ """Disassemble classes, methods, functions, and other compiled objects.
+
+ With no argument, disassemble the last traceback.
+
+ Compiled objects currently include generator objects, async generator
+ objects, and coroutine objects, all of which store their code object
+ in a special attribute.
+ """
+ if x is None:
+ distb(file=file, show_caches=show_caches, adaptive=adaptive,
+ show_offsets=show_offsets, show_positions=show_positions)
+ return
+ # Extract functions from methods.
+ if hasattr(x, '__func__'):
+ x = x.__func__
+ # Extract compiled code objects from...
+ if hasattr(x, '__code__'): # ...a function, or
+ x = x.__code__
+ elif hasattr(x, 'gi_code'): #...a generator object, or
+ x = x.gi_code
+ elif hasattr(x, 'ag_code'): #...an asynchronous generator object, or
+ x = x.ag_code
+ elif hasattr(x, 'cr_code'): #...a coroutine.
+ x = x.cr_code
+ # Perform the disassembly.
+ if hasattr(x, '__dict__'): # Class or module
+ items = sorted(x.__dict__.items())
+ for name, x1 in items:
+ if isinstance(x1, _have_code):
+ print("Disassembly of %s:" % name, file=file)
+ try:
+ dis(x1, file=file, depth=depth, show_caches=show_caches, adaptive=adaptive, show_offsets=show_offsets, show_positions=show_positions)
+ except TypeError as msg:
+ print("Sorry:", msg, file=file)
+ print(file=file)
+ elif hasattr(x, 'co_code'): # Code object
+ _disassemble_recursive(x, file=file, depth=depth, show_caches=show_caches, adaptive=adaptive, show_offsets=show_offsets, show_positions=show_positions)
+ elif isinstance(x, (bytes, bytearray)): # Raw bytecode
+ labels_map = _make_labels_map(x)
+ label_width = 4 + len(str(len(labels_map)))
+ formatter = Formatter(file=file,
+ offset_width=len(str(max(len(x) - 2, 9999))) if show_offsets else 0,
+ label_width=label_width,
+ show_caches=show_caches)
+ arg_resolver = ArgResolver(labels_map=labels_map)
+ _disassemble_bytes(x, arg_resolver=arg_resolver, formatter=formatter)
+ elif isinstance(x, str): # Source code
+ _disassemble_str(x, file=file, depth=depth, show_caches=show_caches, adaptive=adaptive, show_offsets=show_offsets, show_positions=show_positions)
+ else:
+ raise TypeError("don't know how to disassemble %s objects" %
+ type(x).__name__)
+
+def distb(tb=None, *, file=None, show_caches=False, adaptive=False, show_offsets=False, show_positions=False):
+ """Disassemble a traceback (default: last traceback)."""
+ if tb is None:
+ try:
+ if hasattr(sys, 'last_exc'):
+ tb = sys.last_exc.__traceback__
+ else:
+ tb = sys.last_traceback
+ except AttributeError:
+ raise RuntimeError("no last traceback to disassemble") from None
+ while tb.tb_next: tb = tb.tb_next
+ disassemble(tb.tb_frame.f_code, tb.tb_lasti, file=file, show_caches=show_caches, adaptive=adaptive, show_offsets=show_offsets, show_positions=show_positions)
+
+# The inspect module interrogates this dictionary to build its
+# list of CO_* constants. It is also used by pretty_flags to
+# turn the co_flags field into a human readable list.
+COMPILER_FLAG_NAMES = {
+ 1: "OPTIMIZED",
+ 2: "NEWLOCALS",
+ 4: "VARARGS",
+ 8: "VARKEYWORDS",
+ 16: "NESTED",
+ 32: "GENERATOR",
+ 64: "NOFREE",
+ 128: "COROUTINE",
+ 256: "ITERABLE_COROUTINE",
+ 512: "ASYNC_GENERATOR",
+ 0x4000000: "HAS_DOCSTRING",
+ 0x8000000: "METHOD",
+}
+
+def pretty_flags(flags):
+ """Return pretty representation of code flags."""
+ names = []
+ for i in range(32):
+ flag = 1<"
+
+# Sentinel to represent values that cannot be calculated
+UNKNOWN = _Unknown()
+
+def _get_code_object(x):
+ """Helper to handle methods, compiled or raw code objects, and strings."""
+ # Extract functions from methods.
+ if hasattr(x, '__func__'):
+ x = x.__func__
+ # Extract compiled code objects from...
+ if hasattr(x, '__code__'): # ...a function, or
+ x = x.__code__
+ elif hasattr(x, 'gi_code'): #...a generator object, or
+ x = x.gi_code
+ elif hasattr(x, 'ag_code'): #...an asynchronous generator object, or
+ x = x.ag_code
+ elif hasattr(x, 'cr_code'): #...a coroutine.
+ x = x.cr_code
+ # Handle source code.
+ if isinstance(x, str):
+ x = _try_compile(x, "")
+ # By now, if we don't have a code object, we can't disassemble x.
+ if hasattr(x, 'co_code'):
+ return x
+ raise TypeError("don't know how to disassemble %s objects" %
+ type(x).__name__)
+
+def _deoptop(op):
+ name = _all_opname[op]
+ return _all_opmap[deoptmap[name]] if name in deoptmap else op
+
+def _get_code_array(co, adaptive):
+ if adaptive:
+ code = co._co_code_adaptive
+ res = []
+ found = False
+ for i in range(0, len(code), 2):
+ op, arg = code[i], code[i+1]
+ if op == ENTER_EXECUTOR:
+ try:
+ ex = get_executor(co, i)
+ except (ValueError, RuntimeError):
+ ex = None
+
+ if ex:
+ op, arg = ex.get_opcode(), ex.get_oparg()
+ found = True
+
+ res.append(op.to_bytes())
+ res.append(arg.to_bytes())
+ return code if not found else b''.join(res)
+ else:
+ return co.co_code
+
+def code_info(x):
+ """Formatted details of methods, functions, or code."""
+ return _format_code_info(_get_code_object(x))
+
+def _format_code_info(co):
+ lines = []
+ lines.append("Name: %s" % co.co_name)
+ lines.append("Filename: %s" % co.co_filename)
+ lines.append("Argument count: %s" % co.co_argcount)
+ lines.append("Positional-only arguments: %s" % co.co_posonlyargcount)
+ lines.append("Kw-only arguments: %s" % co.co_kwonlyargcount)
+ lines.append("Number of locals: %s" % co.co_nlocals)
+ lines.append("Stack size: %s" % co.co_stacksize)
+ lines.append("Flags: %s" % pretty_flags(co.co_flags))
+ if co.co_consts:
+ lines.append("Constants:")
+ for i_c in enumerate(co.co_consts):
+ lines.append("%4d: %r" % i_c)
+ if co.co_names:
+ lines.append("Names:")
+ for i_n in enumerate(co.co_names):
+ lines.append("%4d: %s" % i_n)
+ if co.co_varnames:
+ lines.append("Variable names:")
+ for i_n in enumerate(co.co_varnames):
+ lines.append("%4d: %s" % i_n)
+ if co.co_freevars:
+ lines.append("Free variables:")
+ for i_n in enumerate(co.co_freevars):
+ lines.append("%4d: %s" % i_n)
+ if co.co_cellvars:
+ lines.append("Cell variables:")
+ for i_n in enumerate(co.co_cellvars):
+ lines.append("%4d: %s" % i_n)
+ return "\n".join(lines)
+
+def show_code(co, *, file=None):
+ """Print details of methods, functions, or code to *file*.
+
+ If *file* is not provided, the output is printed on stdout.
+ """
+ print(code_info(co), file=file)
+
+Positions = collections.namedtuple(
+ 'Positions',
+ [
+ 'lineno',
+ 'end_lineno',
+ 'col_offset',
+ 'end_col_offset',
+ ],
+ defaults=[None] * 4
+)
+
+_Instruction = collections.namedtuple(
+ "_Instruction",
+ [
+ 'opname',
+ 'opcode',
+ 'arg',
+ 'argval',
+ 'argrepr',
+ 'offset',
+ 'start_offset',
+ 'starts_line',
+ 'line_number',
+ 'label',
+ 'positions',
+ 'cache_info',
+ ],
+ defaults=[None, None, None]
+)
+
+_Instruction.opname.__doc__ = "Human readable name for operation"
+_Instruction.opcode.__doc__ = "Numeric code for operation"
+_Instruction.arg.__doc__ = "Numeric argument to operation (if any), otherwise None"
+_Instruction.argval.__doc__ = "Resolved arg value (if known), otherwise same as arg"
+_Instruction.argrepr.__doc__ = "Human readable description of operation argument"
+_Instruction.offset.__doc__ = "Start index of operation within bytecode sequence"
+_Instruction.start_offset.__doc__ = (
+ "Start index of operation within bytecode sequence, including extended args if present; "
+ "otherwise equal to Instruction.offset"
+)
+_Instruction.starts_line.__doc__ = "True if this opcode starts a source line, otherwise False"
+_Instruction.line_number.__doc__ = "source line number associated with this opcode (if any), otherwise None"
+_Instruction.label.__doc__ = "A label (int > 0) if this instruction is a jump target, otherwise None"
+_Instruction.positions.__doc__ = "dis.Positions object holding the span of source code covered by this instruction"
+_Instruction.cache_info.__doc__ = "list of (name, size, data), one for each cache entry of the instruction"
+
+_ExceptionTableEntryBase = collections.namedtuple("_ExceptionTableEntryBase",
+ "start end target depth lasti")
+
+class _ExceptionTableEntry(_ExceptionTableEntryBase):
+ pass
+
+_OPNAME_WIDTH = 20
+_OPARG_WIDTH = 5
+
+def _get_cache_size(opname):
+ return _inline_cache_entries.get(opname, 0)
+
+def _get_jump_target(op, arg, offset):
+ """Gets the bytecode offset of the jump target if this is a jump instruction.
+
+ Otherwise return None.
+ """
+ deop = _deoptop(op)
+ caches = _get_cache_size(_all_opname[deop])
+ if deop in hasjrel:
+ if _is_backward_jump(deop):
+ arg = -arg
+ target = offset + 2 + arg*2
+ target += 2 * caches
+ elif deop in hasjabs:
+ target = arg*2
+ else:
+ target = None
+ return target
+
+class Instruction(_Instruction):
+ """Details for a bytecode operation.
+
+ Defined fields:
+ opname - human readable name for operation
+ opcode - numeric code for operation
+ arg - numeric argument to operation (if any), otherwise None
+ argval - resolved arg value (if known), otherwise same as arg
+ argrepr - human readable description of operation argument
+ offset - start index of operation within bytecode sequence
+ start_offset - start index of operation within bytecode sequence including extended args if present;
+ otherwise equal to Instruction.offset
+ starts_line - True if this opcode starts a source line, otherwise False
+ line_number - source line number associated with this opcode (if any), otherwise None
+ label - A label if this instruction is a jump target, otherwise None
+ positions - Optional dis.Positions object holding the span of source code
+ covered by this instruction
+ cache_info - information about the format and content of the instruction's cache
+ entries (if any)
+ """
+
+ @staticmethod
+ def make(
+ opname, arg, argval, argrepr, offset, start_offset, starts_line,
+ line_number, label=None, positions=None, cache_info=None
+ ):
+ return Instruction(opname, _all_opmap[opname], arg, argval, argrepr, offset,
+ start_offset, starts_line, line_number, label, positions, cache_info)
+
+ @property
+ def oparg(self):
+ """Alias for Instruction.arg."""
+ return self.arg
+
+ @property
+ def baseopcode(self):
+ """Numeric code for the base operation if operation is specialized.
+
+ Otherwise equal to Instruction.opcode.
+ """
+ return _deoptop(self.opcode)
+
+ @property
+ def baseopname(self):
+ """Human readable name for the base operation if operation is specialized.
+
+ Otherwise equal to Instruction.opname.
+ """
+ return opname[self.baseopcode]
+
+ @property
+ def cache_offset(self):
+ """Start index of the cache entries following the operation."""
+ return self.offset + 2
+
+ @property
+ def end_offset(self):
+ """End index of the cache entries following the operation."""
+ return self.cache_offset + _get_cache_size(_all_opname[self.opcode])*2
+
+ @property
+ def jump_target(self):
+ """Bytecode index of the jump target if this is a jump operation.
+
+ Otherwise return None.
+ """
+ return _get_jump_target(self.opcode, self.arg, self.offset)
+
+ @property
+ def is_jump_target(self):
+ """True if other code jumps to here, otherwise False"""
+ return self.label is not None
+
+ def __str__(self):
+ output = io.StringIO()
+ formatter = Formatter(file=output)
+ formatter.print_instruction(self, False)
+ return output.getvalue()
+
+
+class Formatter:
+
+ def __init__(self, file=None, lineno_width=0, offset_width=0, label_width=0,
+ line_offset=0, show_caches=False, *, show_positions=False):
+ """Create a Formatter
+
+ *file* where to write the output
+ *lineno_width* sets the width of the source location field (0 omits it).
+ Should be large enough for a line number or full positions (depending
+ on the value of *show_positions*).
+ *offset_width* sets the width of the instruction offset field
+ *label_width* sets the width of the label field
+ *show_caches* is a boolean indicating whether to display cache lines
+ *show_positions* is a boolean indicating whether full positions should
+ be reported instead of only the line numbers.
+ """
+ self.file = file
+ self.lineno_width = lineno_width
+ self.offset_width = offset_width
+ self.label_width = label_width
+ self.show_caches = show_caches
+ self.show_positions = show_positions
+
+ def print_instruction(self, instr, mark_as_current=False):
+ self.print_instruction_line(instr, mark_as_current)
+ if self.show_caches and instr.cache_info:
+ offset = instr.offset
+ for name, size, data in instr.cache_info:
+ for i in range(size):
+ offset += 2
+ # Only show the fancy argrepr for a CACHE instruction when it's
+ # the first entry for a particular cache value:
+ if i == 0:
+ argrepr = f"{name}: {int.from_bytes(data, sys.byteorder)}"
+ else:
+ argrepr = ""
+ self.print_instruction_line(
+ Instruction("CACHE", CACHE, 0, None, argrepr, offset, offset,
+ False, None, None, instr.positions),
+ False)
+
+ def print_instruction_line(self, instr, mark_as_current):
+ """Format instruction details for inclusion in disassembly output."""
+ lineno_width = self.lineno_width
+ offset_width = self.offset_width
+ label_width = self.label_width
+
+ new_source_line = (lineno_width > 0 and
+ instr.starts_line and
+ instr.offset > 0)
+ if new_source_line:
+ print(file=self.file)
+
+ fields = []
+ # Column: Source code locations information
+ if lineno_width:
+ if self.show_positions:
+ # reporting positions instead of just line numbers
+ if instr_positions := instr.positions:
+ if all(p is None for p in instr_positions):
+ positions_str = _NO_LINENO
+ else:
+ ps = tuple('?' if p is None else p for p in instr_positions)
+ positions_str = f"{ps[0]}:{ps[2]}-{ps[1]}:{ps[3]}"
+ fields.append(f'{positions_str:{lineno_width}}')
+ else:
+ fields.append(' ' * lineno_width)
+ else:
+ if instr.starts_line:
+ lineno_fmt = "%%%dd" if instr.line_number is not None else "%%%ds"
+ lineno_fmt = lineno_fmt % lineno_width
+ lineno = _NO_LINENO if instr.line_number is None else instr.line_number
+ fields.append(lineno_fmt % lineno)
+ else:
+ fields.append(' ' * lineno_width)
+ # Column: Label
+ if instr.label is not None:
+ lbl = f"L{instr.label}:"
+ fields.append(f"{lbl:>{label_width}}")
+ else:
+ fields.append(' ' * label_width)
+ # Column: Instruction offset from start of code sequence
+ if offset_width > 0:
+ fields.append(f"{repr(instr.offset):>{offset_width}} ")
+ # Column: Current instruction indicator
+ if mark_as_current:
+ fields.append('-->')
+ else:
+ fields.append(' ')
+ # Column: Opcode name
+ fields.append(instr.opname.ljust(_OPNAME_WIDTH))
+ # Column: Opcode argument
+ if instr.arg is not None:
+ arg = repr(instr.arg)
+ # If opname is longer than _OPNAME_WIDTH, we allow it to overflow into
+ # the space reserved for oparg. This results in fewer misaligned opargs
+ # in the disassembly output.
+ opname_excess = max(0, len(instr.opname) - _OPNAME_WIDTH)
+ fields.append(repr(instr.arg).rjust(_OPARG_WIDTH - opname_excess))
+ # Column: Opcode argument details
+ if instr.argrepr:
+ fields.append('(' + instr.argrepr + ')')
+ print(' '.join(fields).rstrip(), file=self.file)
+
+ def print_exception_table(self, exception_entries):
+ file = self.file
+ if exception_entries:
+ print("ExceptionTable:", file=file)
+ for entry in exception_entries:
+ lasti = " lasti" if entry.lasti else ""
+ start = entry.start_label
+ end = entry.end_label
+ target = entry.target_label
+ print(f" L{start} to L{end} -> L{target} [{entry.depth}]{lasti}", file=file)
+
+
+class ArgResolver:
+ def __init__(self, co_consts=None, names=None, varname_from_oparg=None, labels_map=None):
+ self.co_consts = co_consts
+ self.names = names
+ self.varname_from_oparg = varname_from_oparg
+ self.labels_map = labels_map or {}
+
+ def offset_from_jump_arg(self, op, arg, offset):
+ deop = _deoptop(op)
+ if deop in hasjabs:
+ return arg * 2
+ elif deop in hasjrel:
+ signed_arg = -arg if _is_backward_jump(deop) else arg
+ argval = offset + 2 + signed_arg*2
+ caches = _get_cache_size(_all_opname[deop])
+ argval += 2 * caches
+ return argval
+ return None
+
+ def get_label_for_offset(self, offset):
+ return self.labels_map.get(offset, None)
+
+ def get_argval_argrepr(self, op, arg, offset):
+ get_name = None if self.names is None else self.names.__getitem__
+ argval = None
+ argrepr = ''
+ deop = _deoptop(op)
+ if arg is not None:
+ # Set argval to the dereferenced value of the argument when
+ # available, and argrepr to the string representation of argval.
+ # _disassemble_bytes needs the string repr of the
+ # raw name index for LOAD_GLOBAL, LOAD_CONST, etc.
+ argval = arg
+ if deop in hasconst:
+ argval, argrepr = _get_const_info(deop, arg, self.co_consts)
+ elif deop in hasname:
+ if deop == LOAD_GLOBAL:
+ argval, argrepr = _get_name_info(arg//2, get_name)
+ if (arg & 1) and argrepr:
+ argrepr = f"{argrepr} + NULL"
+ elif deop == LOAD_ATTR:
+ argval, argrepr = _get_name_info(arg//2, get_name)
+ if (arg & 1) and argrepr:
+ argrepr = f"{argrepr} + NULL|self"
+ elif deop == LOAD_SUPER_ATTR:
+ argval, argrepr = _get_name_info(arg//4, get_name)
+ if (arg & 1) and argrepr:
+ argrepr = f"{argrepr} + NULL|self"
+ else:
+ argval, argrepr = _get_name_info(arg, get_name)
+ elif deop in hasjump or deop in hasexc:
+ argval = self.offset_from_jump_arg(op, arg, offset)
+ lbl = self.get_label_for_offset(argval)
+ assert lbl is not None
+ preposition = "from" if deop == END_ASYNC_FOR else "to"
+ argrepr = f"{preposition} L{lbl}"
+ elif deop in (LOAD_FAST_LOAD_FAST, LOAD_FAST_BORROW_LOAD_FAST_BORROW, STORE_FAST_LOAD_FAST, STORE_FAST_STORE_FAST):
+ arg1 = arg >> 4
+ arg2 = arg & 15
+ val1, argrepr1 = _get_name_info(arg1, self.varname_from_oparg)
+ val2, argrepr2 = _get_name_info(arg2, self.varname_from_oparg)
+ argrepr = argrepr1 + ", " + argrepr2
+ argval = val1, val2
+ elif deop in haslocal or deop in hasfree:
+ argval, argrepr = _get_name_info(arg, self.varname_from_oparg)
+ elif deop in hascompare:
+ argval = cmp_op[arg >> 5]
+ argrepr = argval
+ if arg & 16:
+ argrepr = f"bool({argrepr})"
+ elif deop == CONVERT_VALUE:
+ argval = (None, str, repr, ascii)[arg]
+ argrepr = ('', 'str', 'repr', 'ascii')[arg]
+ elif deop == SET_FUNCTION_ATTRIBUTE:
+ argrepr = ', '.join(s for i, s in enumerate(FUNCTION_ATTR_FLAGS)
+ if arg & (1<> 1
+ lasti = bool(dl&1)
+ entries.append(_ExceptionTableEntry(start, end, target, depth, lasti))
+ except StopIteration:
+ return entries
+
+def _is_backward_jump(op):
+ return opname[op] in ('JUMP_BACKWARD',
+ 'JUMP_BACKWARD_NO_INTERRUPT',
+ 'END_ASYNC_FOR') # Not really a jump, but it has a "target"
+
+def _get_instructions_bytes(code, linestarts=None, line_offset=0, co_positions=None,
+ original_code=None, arg_resolver=None):
+ """Iterate over the instructions in a bytecode string.
+
+ Generates a sequence of Instruction namedtuples giving the details of each
+ opcode.
+
+ """
+ # Use the basic, unadaptive code for finding labels and actually walking the
+ # bytecode, since replacements like ENTER_EXECUTOR and INSTRUMENTED_* can
+ # mess that logic up pretty badly:
+ original_code = original_code or code
+ co_positions = co_positions or iter(())
+
+ starts_line = False
+ local_line_number = None
+ line_number = None
+ for offset, start_offset, op, arg in _unpack_opargs(original_code):
+ if linestarts is not None:
+ starts_line = offset in linestarts
+ if starts_line:
+ local_line_number = linestarts[offset]
+ if local_line_number is not None:
+ line_number = local_line_number + line_offset
+ else:
+ line_number = None
+ positions = Positions(*next(co_positions, ()))
+ deop = _deoptop(op)
+ op = code[offset]
+
+ if arg_resolver:
+ argval, argrepr = arg_resolver.get_argval_argrepr(op, arg, offset)
+ else:
+ argval, argrepr = arg, repr(arg)
+
+ caches = _get_cache_size(_all_opname[deop])
+ # Advance the co_positions iterator:
+ for _ in range(caches):
+ next(co_positions, ())
+
+ if caches:
+ cache_info = []
+ cache_offset = offset
+ for name, size in _cache_format[opname[deop]].items():
+ data = code[cache_offset + 2: cache_offset + 2 + 2 * size]
+ cache_offset += size * 2
+ cache_info.append((name, size, data))
+ else:
+ cache_info = None
+
+ label = arg_resolver.get_label_for_offset(offset) if arg_resolver else None
+ yield Instruction(_all_opname[op], op, arg, argval, argrepr,
+ offset, start_offset, starts_line, line_number,
+ label, positions, cache_info)
+
+
+def disassemble(co, lasti=-1, *, file=None, show_caches=False, adaptive=False,
+ show_offsets=False, show_positions=False):
+ """Disassemble a code object."""
+ linestarts = dict(findlinestarts(co))
+ exception_entries = _parse_exception_table(co)
+ if show_positions:
+ lineno_width = _get_positions_width(co)
+ else:
+ lineno_width = _get_lineno_width(linestarts)
+ labels_map = _make_labels_map(co.co_code, exception_entries=exception_entries)
+ label_width = 4 + len(str(len(labels_map)))
+ formatter = Formatter(file=file,
+ lineno_width=lineno_width,
+ offset_width=len(str(max(len(co.co_code) - 2, 9999))) if show_offsets else 0,
+ label_width=label_width,
+ show_caches=show_caches,
+ show_positions=show_positions)
+ arg_resolver = ArgResolver(co_consts=co.co_consts,
+ names=co.co_names,
+ varname_from_oparg=co._varname_from_oparg,
+ labels_map=labels_map)
+ _disassemble_bytes(_get_code_array(co, adaptive), lasti, linestarts,
+ exception_entries=exception_entries, co_positions=co.co_positions(),
+ original_code=co.co_code, arg_resolver=arg_resolver, formatter=formatter)
+
+def _disassemble_recursive(co, *, file=None, depth=None, show_caches=False, adaptive=False, show_offsets=False, show_positions=False):
+ disassemble(co, file=file, show_caches=show_caches, adaptive=adaptive, show_offsets=show_offsets, show_positions=show_positions)
+ if depth is None or depth > 0:
+ if depth is not None:
+ depth = depth - 1
+ for x in co.co_consts:
+ if hasattr(x, 'co_code'):
+ print(file=file)
+ print("Disassembly of %r:" % (x,), file=file)
+ _disassemble_recursive(
+ x, file=file, depth=depth, show_caches=show_caches,
+ adaptive=adaptive, show_offsets=show_offsets, show_positions=show_positions
+ )
+
+
+def _make_labels_map(original_code, exception_entries=()):
+ jump_targets = set(findlabels(original_code))
+ labels = set(jump_targets)
+ for start, end, target, _, _ in exception_entries:
+ labels.add(start)
+ labels.add(end)
+ labels.add(target)
+ labels = sorted(labels)
+ labels_map = {offset: i+1 for (i, offset) in enumerate(sorted(labels))}
+ for e in exception_entries:
+ e.start_label = labels_map[e.start]
+ e.end_label = labels_map[e.end]
+ e.target_label = labels_map[e.target]
+ return labels_map
+
+_NO_LINENO = ' --'
+
+def _get_lineno_width(linestarts):
+ if linestarts is None:
+ return 0
+ maxlineno = max(filter(None, linestarts.values()), default=-1)
+ if maxlineno == -1:
+ # Omit the line number column entirely if we have no line number info
+ return 0
+ lineno_width = max(3, len(str(maxlineno)))
+ if lineno_width < len(_NO_LINENO) and None in linestarts.values():
+ lineno_width = len(_NO_LINENO)
+ return lineno_width
+
+def _get_positions_width(code):
+ # Positions are formatted as 'LINE:COL-ENDLINE:ENDCOL ' (note trailing space).
+ # A missing component appears as '?', and when all components are None, we
+ # render '_NO_LINENO'. thus the minimum width is 1 + len(_NO_LINENO).
+ #
+ # If all values are missing, positions are not printed (i.e. positions_width = 0).
+ has_value = False
+ values_width = 0
+ for positions in code.co_positions():
+ has_value |= any(isinstance(p, int) for p in positions)
+ width = sum(1 if p is None else len(str(p)) for p in positions)
+ values_width = max(width, values_width)
+ if has_value:
+ # 3 = number of separators in a normal format
+ return 1 + max(len(_NO_LINENO), 3 + values_width)
+ return 0
+
+def _disassemble_bytes(code, lasti=-1, linestarts=None,
+ *, line_offset=0, exception_entries=(),
+ co_positions=None, original_code=None,
+ arg_resolver=None, formatter=None):
+
+ assert formatter is not None
+ assert arg_resolver is not None
+
+ instrs = _get_instructions_bytes(code, linestarts=linestarts,
+ line_offset=line_offset,
+ co_positions=co_positions,
+ original_code=original_code,
+ arg_resolver=arg_resolver)
+
+ print_instructions(instrs, exception_entries, formatter, lasti=lasti)
+
+
+def print_instructions(instrs, exception_entries, formatter, lasti=-1):
+ for instr in instrs:
+ # Each CACHE takes 2 bytes
+ is_current_instr = instr.offset <= lasti \
+ <= instr.offset + 2 * _get_cache_size(_all_opname[_deoptop(instr.opcode)])
+ formatter.print_instruction(instr, is_current_instr)
+
+ formatter.print_exception_table(exception_entries)
+
+def _disassemble_str(source, **kwargs):
+ """Compile the source string, then disassemble the code object."""
+ _disassemble_recursive(_try_compile(source, ''), **kwargs)
+
+disco = disassemble # XXX For backwards compatibility
+
+
+# Rely on C `int` being 32 bits for oparg
+_INT_BITS = 32
+# Value for c int when it overflows
+_INT_OVERFLOW = 2 ** (_INT_BITS - 1)
+
+def _unpack_opargs(code):
+ extended_arg = 0
+ extended_args_offset = 0 # Number of EXTENDED_ARG instructions preceding the current instruction
+ caches = 0
+ for i in range(0, len(code), 2):
+ # Skip inline CACHE entries:
+ if caches:
+ caches -= 1
+ continue
+ op = code[i]
+ deop = _deoptop(op)
+ caches = _get_cache_size(_all_opname[deop])
+ if deop in hasarg:
+ arg = code[i+1] | extended_arg
+ extended_arg = (arg << 8) if deop == EXTENDED_ARG else 0
+ # The oparg is stored as a signed integer
+ # If the value exceeds its upper limit, it will overflow and wrap
+ # to a negative integer
+ if extended_arg >= _INT_OVERFLOW:
+ extended_arg -= 2 * _INT_OVERFLOW
+ else:
+ arg = None
+ extended_arg = 0
+ if deop == EXTENDED_ARG:
+ extended_args_offset += 1
+ yield (i, i, op, arg)
+ else:
+ start_offset = i - extended_args_offset*2
+ yield (i, start_offset, op, arg)
+ extended_args_offset = 0
+
+def findlabels(code):
+ """Detect all offsets in a byte code which are jump targets.
+
+ Return the list of offsets.
+
+ """
+ labels = []
+ for offset, _, op, arg in _unpack_opargs(code):
+ if arg is not None:
+ label = _get_jump_target(op, arg, offset)
+ if label is None:
+ continue
+ if label not in labels:
+ labels.append(label)
+ return labels
+
+def findlinestarts(code):
+ """Find the offsets in a byte code which are start of lines in the source.
+
+ Generate pairs (offset, lineno)
+ lineno will be an integer or None the offset does not have a source line.
+ """
+
+ lastline = False # None is a valid line number
+ for start, end, line in code.co_lines():
+ if line is not lastline:
+ lastline = line
+ yield start, line
+ return
+
+def _find_imports(co):
+ """Find import statements in the code
+
+ Generate triplets (name, level, fromlist) where
+ name is the imported module and level, fromlist are
+ the corresponding args to __import__.
+ """
+ IMPORT_NAME = opmap['IMPORT_NAME']
+
+ consts = co.co_consts
+ names = co.co_names
+ opargs = [(op, arg) for _, _, op, arg in _unpack_opargs(co.co_code)
+ if op != EXTENDED_ARG]
+ for i, (op, oparg) in enumerate(opargs):
+ if op == IMPORT_NAME and i >= 2:
+ from_op = opargs[i-1]
+ level_op = opargs[i-2]
+ if (from_op[0] in hasconst and
+ (level_op[0] in hasconst or level_op[0] == LOAD_SMALL_INT)):
+ level = _get_const_value(level_op[0], level_op[1], consts)
+ fromlist = _get_const_value(from_op[0], from_op[1], consts)
+ yield (names[oparg], level, fromlist)
+
+def _find_store_names(co):
+ """Find names of variables which are written in the code
+
+ Generate sequence of strings
+ """
+ STORE_OPS = {
+ opmap['STORE_NAME'],
+ opmap['STORE_GLOBAL']
+ }
+
+ names = co.co_names
+ for _, _, op, arg in _unpack_opargs(co.co_code):
+ if op in STORE_OPS:
+ yield names[arg]
+
+
+class Bytecode:
+ """The bytecode operations of a piece of code
+
+ Instantiate this with a function, method, other compiled object, string of
+ code, or a code object (as returned by compile()).
+
+ Iterating over this yields the bytecode operations as Instruction instances.
+ """
+ def __init__(self, x, *, first_line=None, current_offset=None, show_caches=False, adaptive=False, show_offsets=False, show_positions=False):
+ self.codeobj = co = _get_code_object(x)
+ if first_line is None:
+ self.first_line = co.co_firstlineno
+ self._line_offset = 0
+ else:
+ self.first_line = first_line
+ self._line_offset = first_line - co.co_firstlineno
+ self._linestarts = dict(findlinestarts(co))
+ self._original_object = x
+ self.current_offset = current_offset
+ self.exception_entries = _parse_exception_table(co)
+ self.show_caches = show_caches
+ self.adaptive = adaptive
+ self.show_offsets = show_offsets
+ self.show_positions = show_positions
+
+ def __iter__(self):
+ co = self.codeobj
+ original_code = co.co_code
+ labels_map = _make_labels_map(original_code, self.exception_entries)
+ arg_resolver = ArgResolver(co_consts=co.co_consts,
+ names=co.co_names,
+ varname_from_oparg=co._varname_from_oparg,
+ labels_map=labels_map)
+ return _get_instructions_bytes(_get_code_array(co, self.adaptive),
+ linestarts=self._linestarts,
+ line_offset=self._line_offset,
+ co_positions=co.co_positions(),
+ original_code=original_code,
+ arg_resolver=arg_resolver)
+
+ def __repr__(self):
+ return "{}({!r})".format(self.__class__.__name__,
+ self._original_object)
+
+ @classmethod
+ def from_traceback(cls, tb, *, show_caches=False, adaptive=False):
+ """ Construct a Bytecode from the given traceback """
+ while tb.tb_next:
+ tb = tb.tb_next
+ return cls(
+ tb.tb_frame.f_code, current_offset=tb.tb_lasti, show_caches=show_caches, adaptive=adaptive
+ )
+
+ def info(self):
+ """Return formatted information about the code object."""
+ return _format_code_info(self.codeobj)
+
+ def dis(self):
+ """Return a formatted view of the bytecode operations."""
+ co = self.codeobj
+ if self.current_offset is not None:
+ offset = self.current_offset
+ else:
+ offset = -1
+ with io.StringIO() as output:
+ code = _get_code_array(co, self.adaptive)
+ offset_width = len(str(max(len(code) - 2, 9999))) if self.show_offsets else 0
+ if self.show_positions:
+ lineno_width = _get_positions_width(co)
+ else:
+ lineno_width = _get_lineno_width(self._linestarts)
+ labels_map = _make_labels_map(co.co_code, self.exception_entries)
+ label_width = 4 + len(str(len(labels_map)))
+ formatter = Formatter(file=output,
+ lineno_width=lineno_width,
+ offset_width=offset_width,
+ label_width=label_width,
+ line_offset=self._line_offset,
+ show_caches=self.show_caches,
+ show_positions=self.show_positions)
+
+ arg_resolver = ArgResolver(co_consts=co.co_consts,
+ names=co.co_names,
+ varname_from_oparg=co._varname_from_oparg,
+ labels_map=labels_map)
+ _disassemble_bytes(code,
+ linestarts=self._linestarts,
+ line_offset=self._line_offset,
+ lasti=offset,
+ exception_entries=self.exception_entries,
+ co_positions=co.co_positions(),
+ original_code=co.co_code,
+ arg_resolver=arg_resolver,
+ formatter=formatter)
+ return output.getvalue()
+
+
+def main(args=None):
+ import argparse
+
+ parser = argparse.ArgumentParser(color=True)
+ parser.add_argument('-C', '--show-caches', action='store_true',
+ help='show inline caches')
+ parser.add_argument('-O', '--show-offsets', action='store_true',
+ help='show instruction offsets')
+ parser.add_argument('-P', '--show-positions', action='store_true',
+ help='show instruction positions')
+ parser.add_argument('-S', '--specialized', action='store_true',
+ help='show specialized bytecode')
+ parser.add_argument('infile', nargs='?', default='-')
+ args = parser.parse_args(args=args)
+ if args.infile == '-':
+ name = ''
+ source = sys.stdin.buffer.read()
+ else:
+ name = args.infile
+ with open(args.infile, 'rb') as infile:
+ source = infile.read()
+ code = compile(source, name, "exec")
+ dis(code, show_caches=args.show_caches, adaptive=args.specialized,
+ show_offsets=args.show_offsets, show_positions=args.show_positions)
+
+if __name__ == "__main__":
+ main()
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/doctest.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/doctest.py
new file mode 100644
index 0000000000000000000000000000000000000000..a66888d8fc9673eac980f2db4c003e16bc08d533
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/doctest.py
@@ -0,0 +1,2921 @@
+# Module doctest.
+# Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org).
+# Major enhancements and refactoring by:
+# Jim Fulton
+# Edward Loper
+
+# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
+
+r"""Module doctest -- a framework for running examples in docstrings.
+
+In simplest use, end each module M to be tested with:
+
+def _test():
+ import doctest
+ doctest.testmod()
+
+if __name__ == "__main__":
+ _test()
+
+Then running the module as a script will cause the examples in the
+docstrings to get executed and verified:
+
+python M.py
+
+This won't display anything unless an example fails, in which case the
+failing example(s) and the cause(s) of the failure(s) are printed to stdout
+(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
+line of output is "Test failed.".
+
+Run it with the -v switch instead:
+
+python M.py -v
+
+and a detailed report of all examples tried is printed to stdout, along
+with assorted summaries at the end.
+
+You can force verbose mode by passing "verbose=True" to testmod, or prohibit
+it by passing "verbose=False". In either of those cases, sys.argv is not
+examined by testmod.
+
+There are a variety of other ways to run doctests, including integration
+with the unittest framework, and support for running non-Python text
+files containing doctests. There are also many ways to override parts
+of doctest's default behaviors. See the Library Reference Manual for
+details.
+"""
+
+__docformat__ = 'reStructuredText en'
+
+__all__ = [
+ # 0, Option Flags
+ 'register_optionflag',
+ 'DONT_ACCEPT_TRUE_FOR_1',
+ 'DONT_ACCEPT_BLANKLINE',
+ 'NORMALIZE_WHITESPACE',
+ 'ELLIPSIS',
+ 'SKIP',
+ 'IGNORE_EXCEPTION_DETAIL',
+ 'COMPARISON_FLAGS',
+ 'REPORT_UDIFF',
+ 'REPORT_CDIFF',
+ 'REPORT_NDIFF',
+ 'REPORT_ONLY_FIRST_FAILURE',
+ 'REPORTING_FLAGS',
+ 'FAIL_FAST',
+ # 1. Utility Functions
+ # 2. Example & DocTest
+ 'Example',
+ 'DocTest',
+ # 3. Doctest Parser
+ 'DocTestParser',
+ # 4. Doctest Finder
+ 'DocTestFinder',
+ # 5. Doctest Runner
+ 'DocTestRunner',
+ 'OutputChecker',
+ 'DocTestFailure',
+ 'UnexpectedException',
+ 'DebugRunner',
+ # 6. Test Functions
+ 'testmod',
+ 'testfile',
+ 'run_docstring_examples',
+ # 7. Unittest Support
+ 'DocTestSuite',
+ 'DocFileSuite',
+ 'set_unittest_reportflags',
+ # 8. Debugging Support
+ 'script_from_examples',
+ 'testsource',
+ 'debug_src',
+ 'debug',
+]
+
+import __future__
+import difflib
+import functools
+import inspect
+import linecache
+import os
+import pdb
+import re
+import sys
+import traceback
+import unittest
+from io import StringIO, IncrementalNewlineDecoder
+from collections import namedtuple
+import _colorize # Used in doctests
+from _colorize import ANSIColors, can_colorize
+
+
+__unittest = True
+
+class TestResults(namedtuple('TestResults', 'failed attempted')):
+ def __new__(cls, failed, attempted, *, skipped=0):
+ results = super().__new__(cls, failed, attempted)
+ results.skipped = skipped
+ return results
+
+ def __repr__(self):
+ if self.skipped:
+ return (f'TestResults(failed={self.failed}, '
+ f'attempted={self.attempted}, '
+ f'skipped={self.skipped})')
+ else:
+ # Leave the repr() unchanged for backward compatibility
+ # if skipped is zero
+ return super().__repr__()
+
+
+# There are 4 basic classes:
+# - Example: a pair, plus an intra-docstring line number.
+# - DocTest: a collection of examples, parsed from a docstring, plus
+# info about where the docstring came from (name, filename, lineno).
+# - DocTestFinder: extracts DocTests from a given object's docstring and
+# its contained objects' docstrings.
+# - DocTestRunner: runs DocTest cases, and accumulates statistics.
+#
+# So the basic picture is:
+#
+# list of:
+# +------+ +---------+ +-------+
+# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
+# +------+ +---------+ +-------+
+# | Example |
+# | ... |
+# | Example |
+# +---------+
+
+# Option constants.
+
+OPTIONFLAGS_BY_NAME = {}
+def register_optionflag(name):
+ # Create a new flag unless `name` is already known.
+ return OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(OPTIONFLAGS_BY_NAME))
+
+DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
+DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
+NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
+ELLIPSIS = register_optionflag('ELLIPSIS')
+SKIP = register_optionflag('SKIP')
+IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL')
+
+COMPARISON_FLAGS = (DONT_ACCEPT_TRUE_FOR_1 |
+ DONT_ACCEPT_BLANKLINE |
+ NORMALIZE_WHITESPACE |
+ ELLIPSIS |
+ SKIP |
+ IGNORE_EXCEPTION_DETAIL)
+
+REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
+REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
+REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
+REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
+FAIL_FAST = register_optionflag('FAIL_FAST')
+
+REPORTING_FLAGS = (REPORT_UDIFF |
+ REPORT_CDIFF |
+ REPORT_NDIFF |
+ REPORT_ONLY_FIRST_FAILURE |
+ FAIL_FAST)
+
+# Special string markers for use in `want` strings:
+BLANKLINE_MARKER = ''
+ELLIPSIS_MARKER = '...'
+
+######################################################################
+## Table of Contents
+######################################################################
+# 1. Utility Functions
+# 2. Example & DocTest -- store test cases
+# 3. DocTest Parser -- extracts examples from strings
+# 4. DocTest Finder -- extracts test cases from objects
+# 5. DocTest Runner -- runs test cases
+# 6. Test Functions -- convenient wrappers for testing
+# 7. Unittest Support
+# 8. Debugging Support
+# 9. Example Usage
+
+######################################################################
+## 1. Utility Functions
+######################################################################
+
+def _extract_future_flags(globs):
+ """
+ Return the compiler-flags associated with the future features that
+ have been imported into the given namespace (globs).
+ """
+ flags = 0
+ for fname in __future__.all_feature_names:
+ feature = globs.get(fname, None)
+ if feature is getattr(__future__, fname):
+ flags |= feature.compiler_flag
+ return flags
+
+def _normalize_module(module, depth=2):
+ """
+ Return the module specified by `module`. In particular:
+ - If `module` is a module, then return module.
+ - If `module` is a string, then import and return the
+ module with that name.
+ - If `module` is None, then return the calling module.
+ The calling module is assumed to be the module of
+ the stack frame at the given depth in the call stack.
+ """
+ if inspect.ismodule(module):
+ return module
+ elif isinstance(module, str):
+ return __import__(module, globals(), locals(), ["*"])
+ elif module is None:
+ try:
+ try:
+ return sys.modules[sys._getframemodulename(depth)]
+ except AttributeError:
+ return sys.modules[sys._getframe(depth).f_globals['__name__']]
+ except KeyError:
+ pass
+ else:
+ raise TypeError("Expected a module, string, or None")
+
+def _newline_convert(data):
+ # The IO module provides a handy decoder for universal newline conversion
+ return IncrementalNewlineDecoder(None, True).decode(data, True)
+
+def _load_testfile(filename, package, module_relative, encoding):
+ if module_relative:
+ package = _normalize_module(package, 3)
+ filename = _module_relative_path(package, filename)
+ if (loader := getattr(package, '__loader__', None)) is None:
+ try:
+ loader = package.__spec__.loader
+ except AttributeError:
+ pass
+ if hasattr(loader, 'get_data'):
+ file_contents = loader.get_data(filename)
+ file_contents = file_contents.decode(encoding)
+ # get_data() opens files as 'rb', so one must do the equivalent
+ # conversion as universal newlines would do.
+ return _newline_convert(file_contents), filename
+ with open(filename, encoding=encoding) as f:
+ return f.read(), filename
+
+def _indent(s, indent=4):
+ """
+ Add the given number of space characters to the beginning of
+ every non-blank line in `s`, and return the result.
+ """
+ # This regexp matches the start of non-blank lines:
+ return re.sub('(?m)^(?!$)', indent*' ', s)
+
+def _exception_traceback(exc_info):
+ """
+ Return a string containing a traceback message for the given
+ exc_info tuple (as returned by sys.exc_info()).
+ """
+ # Get a traceback message.
+ excout = StringIO()
+ exc_type, exc_val, exc_tb = exc_info
+ traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
+ return excout.getvalue()
+
+# Override some StringIO methods.
+class _SpoofOut(StringIO):
+ def getvalue(self):
+ result = StringIO.getvalue(self)
+ # If anything at all was written, make sure there's a trailing
+ # newline. There's no way for the expected output to indicate
+ # that a trailing newline is missing.
+ if result and not result.endswith("\n"):
+ result += "\n"
+ return result
+
+ def truncate(self, size=None):
+ self.seek(size)
+ StringIO.truncate(self)
+
+# Worst-case linear-time ellipsis matching.
+def _ellipsis_match(want, got):
+ """
+ Essentially the only subtle case:
+ >>> _ellipsis_match('aa...aa', 'aaa')
+ False
+ """
+ if ELLIPSIS_MARKER not in want:
+ return want == got
+
+ # Find "the real" strings.
+ ws = want.split(ELLIPSIS_MARKER)
+ assert len(ws) >= 2
+
+ # Deal with exact matches possibly needed at one or both ends.
+ startpos, endpos = 0, len(got)
+ w = ws[0]
+ if w: # starts with exact match
+ if got.startswith(w):
+ startpos = len(w)
+ del ws[0]
+ else:
+ return False
+ w = ws[-1]
+ if w: # ends with exact match
+ if got.endswith(w):
+ endpos -= len(w)
+ del ws[-1]
+ else:
+ return False
+
+ if startpos > endpos:
+ # Exact end matches required more characters than we have, as in
+ # _ellipsis_match('aa...aa', 'aaa')
+ return False
+
+ # For the rest, we only need to find the leftmost non-overlapping
+ # match for each piece. If there's no overall match that way alone,
+ # there's no overall match period.
+ for w in ws:
+ # w may be '' at times, if there are consecutive ellipses, or
+ # due to an ellipsis at the start or end of `want`. That's OK.
+ # Search for an empty string succeeds, and doesn't change startpos.
+ startpos = got.find(w, startpos, endpos)
+ if startpos < 0:
+ return False
+ startpos += len(w)
+
+ return True
+
+def _comment_line(line):
+ "Return a commented form of the given line"
+ line = line.rstrip()
+ if line:
+ return '# '+line
+ else:
+ return '#'
+
+def _strip_exception_details(msg):
+ # Support for IGNORE_EXCEPTION_DETAIL.
+ # Get rid of everything except the exception name; in particular, drop
+ # the possibly dotted module path (if any) and the exception message (if
+ # any). We assume that a colon is never part of a dotted name, or of an
+ # exception name.
+ # E.g., given
+ # "foo.bar.MyError: la di da"
+ # return "MyError"
+ # Or for "abc.def" or "abc.def:\n" return "def".
+
+ start, end = 0, len(msg)
+ # The exception name must appear on the first line.
+ i = msg.find("\n")
+ if i >= 0:
+ end = i
+ # retain up to the first colon (if any)
+ i = msg.find(':', 0, end)
+ if i >= 0:
+ end = i
+ # retain just the exception name
+ i = msg.rfind('.', 0, end)
+ if i >= 0:
+ start = i+1
+ return msg[start: end]
+
+class _OutputRedirectingPdb(pdb.Pdb):
+ """
+ A specialized version of the python debugger that redirects stdout
+ to a given stream when interacting with the user. Stdout is *not*
+ redirected when traced code is executed.
+ """
+ def __init__(self, out):
+ self.__out = out
+ self.__debugger_used = False
+ # do not play signal games in the pdb
+ pdb.Pdb.__init__(self, stdout=out, nosigint=True)
+ # still use input() to get user input
+ self.use_rawinput = 1
+
+ def set_trace(self, frame=None, *, commands=None):
+ self.__debugger_used = True
+ if frame is None:
+ frame = sys._getframe().f_back
+ pdb.Pdb.set_trace(self, frame, commands=commands)
+
+ def set_continue(self):
+ # Calling set_continue unconditionally would break unit test
+ # coverage reporting, as Bdb.set_continue calls sys.settrace(None).
+ if self.__debugger_used:
+ pdb.Pdb.set_continue(self)
+
+ def trace_dispatch(self, *args):
+ # Redirect stdout to the given stream.
+ save_stdout = sys.stdout
+ sys.stdout = self.__out
+ # Call Pdb's trace dispatch method.
+ try:
+ return pdb.Pdb.trace_dispatch(self, *args)
+ finally:
+ sys.stdout = save_stdout
+
+# [XX] Normalize with respect to os.path.pardir?
+def _module_relative_path(module, test_path):
+ if not inspect.ismodule(module):
+ raise TypeError('Expected a module: %r' % module)
+ if test_path.startswith('/'):
+ raise ValueError('Module-relative files may not have absolute paths')
+
+ # Normalize the path. On Windows, replace "/" with "\".
+ test_path = os.path.join(*(test_path.split('/')))
+
+ # Find the base directory for the path.
+ if hasattr(module, '__file__'):
+ # A normal module/package
+ basedir = os.path.split(module.__file__)[0]
+ elif module.__name__ == '__main__':
+ # An interactive session.
+ if len(sys.argv)>0 and sys.argv[0] != '':
+ basedir = os.path.split(sys.argv[0])[0]
+ else:
+ basedir = os.curdir
+ else:
+ if hasattr(module, '__path__'):
+ for directory in module.__path__:
+ fullpath = os.path.join(directory, test_path)
+ if os.path.exists(fullpath):
+ return fullpath
+
+ # A module w/o __file__ (this includes builtins)
+ raise ValueError("Can't resolve paths relative to the module "
+ "%r (it has no __file__)"
+ % module.__name__)
+
+ # Combine the base directory and the test path.
+ return os.path.join(basedir, test_path)
+
+######################################################################
+## 2. Example & DocTest
+######################################################################
+## - An "example" is a pair, where "source" is a
+## fragment of source code, and "want" is the expected output for
+## "source." The Example class also includes information about
+## where the example was extracted from.
+##
+## - A "doctest" is a collection of examples, typically extracted from
+## a string (such as an object's docstring). The DocTest class also
+## includes information about where the string was extracted from.
+
+class Example:
+ """
+ A single doctest example, consisting of source code and expected
+ output. `Example` defines the following attributes:
+
+ - source: A single Python statement, always ending with a newline.
+ The constructor adds a newline if needed.
+
+ - want: The expected output from running the source code (either
+ from stdout, or a traceback in case of exception). `want` ends
+ with a newline unless it's empty, in which case it's an empty
+ string. The constructor adds a newline if needed.
+
+ - exc_msg: The exception message generated by the example, if
+ the example is expected to generate an exception; or `None` if
+ it is not expected to generate an exception. This exception
+ message is compared against the return value of
+ `traceback.format_exception_only()`. `exc_msg` ends with a
+ newline unless it's `None`. The constructor adds a newline
+ if needed.
+
+ - lineno: The line number within the DocTest string containing
+ this Example where the Example begins. This line number is
+ zero-based, with respect to the beginning of the DocTest.
+
+ - indent: The example's indentation in the DocTest string.
+ I.e., the number of space characters that precede the
+ example's first prompt.
+
+ - options: A dictionary mapping from option flags to True or
+ False, which is used to override default options for this
+ example. Any option flags not contained in this dictionary
+ are left at their default value (as specified by the
+ DocTestRunner's optionflags). By default, no options are set.
+ """
+ def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
+ options=None):
+ # Normalize inputs.
+ if not source.endswith('\n'):
+ source += '\n'
+ if want and not want.endswith('\n'):
+ want += '\n'
+ if exc_msg is not None and not exc_msg.endswith('\n'):
+ exc_msg += '\n'
+ # Store properties.
+ self.source = source
+ self.want = want
+ self.lineno = lineno
+ self.indent = indent
+ if options is None: options = {}
+ self.options = options
+ self.exc_msg = exc_msg
+
+ def __eq__(self, other):
+ if type(self) is not type(other):
+ return NotImplemented
+
+ return self.source == other.source and \
+ self.want == other.want and \
+ self.lineno == other.lineno and \
+ self.indent == other.indent and \
+ self.options == other.options and \
+ self.exc_msg == other.exc_msg
+
+ def __hash__(self):
+ return hash((self.source, self.want, self.lineno, self.indent,
+ self.exc_msg))
+
+class DocTest:
+ """
+ A collection of doctest examples that should be run in a single
+ namespace. Each `DocTest` defines the following attributes:
+
+ - examples: the list of examples.
+
+ - globs: The namespace (aka globals) that the examples should
+ be run in.
+
+ - name: A name identifying the DocTest (typically, the name of
+ the object whose docstring this DocTest was extracted from).
+
+ - filename: The name of the file that this DocTest was extracted
+ from, or `None` if the filename is unknown.
+
+ - lineno: The line number within filename where this DocTest
+ begins, or `None` if the line number is unavailable. This
+ line number is zero-based, with respect to the beginning of
+ the file.
+
+ - docstring: The string that the examples were extracted from,
+ or `None` if the string is unavailable.
+ """
+ def __init__(self, examples, globs, name, filename, lineno, docstring):
+ """
+ Create a new DocTest containing the given examples. The
+ DocTest's globals are initialized with a copy of `globs`.
+ """
+ assert not isinstance(examples, str), \
+ "DocTest no longer accepts str; use DocTestParser instead"
+ self.examples = examples
+ self.docstring = docstring
+ self.globs = globs.copy()
+ self.name = name
+ self.filename = filename
+ self.lineno = lineno
+
+ def __repr__(self):
+ if len(self.examples) == 0:
+ examples = 'no examples'
+ elif len(self.examples) == 1:
+ examples = '1 example'
+ else:
+ examples = '%d examples' % len(self.examples)
+ return ('<%s %s from %s:%s (%s)>' %
+ (self.__class__.__name__,
+ self.name, self.filename, self.lineno, examples))
+
+ def __eq__(self, other):
+ if type(self) is not type(other):
+ return NotImplemented
+
+ return self.examples == other.examples and \
+ self.docstring == other.docstring and \
+ self.globs == other.globs and \
+ self.name == other.name and \
+ self.filename == other.filename and \
+ self.lineno == other.lineno
+
+ def __hash__(self):
+ return hash((self.docstring, self.name, self.filename, self.lineno))
+
+ # This lets us sort tests by name:
+ def __lt__(self, other):
+ if not isinstance(other, DocTest):
+ return NotImplemented
+ self_lno = self.lineno if self.lineno is not None else -1
+ other_lno = other.lineno if other.lineno is not None else -1
+ return ((self.name, self.filename, self_lno, id(self))
+ <
+ (other.name, other.filename, other_lno, id(other)))
+
+######################################################################
+## 3. DocTestParser
+######################################################################
+
+class DocTestParser:
+ """
+ A class used to parse strings containing doctest examples.
+ """
+ # This regular expression is used to find doctest examples in a
+ # string. It defines three groups: `source` is the source code
+ # (including leading indentation and prompts); `indent` is the
+ # indentation of the first (PS1) line of the source code; and
+ # `want` is the expected output (including leading indentation).
+ _EXAMPLE_RE = re.compile(r'''
+ # Source consists of a PS1 line followed by zero or more PS2 lines.
+ (?P
+ (?:^(?P [ ]*) >>> .*) # PS1 line
+ (?:\n [ ]* \.\.\. .*)*) # PS2 lines
+ \n?
+ # Want consists of any non-blank lines that do not start with PS1.
+ (?P (?:(?![ ]*$) # Not a blank line
+ (?![ ]*>>>) # Not a line starting with PS1
+ .+$\n? # But any other line
+ )*)
+ ''', re.MULTILINE | re.VERBOSE)
+
+ # A regular expression for handling `want` strings that contain
+ # expected exceptions. It divides `want` into three pieces:
+ # - the traceback header line (`hdr`)
+ # - the traceback stack (`stack`)
+ # - the exception message (`msg`), as generated by
+ # traceback.format_exception_only()
+ # `msg` may have multiple lines. We assume/require that the
+ # exception message is the first non-indented line starting with a word
+ # character following the traceback header line.
+ _EXCEPTION_RE = re.compile(r"""
+ # Grab the traceback header. Different versions of Python have
+ # said different things on the first traceback line.
+ ^(?P Traceback\ \(
+ (?: most\ recent\ call\ last
+ | innermost\ last
+ ) \) :
+ )
+ \s* $ # toss trailing whitespace on the header.
+ (?P .*?) # don't blink: absorb stuff until...
+ ^ (?P \w+ .*) # a line *starts* with alphanum.
+ """, re.VERBOSE | re.MULTILINE | re.DOTALL)
+
+ # A callable returning a true value iff its argument is a blank line
+ # or contains a single comment.
+ _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
+
+ def parse(self, string, name=''):
+ """
+ Divide the given string into examples and intervening text,
+ and return them as a list of alternating Examples and strings.
+ Line numbers for the Examples are 0-based. The optional
+ argument `name` is a name identifying this string, and is only
+ used for error messages.
+ """
+ string = string.expandtabs()
+ # If all lines begin with the same indentation, then strip it.
+ min_indent = self._min_indent(string)
+ if min_indent > 0:
+ string = '\n'.join([l[min_indent:] for l in string.split('\n')])
+
+ output = []
+ charno, lineno = 0, 0
+ # Find all doctest examples in the string:
+ for m in self._EXAMPLE_RE.finditer(string):
+ # Add the pre-example text to `output`.
+ output.append(string[charno:m.start()])
+ # Update lineno (lines before this example)
+ lineno += string.count('\n', charno, m.start())
+ # Extract info from the regexp match.
+ (source, options, want, exc_msg) = \
+ self._parse_example(m, name, lineno)
+ # Create an Example, and add it to the list.
+ if not self._IS_BLANK_OR_COMMENT(source):
+ output.append( Example(source, want, exc_msg,
+ lineno=lineno,
+ indent=min_indent+len(m.group('indent')),
+ options=options) )
+ # Update lineno (lines inside this example)
+ lineno += string.count('\n', m.start(), m.end())
+ # Update charno.
+ charno = m.end()
+ # Add any remaining post-example text to `output`.
+ output.append(string[charno:])
+ return output
+
+ def get_doctest(self, string, globs, name, filename, lineno):
+ """
+ Extract all doctest examples from the given string, and
+ collect them into a `DocTest` object.
+
+ `globs`, `name`, `filename`, and `lineno` are attributes for
+ the new `DocTest` object. See the documentation for `DocTest`
+ for more information.
+ """
+ return DocTest(self.get_examples(string, name), globs,
+ name, filename, lineno, string)
+
+ def get_examples(self, string, name=''):
+ """
+ Extract all doctest examples from the given string, and return
+ them as a list of `Example` objects. Line numbers are
+ 0-based, because it's most common in doctests that nothing
+ interesting appears on the same line as opening triple-quote,
+ and so the first interesting line is called \"line 1\" then.
+
+ The optional argument `name` is a name identifying this
+ string, and is only used for error messages.
+ """
+ return [x for x in self.parse(string, name)
+ if isinstance(x, Example)]
+
+ def _parse_example(self, m, name, lineno):
+ """
+ Given a regular expression match from `_EXAMPLE_RE` (`m`),
+ return a pair `(source, want)`, where `source` is the matched
+ example's source code (with prompts and indentation stripped);
+ and `want` is the example's expected output (with indentation
+ stripped).
+
+ `name` is the string's name, and `lineno` is the line number
+ where the example starts; both are used for error messages.
+ """
+ # Get the example's indentation level.
+ indent = len(m.group('indent'))
+
+ # Divide source into lines; check that they're properly
+ # indented; and then strip their indentation & prompts.
+ source_lines = m.group('source').split('\n')
+ self._check_prompt_blank(source_lines, indent, name, lineno)
+ self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
+ source = '\n'.join([sl[indent+4:] for sl in source_lines])
+
+ # Divide want into lines; check that it's properly indented; and
+ # then strip the indentation. Spaces before the last newline should
+ # be preserved, so plain rstrip() isn't good enough.
+ want = m.group('want')
+ want_lines = want.split('\n')
+ if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
+ del want_lines[-1] # forget final newline & spaces after it
+ self._check_prefix(want_lines, ' '*indent, name,
+ lineno + len(source_lines))
+ want = '\n'.join([wl[indent:] for wl in want_lines])
+
+ # If `want` contains a traceback message, then extract it.
+ m = self._EXCEPTION_RE.match(want)
+ if m:
+ exc_msg = m.group('msg')
+ else:
+ exc_msg = None
+
+ # Extract options from the source.
+ options = self._find_options(source, name, lineno)
+
+ return source, options, want, exc_msg
+
+ # This regular expression looks for option directives in the
+ # source code of an example. Option directives are comments
+ # starting with "doctest:". Warning: this may give false
+ # positives for string-literals that contain the string
+ # "#doctest:". Eliminating these false positives would require
+ # actually parsing the string; but we limit them by ignoring any
+ # line containing "#doctest:" that is *followed* by a quote mark.
+ _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
+ re.MULTILINE)
+
+ def _find_options(self, source, name, lineno):
+ """
+ Return a dictionary containing option overrides extracted from
+ option directives in the given source string.
+
+ `name` is the string's name, and `lineno` is the line number
+ where the example starts; both are used for error messages.
+ """
+ options = {}
+ # (note: with the current regexp, this will match at most once:)
+ for m in self._OPTION_DIRECTIVE_RE.finditer(source):
+ option_strings = m.group(1).replace(',', ' ').split()
+ for option in option_strings:
+ if (option[0] not in '+-' or
+ option[1:] not in OPTIONFLAGS_BY_NAME):
+ raise ValueError('line %r of the doctest for %s '
+ 'has an invalid option: %r' %
+ (lineno+1, name, option))
+ flag = OPTIONFLAGS_BY_NAME[option[1:]]
+ options[flag] = (option[0] == '+')
+ if options and self._IS_BLANK_OR_COMMENT(source):
+ raise ValueError('line %r of the doctest for %s has an option '
+ 'directive on a line with no example: %r' %
+ (lineno, name, source))
+ return options
+
+ # This regular expression finds the indentation of every non-blank
+ # line in a string.
+ _INDENT_RE = re.compile(r'^([ ]*)(?=\S)', re.MULTILINE)
+
+ def _min_indent(self, s):
+ "Return the minimum indentation of any non-blank line in `s`"
+ indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
+ if len(indents) > 0:
+ return min(indents)
+ else:
+ return 0
+
+ def _check_prompt_blank(self, lines, indent, name, lineno):
+ """
+ Given the lines of a source string (including prompts and
+ leading indentation), check to make sure that every prompt is
+ followed by a space character. If any line is not followed by
+ a space character, then raise ValueError.
+ """
+ for i, line in enumerate(lines):
+ if len(line) >= indent+4 and line[indent+3] != ' ':
+ raise ValueError('line %r of the docstring for %s '
+ 'lacks blank after %s: %r' %
+ (lineno+i+1, name,
+ line[indent:indent+3], line))
+
+ def _check_prefix(self, lines, prefix, name, lineno):
+ """
+ Check that every line in the given list starts with the given
+ prefix; if any line does not, then raise a ValueError.
+ """
+ for i, line in enumerate(lines):
+ if line and not line.startswith(prefix):
+ raise ValueError('line %r of the docstring for %s has '
+ 'inconsistent leading whitespace: %r' %
+ (lineno+i+1, name, line))
+
+
+######################################################################
+## 4. DocTest Finder
+######################################################################
+
+class DocTestFinder:
+ """
+ A class used to extract the DocTests that are relevant to a given
+ object, from its docstring and the docstrings of its contained
+ objects. Doctests can currently be extracted from the following
+ object types: modules, functions, classes, methods, staticmethods,
+ classmethods, and properties.
+ """
+
+ def __init__(self, verbose=False, parser=DocTestParser(),
+ recurse=True, exclude_empty=True):
+ """
+ Create a new doctest finder.
+
+ The optional argument `parser` specifies a class or
+ function that should be used to create new DocTest objects (or
+ objects that implement the same interface as DocTest). The
+ signature for this factory function should match the signature
+ of the DocTest constructor.
+
+ If the optional argument `recurse` is false, then `find` will
+ only examine the given object, and not any contained objects.
+
+ If the optional argument `exclude_empty` is false, then `find`
+ will include tests for objects with empty docstrings.
+ """
+ self._parser = parser
+ self._verbose = verbose
+ self._recurse = recurse
+ self._exclude_empty = exclude_empty
+
+ def find(self, obj, name=None, module=None, globs=None, extraglobs=None):
+ """
+ Return a list of the DocTests that are defined by the given
+ object's docstring, or by any of its contained objects'
+ docstrings.
+
+ The optional parameter `module` is the module that contains
+ the given object. If the module is not specified or is None, then
+ the test finder will attempt to automatically determine the
+ correct module. The object's module is used:
+
+ - As a default namespace, if `globs` is not specified.
+ - To prevent the DocTestFinder from extracting DocTests
+ from objects that are imported from other modules.
+ - To find the name of the file containing the object.
+ - To help find the line number of the object within its
+ file.
+
+ Contained objects whose module does not match `module` are ignored.
+
+ If `module` is False, no attempt to find the module will be made.
+ This is obscure, of use mostly in tests: if `module` is False, or
+ is None but cannot be found automatically, then all objects are
+ considered to belong to the (non-existent) module, so all contained
+ objects will (recursively) be searched for doctests.
+
+ The globals for each DocTest is formed by combining `globs`
+ and `extraglobs` (bindings in `extraglobs` override bindings
+ in `globs`). A new copy of the globals dictionary is created
+ for each DocTest. If `globs` is not specified, then it
+ defaults to the module's `__dict__`, if specified, or {}
+ otherwise. If `extraglobs` is not specified, then it defaults
+ to {}.
+
+ """
+ # If name was not specified, then extract it from the object.
+ if name is None:
+ name = getattr(obj, '__name__', None)
+ if name is None:
+ raise ValueError("DocTestFinder.find: name must be given "
+ "when obj.__name__ doesn't exist: %r" %
+ (type(obj),))
+
+ # Find the module that contains the given object (if obj is
+ # a module, then module=obj.). Note: this may fail, in which
+ # case module will be None.
+ if module is False:
+ module = None
+ elif module is None:
+ module = inspect.getmodule(obj)
+
+ # Read the module's source code. This is used by
+ # DocTestFinder._find_lineno to find the line number for a
+ # given object's docstring.
+ try:
+ file = inspect.getsourcefile(obj)
+ except TypeError:
+ source_lines = None
+ else:
+ if not file:
+ # Check to see if it's one of our special internal "files"
+ # (see __patched_linecache_getlines).
+ file = inspect.getfile(obj)
+ if not file[0]+file[-2:] == '<]>': file = None
+ if file is None:
+ source_lines = None
+ else:
+ if module is not None:
+ # Supply the module globals in case the module was
+ # originally loaded via a PEP 302 loader and
+ # file is not a valid filesystem path
+ source_lines = linecache.getlines(file, module.__dict__)
+ else:
+ # No access to a loader, so assume it's a normal
+ # filesystem path
+ source_lines = linecache.getlines(file)
+ if not source_lines:
+ source_lines = None
+
+ # Initialize globals, and merge in extraglobs.
+ if globs is None:
+ if module is None:
+ globs = {}
+ else:
+ globs = module.__dict__.copy()
+ else:
+ globs = globs.copy()
+ if extraglobs is not None:
+ globs.update(extraglobs)
+ if '__name__' not in globs:
+ globs['__name__'] = '__main__' # provide a default module name
+
+ # Recursively explore `obj`, extracting DocTests.
+ tests = []
+ self._find(tests, obj, name, module, source_lines, globs, {})
+ # Sort the tests by alpha order of names, for consistency in
+ # verbose-mode output. This was a feature of doctest in Pythons
+ # <= 2.3 that got lost by accident in 2.4. It was repaired in
+ # 2.4.4 and 2.5.
+ tests.sort()
+ return tests
+
+ def _from_module(self, module, object):
+ """
+ Return true if the given object is defined in the given
+ module.
+ """
+ if module is None:
+ return True
+ elif inspect.getmodule(object) is not None:
+ return module is inspect.getmodule(object)
+ elif inspect.isfunction(object):
+ return module.__dict__ is object.__globals__
+ elif (inspect.ismethoddescriptor(object) or
+ inspect.ismethodwrapper(object)):
+ if hasattr(object, '__objclass__'):
+ obj_mod = object.__objclass__.__module__
+ elif hasattr(object, '__module__'):
+ obj_mod = object.__module__
+ else:
+ return True # [XX] no easy way to tell otherwise
+ return module.__name__ == obj_mod
+ elif inspect.isclass(object):
+ return module.__name__ == object.__module__
+ elif hasattr(object, '__module__'):
+ return module.__name__ == object.__module__
+ elif isinstance(object, property):
+ return True # [XX] no way not be sure.
+ else:
+ raise ValueError("object must be a class or function")
+
+ def _is_routine(self, obj):
+ """
+ Safely unwrap objects and determine if they are functions.
+ """
+ maybe_routine = obj
+ try:
+ maybe_routine = inspect.unwrap(maybe_routine)
+ except ValueError:
+ pass
+ return inspect.isroutine(maybe_routine)
+
+ def _find(self, tests, obj, name, module, source_lines, globs, seen):
+ """
+ Find tests for the given object and any contained objects, and
+ add them to `tests`.
+ """
+ if self._verbose:
+ print('Finding tests in %s' % name)
+
+ # If we've already processed this object, then ignore it.
+ if id(obj) in seen:
+ return
+ seen[id(obj)] = 1
+
+ # Find a test for this object, and add it to the list of tests.
+ test = self._get_test(obj, name, module, globs, source_lines)
+ if test is not None:
+ tests.append(test)
+
+ # Look for tests in a module's contained objects.
+ if inspect.ismodule(obj) and self._recurse:
+ for valname, val in obj.__dict__.items():
+ valname = '%s.%s' % (name, valname)
+
+ # Recurse to functions & classes.
+ if ((self._is_routine(val) or inspect.isclass(val)) and
+ self._from_module(module, val)):
+ self._find(tests, val, valname, module, source_lines,
+ globs, seen)
+
+ # Look for tests in a module's __test__ dictionary.
+ if inspect.ismodule(obj) and self._recurse:
+ for valname, val in getattr(obj, '__test__', {}).items():
+ if not isinstance(valname, str):
+ raise ValueError("DocTestFinder.find: __test__ keys "
+ "must be strings: %r" %
+ (type(valname),))
+ if not (inspect.isroutine(val) or inspect.isclass(val) or
+ inspect.ismodule(val) or isinstance(val, str)):
+ raise ValueError("DocTestFinder.find: __test__ values "
+ "must be strings, functions, methods, "
+ "classes, or modules: %r" %
+ (type(val),))
+ valname = '%s.__test__.%s' % (name, valname)
+ self._find(tests, val, valname, module, source_lines,
+ globs, seen)
+
+ # Look for tests in a class's contained objects.
+ if inspect.isclass(obj) and self._recurse:
+ for valname, val in obj.__dict__.items():
+ # Special handling for staticmethod/classmethod.
+ if isinstance(val, (staticmethod, classmethod)):
+ val = val.__func__
+
+ # Recurse to methods, properties, and nested classes.
+ if ((inspect.isroutine(val) or inspect.isclass(val) or
+ isinstance(val, property)) and
+ self._from_module(module, val)):
+ valname = '%s.%s' % (name, valname)
+ self._find(tests, val, valname, module, source_lines,
+ globs, seen)
+
+ def _get_test(self, obj, name, module, globs, source_lines):
+ """
+ Return a DocTest for the given object, if it defines a docstring;
+ otherwise, return None.
+ """
+ # Extract the object's docstring. If it doesn't have one,
+ # then return None (no test for this object).
+ if isinstance(obj, str):
+ docstring = obj
+ else:
+ try:
+ if obj.__doc__ is None:
+ docstring = ''
+ else:
+ docstring = obj.__doc__
+ if not isinstance(docstring, str):
+ docstring = str(docstring)
+ except (TypeError, AttributeError):
+ docstring = ''
+
+ # Find the docstring's location in the file.
+ lineno = self._find_lineno(obj, source_lines)
+
+ # Don't bother if the docstring is empty.
+ if self._exclude_empty and not docstring:
+ return None
+
+ # Return a DocTest for this object.
+ if module is None:
+ filename = None
+ else:
+ # __file__ can be None for namespace packages.
+ filename = getattr(module, '__file__', None) or module.__name__
+ if filename[-4:] == ".pyc":
+ filename = filename[:-1]
+ return self._parser.get_doctest(docstring, globs, name,
+ filename, lineno)
+
+ def _find_lineno(self, obj, source_lines):
+ """
+ Return a line number of the given object's docstring.
+
+ Returns `None` if the given object does not have a docstring.
+ """
+ lineno = None
+ docstring = getattr(obj, '__doc__', None)
+
+ # Find the line number for modules.
+ if inspect.ismodule(obj) and docstring is not None:
+ lineno = 0
+
+ # Find the line number for classes.
+ # Note: this could be fooled if a class is defined multiple
+ # times in a single file.
+ if inspect.isclass(obj) and docstring is not None:
+ if source_lines is None:
+ return None
+ pat = re.compile(r'^\s*class\s*%s\b' %
+ re.escape(getattr(obj, '__name__', '-')))
+ for i, line in enumerate(source_lines):
+ if pat.match(line):
+ lineno = i
+ break
+
+ # Find the line number for functions & methods.
+ if inspect.ismethod(obj): obj = obj.__func__
+ if isinstance(obj, property):
+ obj = obj.fget
+ if isinstance(obj, functools.cached_property):
+ obj = obj.func
+ if inspect.isroutine(obj) and getattr(obj, '__doc__', None):
+ # We don't use `docstring` var here, because `obj` can be changed.
+ obj = inspect.unwrap(obj)
+ try:
+ obj = obj.__code__
+ except AttributeError:
+ # Functions implemented in C don't necessarily
+ # have a __code__ attribute.
+ # If there's no code, there's no lineno
+ return None
+ if inspect.istraceback(obj): obj = obj.tb_frame
+ if inspect.isframe(obj): obj = obj.f_code
+ if inspect.iscode(obj):
+ lineno = obj.co_firstlineno - 1
+
+ # Find the line number where the docstring starts. Assume
+ # that it's the first line that begins with a quote mark.
+ # Note: this could be fooled by a multiline function
+ # signature, where a continuation line begins with a quote
+ # mark.
+ if lineno is not None:
+ if source_lines is None:
+ return lineno+1
+ pat = re.compile(r'(^|.*:)\s*\w*("|\')')
+ for lineno in range(lineno, len(source_lines)):
+ if pat.match(source_lines[lineno]):
+ return lineno
+
+ # We couldn't find the line number.
+ return None
+
+######################################################################
+## 5. DocTest Runner
+######################################################################
+
+class DocTestRunner:
+ """
+ A class used to run DocTest test cases, and accumulate statistics.
+ The `run` method is used to process a single DocTest case. It
+ returns a TestResults instance.
+
+ >>> save_colorize = _colorize.COLORIZE
+ >>> _colorize.COLORIZE = False
+
+ >>> tests = DocTestFinder().find(_TestClass)
+ >>> runner = DocTestRunner(verbose=False)
+ >>> tests.sort(key = lambda test: test.name)
+ >>> for test in tests:
+ ... print(test.name, '->', runner.run(test))
+ _TestClass -> TestResults(failed=0, attempted=2)
+ _TestClass.__init__ -> TestResults(failed=0, attempted=2)
+ _TestClass.get -> TestResults(failed=0, attempted=2)
+ _TestClass.square -> TestResults(failed=0, attempted=1)
+
+ The `summarize` method prints a summary of all the test cases that
+ have been run by the runner, and returns an aggregated TestResults
+ instance:
+
+ >>> runner.summarize(verbose=1)
+ 4 items passed all tests:
+ 2 tests in _TestClass
+ 2 tests in _TestClass.__init__
+ 2 tests in _TestClass.get
+ 1 test in _TestClass.square
+ 7 tests in 4 items.
+ 7 passed.
+ Test passed.
+ TestResults(failed=0, attempted=7)
+
+ The aggregated number of tried examples and failed examples is also
+ available via the `tries`, `failures` and `skips` attributes:
+
+ >>> runner.tries
+ 7
+ >>> runner.failures
+ 0
+ >>> runner.skips
+ 0
+
+ The comparison between expected outputs and actual outputs is done
+ by an `OutputChecker`. This comparison may be customized with a
+ number of option flags; see the documentation for `testmod` for
+ more information. If the option flags are insufficient, then the
+ comparison may also be customized by passing a subclass of
+ `OutputChecker` to the constructor.
+
+ The test runner's display output can be controlled in two ways.
+ First, an output function (`out`) can be passed to
+ `TestRunner.run`; this function will be called with strings that
+ should be displayed. It defaults to `sys.stdout.write`. If
+ capturing the output is not sufficient, then the display output
+ can be also customized by subclassing DocTestRunner, and
+ overriding the methods `report_start`, `report_success`,
+ `report_unexpected_exception`, and `report_failure`.
+
+ >>> _colorize.COLORIZE = save_colorize
+ """
+ # This divider string is used to separate failure messages, and to
+ # separate sections of the summary.
+ DIVIDER = "*" * 70
+
+ def __init__(self, checker=None, verbose=None, optionflags=0):
+ """
+ Create a new test runner.
+
+ Optional keyword arg `checker` is the `OutputChecker` that
+ should be used to compare the expected outputs and actual
+ outputs of doctest examples.
+
+ Optional keyword arg 'verbose' prints lots of stuff if true,
+ only failures if false; by default, it's true iff '-v' is in
+ sys.argv.
+
+ Optional argument `optionflags` can be used to control how the
+ test runner compares expected output to actual output, and how
+ it displays failures. See the documentation for `testmod` for
+ more information.
+ """
+ self._checker = checker or OutputChecker()
+ if verbose is None:
+ verbose = '-v' in sys.argv
+ self._verbose = verbose
+ self.optionflags = optionflags
+ self.original_optionflags = optionflags
+
+ # Keep track of the examples we've run.
+ self.tries = 0
+ self.failures = 0
+ self.skips = 0
+ self._stats = {}
+
+ # Create a fake output target for capturing doctest output.
+ self._fakeout = _SpoofOut()
+
+ #/////////////////////////////////////////////////////////////////
+ # Reporting methods
+ #/////////////////////////////////////////////////////////////////
+
+ def report_start(self, out, test, example):
+ """
+ Report that the test runner is about to process the given
+ example. (Only displays a message if verbose=True)
+ """
+ if self._verbose:
+ if example.want:
+ out('Trying:\n' + _indent(example.source) +
+ 'Expecting:\n' + _indent(example.want))
+ else:
+ out('Trying:\n' + _indent(example.source) +
+ 'Expecting nothing\n')
+
+ def report_success(self, out, test, example, got):
+ """
+ Report that the given example ran successfully. (Only
+ displays a message if verbose=True)
+ """
+ if self._verbose:
+ out("ok\n")
+
+ def report_failure(self, out, test, example, got):
+ """
+ Report that the given example failed.
+ """
+ out(self._failure_header(test, example) +
+ self._checker.output_difference(example, got, self.optionflags))
+
+ def report_unexpected_exception(self, out, test, example, exc_info):
+ """
+ Report that the given example raised an unexpected exception.
+ """
+ out(self._failure_header(test, example) +
+ 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
+
+ def _failure_header(self, test, example):
+ red, reset = (
+ (ANSIColors.RED, ANSIColors.RESET) if can_colorize() else ("", "")
+ )
+ out = [f"{red}{self.DIVIDER}{reset}"]
+ if test.filename:
+ if test.lineno is not None and example.lineno is not None:
+ lineno = test.lineno + example.lineno + 1
+ else:
+ lineno = '?'
+ out.append('File "%s", line %s, in %s' %
+ (test.filename, lineno, test.name))
+ else:
+ out.append('Line %s, in %s' % (example.lineno+1, test.name))
+ out.append('Failed example:')
+ source = example.source
+ out.append(_indent(source))
+ return '\n'.join(out)
+
+ #/////////////////////////////////////////////////////////////////
+ # DocTest Running
+ #/////////////////////////////////////////////////////////////////
+
+ def __run(self, test, compileflags, out):
+ """
+ Run the examples in `test`. Write the outcome of each example
+ with one of the `DocTestRunner.report_*` methods, using the
+ writer function `out`. `compileflags` is the set of compiler
+ flags that should be used to execute examples. Return a TestResults
+ instance. The examples are run in the namespace `test.globs`.
+ """
+ # Keep track of the number of failed, attempted, skipped examples.
+ failures = attempted = skips = 0
+
+ # Save the option flags (since option directives can be used
+ # to modify them).
+ original_optionflags = self.optionflags
+
+ SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
+
+ check = self._checker.check_output
+
+ # Process each example.
+ for examplenum, example in enumerate(test.examples):
+ attempted += 1
+
+ # If REPORT_ONLY_FIRST_FAILURE is set, then suppress
+ # reporting after the first failure.
+ quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
+ failures > 0)
+
+ # Merge in the example's options.
+ self.optionflags = original_optionflags
+ if example.options:
+ for (optionflag, val) in example.options.items():
+ if val:
+ self.optionflags |= optionflag
+ else:
+ self.optionflags &= ~optionflag
+
+ # If 'SKIP' is set, then skip this example.
+ if self.optionflags & SKIP:
+ skips += 1
+ continue
+
+ # Record that we started this example.
+ if not quiet:
+ self.report_start(out, test, example)
+
+ # Use a special filename for compile(), so we can retrieve
+ # the source code during interactive debugging (see
+ # __patched_linecache_getlines).
+ filename = '' % (test.name, examplenum)
+
+ # Run the example in the given context (globs), and record
+ # any exception that gets raised. (But don't intercept
+ # keyboard interrupts.)
+ try:
+ # Don't blink! This is where the user's code gets run.
+ exec(compile(example.source, filename, "single",
+ compileflags, True), test.globs)
+ self.debugger.set_continue() # ==== Example Finished ====
+ exc_info = None
+ except KeyboardInterrupt:
+ raise
+ except BaseException as exc:
+ exc_info = type(exc), exc, exc.__traceback__.tb_next
+ self.debugger.set_continue() # ==== Example Finished ====
+
+ got = self._fakeout.getvalue() # the actual output
+ self._fakeout.truncate(0)
+ outcome = FAILURE # guilty until proved innocent or insane
+
+ # If the example executed without raising any exceptions,
+ # verify its output.
+ if exc_info is None:
+ if check(example.want, got, self.optionflags):
+ outcome = SUCCESS
+
+ # The example raised an exception: check if it was expected.
+ else:
+ formatted_ex = traceback.format_exception_only(*exc_info[:2])
+ if issubclass(exc_info[0], SyntaxError):
+ # SyntaxError / IndentationError is special:
+ # we don't care about the carets / suggestions / etc
+ # We only care about the error message and notes.
+ # They start with `SyntaxError:` (or any other class name)
+ exception_line_prefixes = (
+ f"{exc_info[0].__qualname__}:",
+ f"{exc_info[0].__module__}.{exc_info[0].__qualname__}:",
+ )
+ exc_msg_index = next(
+ index
+ for index, line in enumerate(formatted_ex)
+ if line.startswith(exception_line_prefixes)
+ )
+ formatted_ex = formatted_ex[exc_msg_index:]
+
+ exc_msg = "".join(formatted_ex)
+ if not quiet:
+ got += _exception_traceback(exc_info)
+
+ # If `example.exc_msg` is None, then we weren't expecting
+ # an exception.
+ if example.exc_msg is None:
+ outcome = BOOM
+
+ # We expected an exception: see whether it matches.
+ elif check(example.exc_msg, exc_msg, self.optionflags):
+ outcome = SUCCESS
+
+ # Another chance if they didn't care about the detail.
+ elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
+ if check(_strip_exception_details(example.exc_msg),
+ _strip_exception_details(exc_msg),
+ self.optionflags):
+ outcome = SUCCESS
+
+ # Report the outcome.
+ if outcome is SUCCESS:
+ if not quiet:
+ self.report_success(out, test, example, got)
+ elif outcome is FAILURE:
+ if not quiet:
+ self.report_failure(out, test, example, got)
+ failures += 1
+ elif outcome is BOOM:
+ if not quiet:
+ self.report_unexpected_exception(out, test, example,
+ exc_info)
+ failures += 1
+ else:
+ assert False, ("unknown outcome", outcome)
+
+ if failures and self.optionflags & FAIL_FAST:
+ break
+
+ # Restore the option flags (in case they were modified)
+ self.optionflags = original_optionflags
+
+ # Record and return the number of failures and attempted.
+ self.__record_outcome(test, failures, attempted, skips)
+ return TestResults(failures, attempted, skipped=skips)
+
+ def __record_outcome(self, test, failures, tries, skips):
+ """
+ Record the fact that the given DocTest (`test`) generated `failures`
+ failures out of `tries` tried examples.
+ """
+ failures2, tries2, skips2 = self._stats.get(test.name, (0, 0, 0))
+ self._stats[test.name] = (failures + failures2,
+ tries + tries2,
+ skips + skips2)
+ self.failures += failures
+ self.tries += tries
+ self.skips += skips
+
+ __LINECACHE_FILENAME_RE = re.compile(r'.+)'
+ r'\[(?P\d+)\]>$')
+ def __patched_linecache_getlines(self, filename, module_globals=None):
+ m = self.__LINECACHE_FILENAME_RE.match(filename)
+ if m and m.group('name') == self.test.name:
+ example = self.test.examples[int(m.group('examplenum'))]
+ return example.source.splitlines(keepends=True)
+ else:
+ return self.save_linecache_getlines(filename, module_globals)
+
+ def run(self, test, compileflags=None, out=None, clear_globs=True):
+ """
+ Run the examples in `test`, and display the results using the
+ writer function `out`.
+
+ The examples are run in the namespace `test.globs`. If
+ `clear_globs` is true (the default), then this namespace will
+ be cleared after the test runs, to help with garbage
+ collection. If you would like to examine the namespace after
+ the test completes, then use `clear_globs=False`.
+
+ `compileflags` gives the set of flags that should be used by
+ the Python compiler when running the examples. If not
+ specified, then it will default to the set of future-import
+ flags that apply to `globs`.
+
+ The output of each example is checked using
+ `DocTestRunner.check_output`, and the results are formatted by
+ the `DocTestRunner.report_*` methods.
+ """
+ self.test = test
+
+ if compileflags is None:
+ compileflags = _extract_future_flags(test.globs)
+
+ save_stdout = sys.stdout
+ if out is None:
+ encoding = save_stdout.encoding
+ if encoding is None or encoding.lower() == 'utf-8':
+ out = save_stdout.write
+ else:
+ # Use backslashreplace error handling on write
+ def out(s):
+ s = str(s.encode(encoding, 'backslashreplace'), encoding)
+ save_stdout.write(s)
+ sys.stdout = self._fakeout
+
+ # Patch pdb.set_trace to restore sys.stdout during interactive
+ # debugging (so it's not still redirected to self._fakeout).
+ # Note that the interactive output will go to *our*
+ # save_stdout, even if that's not the real sys.stdout; this
+ # allows us to write test cases for the set_trace behavior.
+ save_trace = sys.gettrace()
+ save_set_trace = pdb.set_trace
+ self.debugger = _OutputRedirectingPdb(save_stdout)
+ self.debugger.reset()
+ pdb.set_trace = self.debugger.set_trace
+
+ # Patch linecache.getlines, so we can see the example's source
+ # when we're inside the debugger.
+ self.save_linecache_getlines = linecache.getlines
+ linecache.getlines = self.__patched_linecache_getlines
+
+ # Make sure sys.displayhook just prints the value to stdout
+ save_displayhook = sys.displayhook
+ sys.displayhook = sys.__displayhook__
+ saved_can_colorize = _colorize.can_colorize
+ _colorize.can_colorize = lambda *args, **kwargs: False
+ color_variables = {"PYTHON_COLORS": None, "FORCE_COLOR": None}
+ for key in color_variables:
+ color_variables[key] = os.environ.pop(key, None)
+ try:
+ return self.__run(test, compileflags, out)
+ finally:
+ sys.stdout = save_stdout
+ pdb.set_trace = save_set_trace
+ sys.settrace(save_trace)
+ linecache.getlines = self.save_linecache_getlines
+ sys.displayhook = save_displayhook
+ _colorize.can_colorize = saved_can_colorize
+ for key, value in color_variables.items():
+ if value is not None:
+ os.environ[key] = value
+ if clear_globs:
+ test.globs.clear()
+ import builtins
+ builtins._ = None
+
+ #/////////////////////////////////////////////////////////////////
+ # Summarization
+ #/////////////////////////////////////////////////////////////////
+ def summarize(self, verbose=None):
+ """
+ Print a summary of all the test cases that have been run by
+ this DocTestRunner, and return a TestResults instance.
+
+ The optional `verbose` argument controls how detailed the
+ summary is. If the verbosity is not specified, then the
+ DocTestRunner's verbosity is used.
+ """
+ if verbose is None:
+ verbose = self._verbose
+
+ notests, passed, failed = [], [], []
+ total_tries = total_failures = total_skips = 0
+
+ for name, (failures, tries, skips) in self._stats.items():
+ assert failures <= tries
+ total_tries += tries
+ total_failures += failures
+ total_skips += skips
+
+ if tries == 0:
+ notests.append(name)
+ elif failures == 0:
+ passed.append((name, tries))
+ else:
+ failed.append((name, (failures, tries, skips)))
+
+ ansi = _colorize.get_colors()
+ bold_green = ansi.BOLD_GREEN
+ bold_red = ansi.BOLD_RED
+ green = ansi.GREEN
+ red = ansi.RED
+ reset = ansi.RESET
+ yellow = ansi.YELLOW
+
+ if verbose:
+ if notests:
+ print(f"{_n_items(notests)} had no tests:")
+ notests.sort()
+ for name in notests:
+ print(f" {name}")
+
+ if passed:
+ print(f"{green}{_n_items(passed)} passed all tests:{reset}")
+ for name, count in sorted(passed):
+ s = "" if count == 1 else "s"
+ print(f" {green}{count:3d} test{s} in {name}{reset}")
+
+ if failed:
+ print(f"{red}{self.DIVIDER}{reset}")
+ print(f"{_n_items(failed)} had failures:")
+ for name, (failures, tries, skips) in sorted(failed):
+ print(f" {failures:3d} of {tries:3d} in {name}")
+
+ if verbose:
+ s = "" if total_tries == 1 else "s"
+ print(f"{total_tries} test{s} in {_n_items(self._stats)}.")
+
+ and_f = (
+ f" and {red}{total_failures} failed{reset}"
+ if total_failures else ""
+ )
+ print(f"{green}{total_tries - total_failures} passed{reset}{and_f}.")
+
+ if total_failures:
+ s = "" if total_failures == 1 else "s"
+ msg = f"{bold_red}***Test Failed*** {total_failures} failure{s}{reset}"
+ if total_skips:
+ s = "" if total_skips == 1 else "s"
+ msg = f"{msg} and {yellow}{total_skips} skipped test{s}{reset}"
+ print(f"{msg}.")
+ elif verbose:
+ print(f"{bold_green}Test passed.{reset}")
+
+ return TestResults(total_failures, total_tries, skipped=total_skips)
+
+ #/////////////////////////////////////////////////////////////////
+ # Backward compatibility cruft to maintain doctest.master.
+ #/////////////////////////////////////////////////////////////////
+ def merge(self, other):
+ d = self._stats
+ for name, (failures, tries, skips) in other._stats.items():
+ if name in d:
+ failures2, tries2, skips2 = d[name]
+ failures = failures + failures2
+ tries = tries + tries2
+ skips = skips + skips2
+ d[name] = (failures, tries, skips)
+
+
+def _n_items(items: list | dict) -> str:
+ """
+ Helper to pluralise the number of items in a list.
+ """
+ n = len(items)
+ s = "" if n == 1 else "s"
+ return f"{n} item{s}"
+
+
+class OutputChecker:
+ """
+ A class used to check whether the actual output from a doctest
+ example matches the expected output. `OutputChecker` defines two
+ methods: `check_output`, which compares a given pair of outputs,
+ and returns true if they match; and `output_difference`, which
+ returns a string describing the differences between two outputs.
+ """
+ def _toAscii(self, s):
+ """
+ Convert string to hex-escaped ASCII string.
+ """
+ return str(s.encode('ASCII', 'backslashreplace'), "ASCII")
+
+ def check_output(self, want, got, optionflags):
+ """
+ Return True iff the actual output from an example (`got`)
+ matches the expected output (`want`). These strings are
+ always considered to match if they are identical; but
+ depending on what option flags the test runner is using,
+ several non-exact match types are also possible. See the
+ documentation for `TestRunner` for more information about
+ option flags.
+ """
+
+ # If `want` contains hex-escaped character such as "\u1234",
+ # then `want` is a string of six characters(e.g. [\,u,1,2,3,4]).
+ # On the other hand, `got` could be another sequence of
+ # characters such as [\u1234], so `want` and `got` should
+ # be folded to hex-escaped ASCII string to compare.
+ got = self._toAscii(got)
+ want = self._toAscii(want)
+
+ # Handle the common case first, for efficiency:
+ # if they're string-identical, always return true.
+ if got == want:
+ return True
+
+ # The values True and False replaced 1 and 0 as the return
+ # value for boolean comparisons in Python 2.3.
+ if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
+ if (got,want) == ("True\n", "1\n"):
+ return True
+ if (got,want) == ("False\n", "0\n"):
+ return True
+
+ # can be used as a special sequence to signify a
+ # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
+ if not (optionflags & DONT_ACCEPT_BLANKLINE):
+ # Replace in want with a blank line.
+ want = re.sub(r'(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
+ '', want)
+ # If a line in got contains only spaces, then remove the
+ # spaces.
+ got = re.sub(r'(?m)^[^\S\n]+$', '', got)
+ if got == want:
+ return True
+
+ # This flag causes doctest to ignore any differences in the
+ # contents of whitespace strings. Note that this can be used
+ # in conjunction with the ELLIPSIS flag.
+ if optionflags & NORMALIZE_WHITESPACE:
+ got = ' '.join(got.split())
+ want = ' '.join(want.split())
+ if got == want:
+ return True
+
+ # The ELLIPSIS flag says to let the sequence "..." in `want`
+ # match any substring in `got`.
+ if optionflags & ELLIPSIS:
+ if _ellipsis_match(want, got):
+ return True
+
+ # We didn't find any match; return false.
+ return False
+
+ # Should we do a fancy diff?
+ def _do_a_fancy_diff(self, want, got, optionflags):
+ # Not unless they asked for a fancy diff.
+ if not optionflags & (REPORT_UDIFF |
+ REPORT_CDIFF |
+ REPORT_NDIFF):
+ return False
+
+ # If expected output uses ellipsis, a meaningful fancy diff is
+ # too hard ... or maybe not. In two real-life failures Tim saw,
+ # a diff was a major help anyway, so this is commented out.
+ # [todo] _ellipsis_match() knows which pieces do and don't match,
+ # and could be the basis for a kick-ass diff in this case.
+ ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
+ ## return False
+
+ # ndiff does intraline difference marking, so can be useful even
+ # for 1-line differences.
+ if optionflags & REPORT_NDIFF:
+ return True
+
+ # The other diff types need at least a few lines to be helpful.
+ return want.count('\n') > 2 and got.count('\n') > 2
+
+ def output_difference(self, example, got, optionflags):
+ """
+ Return a string describing the differences between the
+ expected output for a given example (`example`) and the actual
+ output (`got`). `optionflags` is the set of option flags used
+ to compare `want` and `got`.
+ """
+ want = example.want
+ # If s are being used, then replace blank lines
+ # with in the actual output string.
+ if not (optionflags & DONT_ACCEPT_BLANKLINE):
+ got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
+
+ # Check if we should use diff.
+ if self._do_a_fancy_diff(want, got, optionflags):
+ # Split want & got into lines.
+ want_lines = want.splitlines(keepends=True)
+ got_lines = got.splitlines(keepends=True)
+ # Use difflib to find their differences.
+ if optionflags & REPORT_UDIFF:
+ diff = difflib.unified_diff(want_lines, got_lines, n=2)
+ diff = list(diff)[2:] # strip the diff header
+ kind = 'unified diff with -expected +actual'
+ elif optionflags & REPORT_CDIFF:
+ diff = difflib.context_diff(want_lines, got_lines, n=2)
+ diff = list(diff)[2:] # strip the diff header
+ kind = 'context diff with expected followed by actual'
+ elif optionflags & REPORT_NDIFF:
+ engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
+ diff = list(engine.compare(want_lines, got_lines))
+ kind = 'ndiff with -expected +actual'
+ else:
+ assert 0, 'Bad diff option'
+ return 'Differences (%s):\n' % kind + _indent(''.join(diff))
+
+ # If we're not using diff, then simply list the expected
+ # output followed by the actual output.
+ if want and got:
+ return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
+ elif want:
+ return 'Expected:\n%sGot nothing\n' % _indent(want)
+ elif got:
+ return 'Expected nothing\nGot:\n%s' % _indent(got)
+ else:
+ return 'Expected nothing\nGot nothing\n'
+
+class DocTestFailure(Exception):
+ """A DocTest example has failed in debugging mode.
+
+ The exception instance has variables:
+
+ - test: the DocTest object being run
+
+ - example: the Example object that failed
+
+ - got: the actual output
+ """
+ def __init__(self, test, example, got):
+ self.test = test
+ self.example = example
+ self.got = got
+
+ def __str__(self):
+ return str(self.test)
+
+class UnexpectedException(Exception):
+ """A DocTest example has encountered an unexpected exception
+
+ The exception instance has variables:
+
+ - test: the DocTest object being run
+
+ - example: the Example object that failed
+
+ - exc_info: the exception info
+ """
+ def __init__(self, test, example, exc_info):
+ self.test = test
+ self.example = example
+ self.exc_info = exc_info
+
+ def __str__(self):
+ return str(self.test)
+
+class DebugRunner(DocTestRunner):
+ r"""Run doc tests but raise an exception as soon as there is a failure.
+
+ If an unexpected exception occurs, an UnexpectedException is raised.
+ It contains the test, the example, and the original exception:
+
+ >>> runner = DebugRunner(verbose=False)
+ >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
+ ... {}, 'foo', 'foo.py', 0)
+ >>> try:
+ ... runner.run(test)
+ ... except UnexpectedException as f:
+ ... failure = f
+
+ >>> failure.test is test
+ True
+
+ >>> failure.example.want
+ '42\n'
+
+ >>> exc_info = failure.exc_info
+ >>> raise exc_info[1] # Already has the traceback
+ Traceback (most recent call last):
+ ...
+ KeyError
+
+ We wrap the original exception to give the calling application
+ access to the test and example information.
+
+ If the output doesn't match, then a DocTestFailure is raised:
+
+ >>> test = DocTestParser().get_doctest('''
+ ... >>> x = 1
+ ... >>> x
+ ... 2
+ ... ''', {}, 'foo', 'foo.py', 0)
+
+ >>> try:
+ ... runner.run(test)
+ ... except DocTestFailure as f:
+ ... failure = f
+
+ DocTestFailure objects provide access to the test:
+
+ >>> failure.test is test
+ True
+
+ As well as to the example:
+
+ >>> failure.example.want
+ '2\n'
+
+ and the actual output:
+
+ >>> failure.got
+ '1\n'
+
+ If a failure or error occurs, the globals are left intact:
+
+ >>> del test.globs['__builtins__']
+ >>> test.globs
+ {'x': 1}
+
+ >>> test = DocTestParser().get_doctest('''
+ ... >>> x = 2
+ ... >>> raise KeyError
+ ... ''', {}, 'foo', 'foo.py', 0)
+
+ >>> runner.run(test)
+ Traceback (most recent call last):
+ ...
+ doctest.UnexpectedException:
+
+ >>> del test.globs['__builtins__']
+ >>> test.globs
+ {'x': 2}
+
+ But the globals are cleared if there is no error:
+
+ >>> test = DocTestParser().get_doctest('''
+ ... >>> x = 2
+ ... ''', {}, 'foo', 'foo.py', 0)
+
+ >>> runner.run(test)
+ TestResults(failed=0, attempted=1)
+
+ >>> test.globs
+ {}
+
+ """
+
+ def run(self, test, compileflags=None, out=None, clear_globs=True):
+ r = DocTestRunner.run(self, test, compileflags, out, False)
+ if clear_globs:
+ test.globs.clear()
+ return r
+
+ def report_unexpected_exception(self, out, test, example, exc_info):
+ raise UnexpectedException(test, example, exc_info)
+
+ def report_failure(self, out, test, example, got):
+ raise DocTestFailure(test, example, got)
+
+######################################################################
+## 6. Test Functions
+######################################################################
+# These should be backwards compatible.
+
+# For backward compatibility, a global instance of a DocTestRunner
+# class, updated by testmod.
+master = None
+
+def testmod(m=None, name=None, globs=None, verbose=None,
+ report=True, optionflags=0, extraglobs=None,
+ raise_on_error=False, exclude_empty=False):
+ """m=None, name=None, globs=None, verbose=None, report=True,
+ optionflags=0, extraglobs=None, raise_on_error=False,
+ exclude_empty=False
+
+ Test examples in docstrings in functions and classes reachable
+ from module m (or the current module if m is not supplied), starting
+ with m.__doc__.
+
+ Also test examples reachable from dict m.__test__ if it exists.
+ m.__test__ maps names to functions, classes and strings;
+ function and class docstrings are tested even if the name is private;
+ strings are tested directly, as if they were docstrings.
+
+ Return (#failures, #tests).
+
+ See help(doctest) for an overview.
+
+ Optional keyword arg "name" gives the name of the module; by default
+ use m.__name__.
+
+ Optional keyword arg "globs" gives a dict to be used as the globals
+ when executing examples; by default, use m.__dict__. A copy of this
+ dict is actually used for each docstring, so that each docstring's
+ examples start with a clean slate.
+
+ Optional keyword arg "extraglobs" gives a dictionary that should be
+ merged into the globals that are used to execute examples. By
+ default, no extra globals are used. This is new in 2.4.
+
+ Optional keyword arg "verbose" prints lots of stuff if true, prints
+ only failures if false; by default, it's true iff "-v" is in sys.argv.
+
+ Optional keyword arg "report" prints a summary at the end when true,
+ else prints nothing at the end. In verbose mode, the summary is
+ detailed, else very brief (in fact, empty if all tests passed).
+
+ Optional keyword arg "optionflags" or's together module constants,
+ and defaults to 0. This is new in 2.3. Possible values (see the
+ docs for details):
+
+ DONT_ACCEPT_TRUE_FOR_1
+ DONT_ACCEPT_BLANKLINE
+ NORMALIZE_WHITESPACE
+ ELLIPSIS
+ SKIP
+ IGNORE_EXCEPTION_DETAIL
+ REPORT_UDIFF
+ REPORT_CDIFF
+ REPORT_NDIFF
+ REPORT_ONLY_FIRST_FAILURE
+
+ Optional keyword arg "raise_on_error" raises an exception on the
+ first unexpected exception or failure. This allows failures to be
+ post-mortem debugged.
+
+ Advanced tomfoolery: testmod runs methods of a local instance of
+ class doctest.Tester, then merges the results into (or creates)
+ global Tester instance doctest.master. Methods of doctest.master
+ can be called directly too, if you want to do something unusual.
+ Passing report=0 to testmod is especially useful then, to delay
+ displaying a summary. Invoke doctest.master.summarize(verbose)
+ when you're done fiddling.
+ """
+ global master
+
+ # If no module was given, then use __main__.
+ if m is None:
+ # DWA - m will still be None if this wasn't invoked from the command
+ # line, in which case the following TypeError is about as good an error
+ # as we should expect
+ m = sys.modules.get('__main__')
+
+ # Check that we were actually given a module.
+ if not inspect.ismodule(m):
+ raise TypeError("testmod: module required; %r" % (m,))
+
+ # If no name was given, then use the module's name.
+ if name is None:
+ name = m.__name__
+
+ # Find, parse, and run all tests in the given module.
+ finder = DocTestFinder(exclude_empty=exclude_empty)
+
+ if raise_on_error:
+ runner = DebugRunner(verbose=verbose, optionflags=optionflags)
+ else:
+ runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
+
+ for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
+ runner.run(test)
+
+ if report:
+ runner.summarize()
+
+ if master is None:
+ master = runner
+ else:
+ master.merge(runner)
+
+ return TestResults(runner.failures, runner.tries, skipped=runner.skips)
+
+
+def testfile(filename, module_relative=True, name=None, package=None,
+ globs=None, verbose=None, report=True, optionflags=0,
+ extraglobs=None, raise_on_error=False, parser=DocTestParser(),
+ encoding=None):
+ """
+ Test examples in the given file. Return (#failures, #tests).
+
+ Optional keyword arg "module_relative" specifies how filenames
+ should be interpreted:
+
+ - If "module_relative" is True (the default), then "filename"
+ specifies a module-relative path. By default, this path is
+ relative to the calling module's directory; but if the
+ "package" argument is specified, then it is relative to that
+ package. To ensure os-independence, "filename" should use
+ "/" characters to separate path segments, and should not
+ be an absolute path (i.e., it may not begin with "/").
+
+ - If "module_relative" is False, then "filename" specifies an
+ os-specific path. The path may be absolute or relative (to
+ the current working directory).
+
+ Optional keyword arg "name" gives the name of the test; by default
+ use the file's basename.
+
+ Optional keyword argument "package" is a Python package or the
+ name of a Python package whose directory should be used as the
+ base directory for a module relative filename. If no package is
+ specified, then the calling module's directory is used as the base
+ directory for module relative filenames. It is an error to
+ specify "package" if "module_relative" is False.
+
+ Optional keyword arg "globs" gives a dict to be used as the globals
+ when executing examples; by default, use {}. A copy of this dict
+ is actually used for each docstring, so that each docstring's
+ examples start with a clean slate.
+
+ Optional keyword arg "extraglobs" gives a dictionary that should be
+ merged into the globals that are used to execute examples. By
+ default, no extra globals are used.
+
+ Optional keyword arg "verbose" prints lots of stuff if true, prints
+ only failures if false; by default, it's true iff "-v" is in sys.argv.
+
+ Optional keyword arg "report" prints a summary at the end when true,
+ else prints nothing at the end. In verbose mode, the summary is
+ detailed, else very brief (in fact, empty if all tests passed).
+
+ Optional keyword arg "optionflags" or's together module constants,
+ and defaults to 0. Possible values (see the docs for details):
+
+ DONT_ACCEPT_TRUE_FOR_1
+ DONT_ACCEPT_BLANKLINE
+ NORMALIZE_WHITESPACE
+ ELLIPSIS
+ SKIP
+ IGNORE_EXCEPTION_DETAIL
+ REPORT_UDIFF
+ REPORT_CDIFF
+ REPORT_NDIFF
+ REPORT_ONLY_FIRST_FAILURE
+
+ Optional keyword arg "raise_on_error" raises an exception on the
+ first unexpected exception or failure. This allows failures to be
+ post-mortem debugged.
+
+ Optional keyword arg "parser" specifies a DocTestParser (or
+ subclass) that should be used to extract tests from the files.
+
+ Optional keyword arg "encoding" specifies an encoding that should
+ be used to convert the file to unicode.
+
+ Advanced tomfoolery: testmod runs methods of a local instance of
+ class doctest.Tester, then merges the results into (or creates)
+ global Tester instance doctest.master. Methods of doctest.master
+ can be called directly too, if you want to do something unusual.
+ Passing report=0 to testmod is especially useful then, to delay
+ displaying a summary. Invoke doctest.master.summarize(verbose)
+ when you're done fiddling.
+ """
+ global master
+
+ if package and not module_relative:
+ raise ValueError("Package may only be specified for module-"
+ "relative paths.")
+
+ # Relativize the path
+ text, filename = _load_testfile(filename, package, module_relative,
+ encoding or "utf-8")
+
+ # If no name was given, then use the file's name.
+ if name is None:
+ name = os.path.basename(filename)
+
+ # Assemble the globals.
+ if globs is None:
+ globs = {}
+ else:
+ globs = globs.copy()
+ if extraglobs is not None:
+ globs.update(extraglobs)
+ if '__name__' not in globs:
+ globs['__name__'] = '__main__'
+
+ if raise_on_error:
+ runner = DebugRunner(verbose=verbose, optionflags=optionflags)
+ else:
+ runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
+
+ # Read the file, convert it to a test, and run it.
+ test = parser.get_doctest(text, globs, name, filename, 0)
+ runner.run(test)
+
+ if report:
+ runner.summarize()
+
+ if master is None:
+ master = runner
+ else:
+ master.merge(runner)
+
+ return TestResults(runner.failures, runner.tries, skipped=runner.skips)
+
+
+def run_docstring_examples(f, globs, verbose=False, name="NoName",
+ compileflags=None, optionflags=0):
+ """
+ Test examples in the given object's docstring (`f`), using `globs`
+ as globals. Optional argument `name` is used in failure messages.
+ If the optional argument `verbose` is true, then generate output
+ even if there are no failures.
+
+ `compileflags` gives the set of flags that should be used by the
+ Python compiler when running the examples. If not specified, then
+ it will default to the set of future-import flags that apply to
+ `globs`.
+
+ Optional keyword arg `optionflags` specifies options for the
+ testing and output. See the documentation for `testmod` for more
+ information.
+ """
+ # Find, parse, and run all tests in the given module.
+ finder = DocTestFinder(verbose=verbose, recurse=False)
+ runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
+ for test in finder.find(f, name, globs=globs):
+ runner.run(test, compileflags=compileflags)
+
+######################################################################
+## 7. Unittest Support
+######################################################################
+
+_unittest_reportflags = 0
+
+def set_unittest_reportflags(flags):
+ """Sets the unittest option flags.
+
+ The old flag is returned so that a runner could restore the old
+ value if it wished to:
+
+ >>> import doctest
+ >>> old = doctest._unittest_reportflags
+ >>> doctest.set_unittest_reportflags(REPORT_NDIFF |
+ ... REPORT_ONLY_FIRST_FAILURE) == old
+ True
+
+ >>> doctest._unittest_reportflags == (REPORT_NDIFF |
+ ... REPORT_ONLY_FIRST_FAILURE)
+ True
+
+ Only reporting flags can be set:
+
+ >>> doctest.set_unittest_reportflags(ELLIPSIS)
+ Traceback (most recent call last):
+ ...
+ ValueError: ('Only reporting flags allowed', 8)
+
+ >>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF |
+ ... REPORT_ONLY_FIRST_FAILURE)
+ True
+ """
+ global _unittest_reportflags
+
+ if (flags & REPORTING_FLAGS) != flags:
+ raise ValueError("Only reporting flags allowed", flags)
+ old = _unittest_reportflags
+ _unittest_reportflags = flags
+ return old
+
+
+class DocTestCase(unittest.TestCase):
+
+ def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
+ checker=None):
+
+ unittest.TestCase.__init__(self)
+ self._dt_optionflags = optionflags
+ self._dt_checker = checker
+ self._dt_test = test
+ self._dt_setUp = setUp
+ self._dt_tearDown = tearDown
+
+ def setUp(self):
+ test = self._dt_test
+ self._dt_globs = test.globs.copy()
+
+ if self._dt_setUp is not None:
+ self._dt_setUp(test)
+
+ def tearDown(self):
+ test = self._dt_test
+
+ if self._dt_tearDown is not None:
+ self._dt_tearDown(test)
+
+ # restore the original globs
+ test.globs.clear()
+ test.globs.update(self._dt_globs)
+
+ def runTest(self):
+ test = self._dt_test
+ old = sys.stdout
+ new = StringIO()
+ optionflags = self._dt_optionflags
+
+ if not (optionflags & REPORTING_FLAGS):
+ # The option flags don't include any reporting flags,
+ # so add the default reporting flags
+ optionflags |= _unittest_reportflags
+
+ runner = DocTestRunner(optionflags=optionflags,
+ checker=self._dt_checker, verbose=False)
+
+ try:
+ runner.DIVIDER = "-"*70
+ results = runner.run(test, out=new.write, clear_globs=False)
+ if results.skipped == results.attempted:
+ raise unittest.SkipTest("all examples were skipped")
+ finally:
+ sys.stdout = old
+
+ if results.failed:
+ raise self.failureException(self.format_failure(new.getvalue().rstrip('\n')))
+
+ def format_failure(self, err):
+ test = self._dt_test
+ if test.lineno is None:
+ lineno = 'unknown line number'
+ else:
+ lineno = '%s' % test.lineno
+ lname = '.'.join(test.name.split('.')[-1:])
+ return ('Failed doctest test for %s\n'
+ ' File "%s", line %s, in %s\n\n%s'
+ % (test.name, test.filename, lineno, lname, err)
+ )
+
+ def debug(self):
+ r"""Run the test case without results and without catching exceptions
+
+ The unit test framework includes a debug method on test cases
+ and test suites to support post-mortem debugging. The test code
+ is run in such a way that errors are not caught. This way a
+ caller can catch the errors and initiate post-mortem debugging.
+
+ The DocTestCase provides a debug method that raises
+ UnexpectedException errors if there is an unexpected
+ exception:
+
+ >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
+ ... {}, 'foo', 'foo.py', 0)
+ >>> case = DocTestCase(test)
+ >>> try:
+ ... case.debug()
+ ... except UnexpectedException as f:
+ ... failure = f
+
+ The UnexpectedException contains the test, the example, and
+ the original exception:
+
+ >>> failure.test is test
+ True
+
+ >>> failure.example.want
+ '42\n'
+
+ >>> exc_info = failure.exc_info
+ >>> raise exc_info[1] # Already has the traceback
+ Traceback (most recent call last):
+ ...
+ KeyError
+
+ If the output doesn't match, then a DocTestFailure is raised:
+
+ >>> test = DocTestParser().get_doctest('''
+ ... >>> x = 1
+ ... >>> x
+ ... 2
+ ... ''', {}, 'foo', 'foo.py', 0)
+ >>> case = DocTestCase(test)
+
+ >>> try:
+ ... case.debug()
+ ... except DocTestFailure as f:
+ ... failure = f
+
+ DocTestFailure objects provide access to the test:
+
+ >>> failure.test is test
+ True
+
+ As well as to the example:
+
+ >>> failure.example.want
+ '2\n'
+
+ and the actual output:
+
+ >>> failure.got
+ '1\n'
+
+ """
+
+ self.setUp()
+ runner = DebugRunner(optionflags=self._dt_optionflags,
+ checker=self._dt_checker, verbose=False)
+ runner.run(self._dt_test, clear_globs=False)
+ self.tearDown()
+
+ def id(self):
+ return self._dt_test.name
+
+ def __eq__(self, other):
+ if type(self) is not type(other):
+ return NotImplemented
+
+ return self._dt_test == other._dt_test and \
+ self._dt_optionflags == other._dt_optionflags and \
+ self._dt_setUp == other._dt_setUp and \
+ self._dt_tearDown == other._dt_tearDown and \
+ self._dt_checker == other._dt_checker
+
+ def __hash__(self):
+ return hash((self._dt_optionflags, self._dt_setUp, self._dt_tearDown,
+ self._dt_checker))
+
+ def __repr__(self):
+ name = self._dt_test.name.split('.')
+ return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
+
+ __str__ = object.__str__
+
+ def shortDescription(self):
+ return "Doctest: " + self._dt_test.name
+
+class SkipDocTestCase(DocTestCase):
+ def __init__(self, module):
+ self.module = module
+ DocTestCase.__init__(self, None)
+
+ def setUp(self):
+ self.skipTest("DocTestSuite will not work with -O2 and above")
+
+ def test_skip(self):
+ pass
+
+ def shortDescription(self):
+ return "Skipping tests from %s" % self.module.__name__
+
+ __str__ = shortDescription
+
+
+class _DocTestSuite(unittest.TestSuite):
+
+ def _removeTestAtIndex(self, index):
+ pass
+
+
+def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
+ **options):
+ """
+ Convert doctest tests for a module to a unittest test suite.
+
+ This converts each documentation string in a module that
+ contains doctest tests to a unittest test case. If any of the
+ tests in a doc string fail, then the test case fails. An exception
+ is raised showing the name of the file containing the test and a
+ (sometimes approximate) line number.
+
+ The `module` argument provides the module to be tested. The argument
+ can be either a module or a module name.
+
+ If no argument is given, the calling module is used.
+
+ A number of options may be provided as keyword arguments:
+
+ setUp
+ A set-up function. This is called before running the
+ tests in each file. The setUp function will be passed a DocTest
+ object. The setUp function can access the test globals as the
+ globs attribute of the test passed.
+
+ tearDown
+ A tear-down function. This is called after running the
+ tests in each file. The tearDown function will be passed a DocTest
+ object. The tearDown function can access the test globals as the
+ globs attribute of the test passed.
+
+ globs
+ A dictionary containing initial global variables for the tests.
+
+ optionflags
+ A set of doctest option flags expressed as an integer.
+ """
+
+ if test_finder is None:
+ test_finder = DocTestFinder()
+
+ module = _normalize_module(module)
+ tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
+
+ if not tests and sys.flags.optimize >=2:
+ # Skip doctests when running with -O2
+ suite = _DocTestSuite()
+ suite.addTest(SkipDocTestCase(module))
+ return suite
+
+ tests.sort()
+ suite = _DocTestSuite()
+
+ for test in tests:
+ if len(test.examples) == 0:
+ continue
+ if not test.filename:
+ filename = module.__file__
+ if filename[-4:] == ".pyc":
+ filename = filename[:-1]
+ test.filename = filename
+ suite.addTest(DocTestCase(test, **options))
+
+ return suite
+
+class DocFileCase(DocTestCase):
+
+ def id(self):
+ return '_'.join(self._dt_test.name.split('.'))
+
+ def __repr__(self):
+ return self._dt_test.filename
+
+ def format_failure(self, err):
+ return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
+ % (self._dt_test.name, self._dt_test.filename, err)
+ )
+
+def DocFileTest(path, module_relative=True, package=None,
+ globs=None, parser=DocTestParser(),
+ encoding=None, **options):
+ if globs is None:
+ globs = {}
+ else:
+ globs = globs.copy()
+
+ if package and not module_relative:
+ raise ValueError("Package may only be specified for module-"
+ "relative paths.")
+
+ # Relativize the path.
+ doc, path = _load_testfile(path, package, module_relative,
+ encoding or "utf-8")
+
+ if "__file__" not in globs:
+ globs["__file__"] = path
+
+ # Find the file and read it.
+ name = os.path.basename(path)
+
+ # Convert it to a test, and wrap it in a DocFileCase.
+ test = parser.get_doctest(doc, globs, name, path, 0)
+ return DocFileCase(test, **options)
+
+def DocFileSuite(*paths, **kw):
+ """A unittest suite for one or more doctest files.
+
+ The path to each doctest file is given as a string; the
+ interpretation of that string depends on the keyword argument
+ "module_relative".
+
+ A number of options may be provided as keyword arguments:
+
+ module_relative
+ If "module_relative" is True, then the given file paths are
+ interpreted as os-independent module-relative paths. By
+ default, these paths are relative to the calling module's
+ directory; but if the "package" argument is specified, then
+ they are relative to that package. To ensure os-independence,
+ "filename" should use "/" characters to separate path
+ segments, and may not be an absolute path (i.e., it may not
+ begin with "/").
+
+ If "module_relative" is False, then the given file paths are
+ interpreted as os-specific paths. These paths may be absolute
+ or relative (to the current working directory).
+
+ package
+ A Python package or the name of a Python package whose directory
+ should be used as the base directory for module relative paths.
+ If "package" is not specified, then the calling module's
+ directory is used as the base directory for module relative
+ filenames. It is an error to specify "package" if
+ "module_relative" is False.
+
+ setUp
+ A set-up function. This is called before running the
+ tests in each file. The setUp function will be passed a DocTest
+ object. The setUp function can access the test globals as the
+ globs attribute of the test passed.
+
+ tearDown
+ A tear-down function. This is called after running the
+ tests in each file. The tearDown function will be passed a DocTest
+ object. The tearDown function can access the test globals as the
+ globs attribute of the test passed.
+
+ globs
+ A dictionary containing initial global variables for the tests.
+
+ optionflags
+ A set of doctest option flags expressed as an integer.
+
+ parser
+ A DocTestParser (or subclass) that should be used to extract
+ tests from the files.
+
+ encoding
+ An encoding that will be used to convert the files to unicode.
+ """
+ suite = _DocTestSuite()
+
+ # We do this here so that _normalize_module is called at the right
+ # level. If it were called in DocFileTest, then this function
+ # would be the caller and we might guess the package incorrectly.
+ if kw.get('module_relative', True):
+ kw['package'] = _normalize_module(kw.get('package'))
+
+ for path in paths:
+ suite.addTest(DocFileTest(path, **kw))
+
+ return suite
+
+######################################################################
+## 8. Debugging Support
+######################################################################
+
+def script_from_examples(s):
+ r"""Extract script from text with examples.
+
+ Converts text with examples to a Python script. Example input is
+ converted to regular code. Example output and all other words
+ are converted to comments:
+
+ >>> text = '''
+ ... Here are examples of simple math.
+ ...
+ ... Python has super accurate integer addition
+ ...
+ ... >>> 2 + 2
+ ... 5
+ ...
+ ... And very friendly error messages:
+ ...
+ ... >>> 1/0
+ ... To Infinity
+ ... And
+ ... Beyond
+ ...
+ ... You can use logic if you want:
+ ...
+ ... >>> if 0:
+ ... ... blah
+ ... ... blah
+ ... ...
+ ...
+ ... Ho hum
+ ... '''
+
+ >>> print(script_from_examples(text))
+ # Here are examples of simple math.
+ #
+ # Python has super accurate integer addition
+ #
+ 2 + 2
+ # Expected:
+ ## 5
+ #
+ # And very friendly error messages:
+ #
+ 1/0
+ # Expected:
+ ## To Infinity
+ ## And
+ ## Beyond
+ #
+ # You can use logic if you want:
+ #
+ if 0:
+ blah
+ blah
+ #
+ # Ho hum
+
+ """
+ output = []
+ for piece in DocTestParser().parse(s):
+ if isinstance(piece, Example):
+ # Add the example's source code (strip trailing NL)
+ output.append(piece.source[:-1])
+ # Add the expected output:
+ want = piece.want
+ if want:
+ output.append('# Expected:')
+ output += ['## '+l for l in want.split('\n')[:-1]]
+ else:
+ # Add non-example text.
+ output += [_comment_line(l)
+ for l in piece.split('\n')[:-1]]
+
+ # Trim junk on both ends.
+ while output and output[-1] == '#':
+ output.pop()
+ while output and output[0] == '#':
+ output.pop(0)
+ # Combine the output, and return it.
+ # Add a courtesy newline to prevent exec from choking (see bug #1172785)
+ return '\n'.join(output) + '\n'
+
+def testsource(module, name):
+ """Extract the test sources from a doctest docstring as a script.
+
+ Provide the module (or dotted name of the module) containing the
+ test to be debugged and the name (within the module) of the object
+ with the doc string with tests to be debugged.
+ """
+ module = _normalize_module(module)
+ tests = DocTestFinder().find(module)
+ test = [t for t in tests if t.name == name]
+ if not test:
+ raise ValueError(name, "not found in tests")
+ test = test[0]
+ testsrc = script_from_examples(test.docstring)
+ return testsrc
+
+def debug_src(src, pm=False, globs=None):
+ """Debug a single doctest docstring, in argument `src`"""
+ testsrc = script_from_examples(src)
+ debug_script(testsrc, pm, globs)
+
+def debug_script(src, pm=False, globs=None):
+ "Debug a test script. `src` is the script, as a string."
+ import pdb
+
+ if globs:
+ globs = globs.copy()
+ else:
+ globs = {}
+
+ if pm:
+ try:
+ exec(src, globs, globs)
+ except:
+ print(sys.exc_info()[1])
+ p = pdb.Pdb(nosigint=True)
+ p.reset()
+ p.interaction(None, sys.exc_info()[2])
+ else:
+ pdb.Pdb(nosigint=True).run("exec(%r)" % src, globs, globs)
+
+def debug(module, name, pm=False):
+ """Debug a single doctest docstring.
+
+ Provide the module (or dotted name of the module) containing the
+ test to be debugged and the name (within the module) of the object
+ with the docstring with tests to be debugged.
+ """
+ module = _normalize_module(module)
+ testsrc = testsource(module, name)
+ debug_script(testsrc, pm, module.__dict__)
+
+######################################################################
+## 9. Example Usage
+######################################################################
+class _TestClass:
+ """
+ A pointless class, for sanity-checking of docstring testing.
+
+ Methods:
+ square()
+ get()
+
+ >>> _TestClass(13).get() + _TestClass(-12).get()
+ 1
+ >>> hex(_TestClass(13).square().get())
+ '0xa9'
+ """
+
+ def __init__(self, val):
+ """val -> _TestClass object with associated value val.
+
+ >>> t = _TestClass(123)
+ >>> print(t.get())
+ 123
+ """
+
+ self.val = val
+
+ def square(self):
+ """square() -> square TestClass's associated value
+
+ >>> _TestClass(13).square().get()
+ 169
+ """
+
+ self.val = self.val ** 2
+ return self
+
+ def get(self):
+ """get() -> return TestClass's associated value.
+
+ >>> x = _TestClass(-42)
+ >>> print(x.get())
+ -42
+ """
+
+ return self.val
+
+__test__ = {"_TestClass": _TestClass,
+ "string": r"""
+ Example of a string object, searched as-is.
+ >>> x = 1; y = 2
+ >>> x + y, x * y
+ (3, 2)
+ """,
+
+ "bool-int equivalence": r"""
+ In 2.2, boolean expressions displayed
+ 0 or 1. By default, we still accept
+ them. This can be disabled by passing
+ DONT_ACCEPT_TRUE_FOR_1 to the new
+ optionflags argument.
+ >>> 4 == 4
+ 1
+ >>> 4 == 4
+ True
+ >>> 4 > 4
+ 0
+ >>> 4 > 4
+ False
+ """,
+
+ "blank lines": r"""
+ Blank lines can be marked with :
+ >>> print('foo\n\nbar\n')
+ foo
+
+ bar
+
+ """,
+
+ "ellipsis": r"""
+ If the ellipsis flag is used, then '...' can be used to
+ elide substrings in the desired output:
+ >>> print(list(range(1000))) #doctest: +ELLIPSIS
+ [0, 1, 2, ..., 999]
+ """,
+
+ "whitespace normalization": r"""
+ If the whitespace normalization flag is used, then
+ differences in whitespace are ignored.
+ >>> print(list(range(30))) #doctest: +NORMALIZE_WHITESPACE
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
+ 27, 28, 29]
+ """,
+ }
+
+
+def _test():
+ import argparse
+
+ parser = argparse.ArgumentParser(description="doctest runner", color=True)
+ parser.add_argument('-v', '--verbose', action='store_true', default=False,
+ help='print very verbose output for all tests')
+ parser.add_argument('-o', '--option', action='append',
+ choices=OPTIONFLAGS_BY_NAME.keys(), default=[],
+ help=('specify a doctest option flag to apply'
+ ' to the test run; may be specified more'
+ ' than once to apply multiple options'))
+ parser.add_argument('-f', '--fail-fast', action='store_true',
+ help=('stop running tests after first failure (this'
+ ' is a shorthand for -o FAIL_FAST, and is'
+ ' in addition to any other -o options)'))
+ parser.add_argument('file', nargs='+',
+ help='file containing the tests to run')
+ args = parser.parse_args()
+ testfiles = args.file
+ # Verbose used to be handled by the "inspect argv" magic in DocTestRunner,
+ # but since we are using argparse we are passing it manually now.
+ verbose = args.verbose
+ options = 0
+ for option in args.option:
+ options |= OPTIONFLAGS_BY_NAME[option]
+ if args.fail_fast:
+ options |= FAIL_FAST
+ for filename in testfiles:
+ if filename.endswith(".py"):
+ # It is a module -- insert its dir into sys.path and try to
+ # import it. If it is part of a package, that possibly
+ # won't work because of package imports.
+ dirname, filename = os.path.split(filename)
+ sys.path.insert(0, dirname)
+ m = __import__(filename[:-3])
+ del sys.path[0]
+ failures, _ = testmod(m, verbose=verbose, optionflags=options)
+ else:
+ failures, _ = testfile(filename, module_relative=False,
+ verbose=verbose, optionflags=options)
+ if failures:
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(_test())
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/enum.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/enum.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4551da1c17187b79b438c8b20cc3db1cf6a6452
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/enum.py
@@ -0,0 +1,2168 @@
+import sys
+import builtins as bltns
+from types import MappingProxyType, DynamicClassAttribute
+
+
+__all__ = [
+ 'EnumType', 'EnumMeta', 'EnumDict',
+ 'Enum', 'IntEnum', 'StrEnum', 'Flag', 'IntFlag', 'ReprEnum',
+ 'auto', 'unique', 'property', 'verify', 'member', 'nonmember',
+ 'FlagBoundary', 'STRICT', 'CONFORM', 'EJECT', 'KEEP',
+ 'global_flag_repr', 'global_enum_repr', 'global_str', 'global_enum',
+ 'EnumCheck', 'CONTINUOUS', 'NAMED_FLAGS', 'UNIQUE',
+ 'pickle_by_global_name', 'pickle_by_enum_name',
+ ]
+
+
+# Dummy value for Enum and Flag as there are explicit checks for them
+# before they have been created.
+# This is also why there are checks in EnumType like `if Enum is not None`
+Enum = Flag = EJECT = _stdlib_enums = ReprEnum = None
+
+class nonmember(object):
+ """
+ Protects item from becoming an Enum member during class creation.
+ """
+ def __init__(self, value):
+ self.value = value
+
+class member(object):
+ """
+ Forces item to become an Enum member during class creation.
+ """
+ def __init__(self, value):
+ self.value = value
+
+def _is_descriptor(obj):
+ """
+ Returns True if obj is a descriptor, False otherwise.
+ """
+ return (
+ hasattr(obj, '__get__') or
+ hasattr(obj, '__set__') or
+ hasattr(obj, '__delete__')
+ )
+
+def _is_dunder(name):
+ """
+ Returns True if a __dunder__ name, False otherwise.
+ """
+ return (
+ len(name) > 4 and
+ name[:2] == name[-2:] == '__' and
+ name[2] != '_' and
+ name[-3] != '_'
+ )
+
+def _is_sunder(name):
+ """
+ Returns True if a _sunder_ name, False otherwise.
+ """
+ return (
+ len(name) > 2 and
+ name[0] == name[-1] == '_' and
+ name[1] != '_' and
+ name[-2] != '_'
+ )
+
+def _is_internal_class(cls_name, obj):
+ # do not use `re` as `re` imports `enum`
+ if not isinstance(obj, type):
+ return False
+ qualname = getattr(obj, '__qualname__', '')
+ s_pattern = cls_name + '.' + getattr(obj, '__name__', '')
+ e_pattern = '.' + s_pattern
+ return qualname == s_pattern or qualname.endswith(e_pattern)
+
+def _is_private(cls_name, name):
+ # do not use `re` as `re` imports `enum`
+ pattern = '_%s__' % (cls_name, )
+ pat_len = len(pattern)
+ if (
+ len(name) > pat_len
+ and name.startswith(pattern)
+ and (name[-1] != '_' or name[-2] != '_')
+ ):
+ return True
+ else:
+ return False
+
+def _is_single_bit(num):
+ """
+ True if only one bit set in num (should be an int)
+ """
+ if num == 0:
+ return False
+ num &= num - 1
+ return num == 0
+
+def _make_class_unpicklable(obj):
+ """
+ Make the given obj un-picklable.
+
+ obj should be either a dictionary, or an Enum
+ """
+ def _break_on_call_reduce(self, proto):
+ raise TypeError('%r cannot be pickled' % self)
+ if isinstance(obj, dict):
+ obj['__reduce_ex__'] = _break_on_call_reduce
+ obj['__module__'] = ''
+ else:
+ setattr(obj, '__reduce_ex__', _break_on_call_reduce)
+ setattr(obj, '__module__', '')
+
+def _iter_bits_lsb(num):
+ # num must be a positive integer
+ original = num
+ if isinstance(num, Enum):
+ num = num.value
+ if num < 0:
+ raise ValueError('%r is not a positive integer' % original)
+ while num:
+ b = num & (~num + 1)
+ yield b
+ num ^= b
+
+def show_flag_values(value):
+ return list(_iter_bits_lsb(value))
+
+def bin(num, max_bits=None):
+ """
+ Like built-in bin(), except negative values are represented in
+ twos-complement, and the leading bit always indicates sign
+ (0=positive, 1=negative).
+
+ >>> bin(10)
+ '0b0 1010'
+ >>> bin(~10) # ~10 is -11
+ '0b1 0101'
+ """
+
+ num = num.__index__()
+ ceiling = 2 ** (num).bit_length()
+ if num >= 0:
+ s = bltns.bin(num + ceiling).replace('1', '0', 1)
+ else:
+ s = bltns.bin(~num ^ (ceiling - 1) + ceiling)
+ sign = s[:3]
+ digits = s[3:]
+ if max_bits is not None:
+ if len(digits) < max_bits:
+ digits = (sign[-1] * max_bits + digits)[-max_bits:]
+ return "%s %s" % (sign, digits)
+
+class _not_given:
+ def __repr__(self):
+ return('')
+_not_given = _not_given()
+
+class _auto_null:
+ def __repr__(self):
+ return '_auto_null'
+_auto_null = _auto_null()
+
+class auto:
+ """
+ Instances are replaced with an appropriate value in Enum class suites.
+ """
+ def __init__(self, value=_auto_null):
+ self.value = value
+
+ def __repr__(self):
+ return "auto(%r)" % self.value
+
+class property(DynamicClassAttribute):
+ """
+ This is a descriptor, used to define attributes that act differently
+ when accessed through an enum member and through an enum class.
+ Instance access is the same as property(), but access to an attribute
+ through the enum class will instead look in the class' _member_map_ for
+ a corresponding enum member.
+ """
+
+ member = None
+ _attr_type = None
+ _cls_type = None
+
+ def __get__(self, instance, ownerclass=None):
+ if instance is None:
+ if self.member is not None:
+ return self.member
+ else:
+ raise AttributeError(
+ '%r has no attribute %r' % (ownerclass, self.name)
+ )
+ if self.fget is not None:
+ # use previous enum.property
+ return self.fget(instance)
+ elif self._attr_type == 'attr':
+ # look up previous attribute
+ return getattr(self._cls_type, self.name)
+ elif self._attr_type == 'desc':
+ # use previous descriptor
+ return getattr(instance._value_, self.name)
+ # look for a member by this name.
+ try:
+ return ownerclass._member_map_[self.name]
+ except KeyError:
+ raise AttributeError(
+ '%r has no attribute %r' % (ownerclass, self.name)
+ ) from None
+
+ def __set__(self, instance, value):
+ if self.fset is not None:
+ return self.fset(instance, value)
+ raise AttributeError(
+ " cannot set attribute %r" % (self.clsname, self.name)
+ )
+
+ def __delete__(self, instance):
+ if self.fdel is not None:
+ return self.fdel(instance)
+ raise AttributeError(
+ " cannot delete attribute %r" % (self.clsname, self.name)
+ )
+
+ def __set_name__(self, ownerclass, name):
+ self.name = name
+ self.clsname = ownerclass.__name__
+
+
+class _proto_member:
+ """
+ intermediate step for enum members between class execution and final creation
+ """
+
+ def __init__(self, value):
+ self.value = value
+
+ def __set_name__(self, enum_class, member_name):
+ """
+ convert each quasi-member into an instance of the new enum class
+ """
+ # first step: remove ourself from enum_class
+ delattr(enum_class, member_name)
+ # second step: create member based on enum_class
+ value = self.value
+ if not isinstance(value, tuple):
+ args = (value, )
+ else:
+ args = value
+ if enum_class._member_type_ is tuple: # special case for tuple enums
+ args = (args, ) # wrap it one more time
+ if not enum_class._use_args_:
+ enum_member = enum_class._new_member_(enum_class)
+ else:
+ enum_member = enum_class._new_member_(enum_class, *args)
+ if not hasattr(enum_member, '_value_'):
+ if enum_class._member_type_ is object:
+ enum_member._value_ = value
+ else:
+ try:
+ enum_member._value_ = enum_class._member_type_(*args)
+ except Exception as exc:
+ new_exc = TypeError(
+ '_value_ not set in __new__, unable to create it'
+ )
+ new_exc.__cause__ = exc
+ raise new_exc
+ value = enum_member._value_
+ enum_member._name_ = member_name
+ enum_member.__objclass__ = enum_class
+ enum_member.__init__(*args)
+ enum_member._sort_order_ = len(enum_class._member_names_)
+
+ if Flag is not None and issubclass(enum_class, Flag):
+ if isinstance(value, int):
+ enum_class._flag_mask_ |= value
+ if _is_single_bit(value):
+ enum_class._singles_mask_ |= value
+ enum_class._all_bits_ = 2 ** ((enum_class._flag_mask_).bit_length()) - 1
+
+ # If another member with the same value was already defined, the
+ # new member becomes an alias to the existing one.
+ try:
+ try:
+ # try to do a fast lookup to avoid the quadratic loop
+ enum_member = enum_class._value2member_map_[value]
+ except TypeError:
+ for name, canonical_member in enum_class._member_map_.items():
+ if canonical_member._value_ == value:
+ enum_member = canonical_member
+ break
+ else:
+ raise KeyError
+ except KeyError:
+ # this could still be an alias if the value is multi-bit and the
+ # class is a flag class
+ if (
+ Flag is None
+ or not issubclass(enum_class, Flag)
+ ):
+ # no other instances found, record this member in _member_names_
+ enum_class._member_names_.append(member_name)
+ elif (
+ Flag is not None
+ and issubclass(enum_class, Flag)
+ and isinstance(value, int)
+ and _is_single_bit(value)
+ ):
+ # no other instances found, record this member in _member_names_
+ enum_class._member_names_.append(member_name)
+
+ enum_class._add_member_(member_name, enum_member)
+ try:
+ # This may fail if value is not hashable. We can't add the value
+ # to the map, and by-value lookups for this value will be
+ # linear.
+ enum_class._value2member_map_.setdefault(value, enum_member)
+ if value not in enum_class._hashable_values_:
+ enum_class._hashable_values_.append(value)
+ except TypeError:
+ # keep track of the value in a list so containment checks are quick
+ enum_class._unhashable_values_.append(value)
+ enum_class._unhashable_values_map_.setdefault(member_name, []).append(value)
+
+
+class EnumDict(dict):
+ """
+ Track enum member order and ensure member names are not reused.
+
+ EnumType will use the names found in self._member_names as the
+ enumeration member names.
+ """
+ def __init__(self, cls_name=None):
+ super().__init__()
+ self._member_names = {} # use a dict -- faster look-up than a list, and keeps insertion order since 3.7
+ self._last_values = []
+ self._ignore = []
+ self._auto_called = False
+ self._cls_name = cls_name
+
+ def __setitem__(self, key, value):
+ """
+ Changes anything not dundered or not a descriptor.
+
+ If an enum member name is used twice, an error is raised; duplicate
+ values are not checked for.
+
+ Single underscore (sunder) names are reserved.
+ """
+ if self._cls_name is not None and _is_private(self._cls_name, key):
+ # do nothing, name will be a normal attribute
+ pass
+ elif _is_sunder(key):
+ if key not in (
+ '_order_',
+ '_generate_next_value_', '_numeric_repr_', '_missing_', '_ignore_',
+ '_iter_member_', '_iter_member_by_value_', '_iter_member_by_def_',
+ '_add_alias_', '_add_value_alias_',
+ # While not in use internally, those are common for pretty
+ # printing and thus excluded from Enum's reservation of
+ # _sunder_ names
+ ) and not key.startswith('_repr_'):
+ raise ValueError(
+ '_sunder_ names, such as %r, are reserved for future Enum use'
+ % (key, )
+ )
+ if key == '_generate_next_value_':
+ # check if members already defined as auto()
+ if self._auto_called:
+ raise TypeError("_generate_next_value_ must be defined before members")
+ _gnv = value.__func__ if isinstance(value, staticmethod) else value
+ setattr(self, '_generate_next_value', _gnv)
+ elif key == '_ignore_':
+ if isinstance(value, str):
+ value = value.replace(',',' ').split()
+ else:
+ value = list(value)
+ self._ignore = value
+ already = set(value) & set(self._member_names)
+ if already:
+ raise ValueError(
+ '_ignore_ cannot specify already set names: %r'
+ % (already, )
+ )
+ elif _is_dunder(key):
+ if key == '__order__':
+ key = '_order_'
+ elif key in self._member_names:
+ # descriptor overwriting an enum?
+ raise TypeError('%r already defined as %r' % (key, self[key]))
+ elif key in self._ignore:
+ pass
+ elif isinstance(value, nonmember):
+ # unwrap value here; it won't be processed by the below `else`
+ value = value.value
+ elif _is_descriptor(value):
+ pass
+ elif self._cls_name is not None and _is_internal_class(self._cls_name, value):
+ # do nothing, name will be a normal attribute
+ pass
+ else:
+ if key in self:
+ # enum overwriting a descriptor?
+ raise TypeError('%r already defined as %r' % (key, self[key]))
+ elif isinstance(value, member):
+ # unwrap value here -- it will become a member
+ value = value.value
+ non_auto_store = True
+ single = False
+ if isinstance(value, auto):
+ single = True
+ value = (value, )
+ if isinstance(value, tuple) and any(isinstance(v, auto) for v in value):
+ # insist on an actual tuple, no subclasses, in keeping with only supporting
+ # top-level auto() usage (not contained in any other data structure)
+ auto_valued = []
+ t = type(value)
+ for v in value:
+ if isinstance(v, auto):
+ non_auto_store = False
+ if v.value == _auto_null:
+ v.value = self._generate_next_value(
+ key, 1, len(self._member_names), self._last_values[:],
+ )
+ self._auto_called = True
+ v = v.value
+ self._last_values.append(v)
+ auto_valued.append(v)
+ if single:
+ value = auto_valued[0]
+ else:
+ try:
+ # accepts iterable as multiple arguments?
+ value = t(auto_valued)
+ except TypeError:
+ # then pass them in singly
+ value = t(*auto_valued)
+ self._member_names[key] = None
+ if non_auto_store:
+ self._last_values.append(value)
+ super().__setitem__(key, value)
+
+ @property
+ def member_names(self):
+ return list(self._member_names)
+
+ def update(self, members, **more_members):
+ try:
+ for name in members.keys():
+ self[name] = members[name]
+ except AttributeError:
+ for name, value in members:
+ self[name] = value
+ for name, value in more_members.items():
+ self[name] = value
+
+_EnumDict = EnumDict # keep private name for backwards compatibility
+
+
+class EnumType(type):
+ """
+ Metaclass for Enum
+ """
+
+ @classmethod
+ def __prepare__(metacls, cls, bases, **kwds):
+ # check that previous enum members do not exist
+ metacls._check_for_existing_members_(cls, bases)
+ # create the namespace dict
+ enum_dict = EnumDict(cls)
+ # inherit previous flags and _generate_next_value_ function
+ member_type, first_enum = metacls._get_mixins_(cls, bases)
+ if first_enum is not None:
+ enum_dict['_generate_next_value_'] = getattr(
+ first_enum, '_generate_next_value_', None,
+ )
+ return enum_dict
+
+ def __new__(metacls, cls, bases, classdict, *, boundary=None, _simple=False, **kwds):
+ # an Enum class is final once enumeration items have been defined; it
+ # cannot be mixed with other types (int, float, etc.) if it has an
+ # inherited __new__ unless a new __new__ is defined (or the resulting
+ # class will fail).
+ #
+ if _simple:
+ return super().__new__(metacls, cls, bases, classdict, **kwds)
+ #
+ # remove any keys listed in _ignore_
+ classdict.setdefault('_ignore_', []).append('_ignore_')
+ ignore = classdict['_ignore_']
+ for key in ignore:
+ classdict.pop(key, None)
+ #
+ # grab member names
+ member_names = classdict._member_names
+ #
+ # check for illegal enum names (any others?)
+ invalid_names = set(member_names) & {'mro', ''}
+ if invalid_names:
+ raise ValueError('invalid enum member name(s) %s' % (
+ ','.join(repr(n) for n in invalid_names)
+ ))
+ #
+ # adjust the sunders
+ _order_ = classdict.pop('_order_', None)
+ _gnv = classdict.get('_generate_next_value_')
+ if _gnv is not None and type(_gnv) is not staticmethod:
+ _gnv = staticmethod(_gnv)
+ # convert to normal dict
+ classdict = dict(classdict.items())
+ if _gnv is not None:
+ classdict['_generate_next_value_'] = _gnv
+ #
+ # data type of member and the controlling Enum class
+ member_type, first_enum = metacls._get_mixins_(cls, bases)
+ __new__, save_new, use_args = metacls._find_new_(
+ classdict, member_type, first_enum,
+ )
+ classdict['_new_member_'] = __new__
+ classdict['_use_args_'] = use_args
+ #
+ # convert future enum members into temporary _proto_members
+ for name in member_names:
+ value = classdict[name]
+ classdict[name] = _proto_member(value)
+ #
+ # house-keeping structures
+ classdict['_member_names_'] = []
+ classdict['_member_map_'] = {}
+ classdict['_value2member_map_'] = {}
+ classdict['_hashable_values_'] = [] # for comparing with non-hashable types
+ classdict['_unhashable_values_'] = [] # e.g. frozenset() with set()
+ classdict['_unhashable_values_map_'] = {}
+ classdict['_member_type_'] = member_type
+ # now set the __repr__ for the value
+ classdict['_value_repr_'] = metacls._find_data_repr_(cls, bases)
+ #
+ # Flag structures (will be removed if final class is not a Flag
+ classdict['_boundary_'] = (
+ boundary
+ or getattr(first_enum, '_boundary_', None)
+ )
+ classdict['_flag_mask_'] = 0
+ classdict['_singles_mask_'] = 0
+ classdict['_all_bits_'] = 0
+ classdict['_inverted_'] = None
+ try:
+ classdict['_%s__in_progress' % cls] = True
+ enum_class = super().__new__(metacls, cls, bases, classdict, **kwds)
+ classdict['_%s__in_progress' % cls] = False
+ delattr(enum_class, '_%s__in_progress' % cls)
+ except Exception as e:
+ # since 3.12 the note "Error calling __set_name__ on '_proto_member' instance ..."
+ # is tacked on to the error instead of raising a RuntimeError, so discard it
+ if hasattr(e, '__notes__'):
+ del e.__notes__
+ raise
+ # update classdict with any changes made by __init_subclass__
+ classdict.update(enum_class.__dict__)
+ #
+ # double check that repr and friends are not the mixin's or various
+ # things break (such as pickle)
+ # however, if the method is defined in the Enum itself, don't replace
+ # it
+ #
+ # Also, special handling for ReprEnum
+ if ReprEnum is not None and ReprEnum in bases:
+ if member_type is object:
+ raise TypeError(
+ 'ReprEnum subclasses must be mixed with a data type (i.e.'
+ ' int, str, float, etc.)'
+ )
+ if '__format__' not in classdict:
+ enum_class.__format__ = member_type.__format__
+ classdict['__format__'] = enum_class.__format__
+ if '__str__' not in classdict:
+ method = member_type.__str__
+ if method is object.__str__:
+ # if member_type does not define __str__, object.__str__ will use
+ # its __repr__ instead, so we'll also use its __repr__
+ method = member_type.__repr__
+ enum_class.__str__ = method
+ classdict['__str__'] = enum_class.__str__
+ for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'):
+ if name not in classdict:
+ # check for mixin overrides before replacing
+ enum_method = getattr(first_enum, name)
+ found_method = getattr(enum_class, name)
+ object_method = getattr(object, name)
+ data_type_method = getattr(member_type, name)
+ if found_method in (data_type_method, object_method):
+ setattr(enum_class, name, enum_method)
+ #
+ # for Flag, add __or__, __and__, __xor__, and __invert__
+ if Flag is not None and issubclass(enum_class, Flag):
+ for name in (
+ '__or__', '__and__', '__xor__',
+ '__ror__', '__rand__', '__rxor__',
+ '__invert__'
+ ):
+ if name not in classdict:
+ enum_method = getattr(Flag, name)
+ setattr(enum_class, name, enum_method)
+ classdict[name] = enum_method
+ #
+ # replace any other __new__ with our own (as long as Enum is not None,
+ # anyway) -- again, this is to support pickle
+ if Enum is not None:
+ # if the user defined their own __new__, save it before it gets
+ # clobbered in case they subclass later
+ if save_new:
+ enum_class.__new_member__ = __new__
+ enum_class.__new__ = Enum.__new__
+ #
+ # py3 support for definition order (helps keep py2/py3 code in sync)
+ #
+ # _order_ checking is spread out into three/four steps
+ # - if enum_class is a Flag:
+ # - remove any non-single-bit flags from _order_
+ # - remove any aliases from _order_
+ # - check that _order_ and _member_names_ match
+ #
+ # step 1: ensure we have a list
+ if _order_ is not None:
+ if isinstance(_order_, str):
+ _order_ = _order_.replace(',', ' ').split()
+ #
+ # remove Flag structures if final class is not a Flag
+ if (
+ Flag is None and cls != 'Flag'
+ or Flag is not None and not issubclass(enum_class, Flag)
+ ):
+ delattr(enum_class, '_boundary_')
+ delattr(enum_class, '_flag_mask_')
+ delattr(enum_class, '_singles_mask_')
+ delattr(enum_class, '_all_bits_')
+ delattr(enum_class, '_inverted_')
+ elif Flag is not None and issubclass(enum_class, Flag):
+ # set correct __iter__
+ member_list = [m._value_ for m in enum_class]
+ if member_list != sorted(member_list):
+ enum_class._iter_member_ = enum_class._iter_member_by_def_
+ if _order_:
+ # _order_ step 2: remove any items from _order_ that are not single-bit
+ _order_ = [
+ o
+ for o in _order_
+ if o not in enum_class._member_map_ or _is_single_bit(enum_class[o]._value_)
+ ]
+ #
+ if _order_:
+ # _order_ step 3: remove aliases from _order_
+ _order_ = [
+ o
+ for o in _order_
+ if (
+ o not in enum_class._member_map_
+ or
+ (o in enum_class._member_map_ and o in enum_class._member_names_)
+ )]
+ # _order_ step 4: verify that _order_ and _member_names_ match
+ if _order_ != enum_class._member_names_:
+ raise TypeError(
+ 'member order does not match _order_:\n %r\n %r'
+ % (enum_class._member_names_, _order_)
+ )
+ #
+ return enum_class
+
+ def __bool__(cls):
+ """
+ classes/types should always be True.
+ """
+ return True
+
+ def __call__(cls, value, names=_not_given, *values, module=None, qualname=None, type=None, start=1, boundary=None):
+ """
+ Either returns an existing member, or creates a new enum class.
+
+ This method is used both when an enum class is given a value to match
+ to an enumeration member (i.e. Color(3)) and for the functional API
+ (i.e. Color = Enum('Color', names='RED GREEN BLUE')).
+
+ The value lookup branch is chosen if the enum is final.
+
+ When used for the functional API:
+
+ `value` will be the name of the new class.
+
+ `names` should be either a string of white-space/comma delimited names
+ (values will start at `start`), or an iterator/mapping of name, value pairs.
+
+ `module` should be set to the module this class is being created in;
+ if it is not set, an attempt to find that module will be made, but if
+ it fails the class will not be picklable.
+
+ `qualname` should be set to the actual location this class can be found
+ at in its module; by default it is set to the global scope. If this is
+ not correct, unpickling will fail in some circumstances.
+
+ `type`, if set, will be mixed in as the first base class.
+ """
+ if cls._member_map_:
+ # simple value lookup if members exist
+ if names is not _not_given:
+ value = (value, names) + values
+ return cls.__new__(cls, value)
+ # otherwise, functional API: we're creating a new Enum type
+ if names is _not_given and type is None:
+ # no body? no data-type? possibly wrong usage
+ raise TypeError(
+ f"{cls} has no members; specify `names=()` if you meant to create a new, empty, enum"
+ )
+ return cls._create_(
+ class_name=value,
+ names=None if names is _not_given else names,
+ module=module,
+ qualname=qualname,
+ type=type,
+ start=start,
+ boundary=boundary,
+ )
+
+ def __contains__(cls, value):
+ """Return True if `value` is in `cls`.
+
+ `value` is in `cls` if:
+ 1) `value` is a member of `cls`, or
+ 2) `value` is the value of one of the `cls`'s members.
+ 3) `value` is a pseudo-member (flags)
+ """
+ if isinstance(value, cls):
+ return True
+ if issubclass(cls, Flag):
+ try:
+ result = cls._missing_(value)
+ return isinstance(result, cls)
+ except ValueError:
+ pass
+ return (
+ value in cls._unhashable_values_ # both structures are lists
+ or value in cls._hashable_values_
+ )
+
+ def __delattr__(cls, attr):
+ # nicer error message when someone tries to delete an attribute
+ # (see issue19025).
+ if attr in cls._member_map_:
+ raise AttributeError("%r cannot delete member %r." % (cls.__name__, attr))
+ super().__delattr__(attr)
+
+ def __dir__(cls):
+ interesting = set([
+ '__class__', '__contains__', '__doc__', '__getitem__',
+ '__iter__', '__len__', '__members__', '__module__',
+ '__name__', '__qualname__',
+ ]
+ + cls._member_names_
+ )
+ if cls._new_member_ is not object.__new__:
+ interesting.add('__new__')
+ if cls.__init_subclass__ is not object.__init_subclass__:
+ interesting.add('__init_subclass__')
+ if cls._member_type_ is object:
+ return sorted(interesting)
+ else:
+ # return whatever mixed-in data type has
+ return sorted(set(dir(cls._member_type_)) | interesting)
+
+ def __getitem__(cls, name):
+ """
+ Return the member matching `name`.
+ """
+ return cls._member_map_[name]
+
+ def __iter__(cls):
+ """
+ Return members in definition order.
+ """
+ return (cls._member_map_[name] for name in cls._member_names_)
+
+ def __len__(cls):
+ """
+ Return the number of members (no aliases)
+ """
+ return len(cls._member_names_)
+
+ @bltns.property
+ def __members__(cls):
+ """
+ Returns a mapping of member name->value.
+
+ This mapping lists all enum members, including aliases. Note that this
+ is a read-only view of the internal mapping.
+ """
+ return MappingProxyType(cls._member_map_)
+
+ def __repr__(cls):
+ if Flag is not None and issubclass(cls, Flag):
+ return "" % cls.__name__
+ else:
+ return "" % cls.__name__
+
+ def __reversed__(cls):
+ """
+ Return members in reverse definition order.
+ """
+ return (cls._member_map_[name] for name in reversed(cls._member_names_))
+
+ def __setattr__(cls, name, value):
+ """
+ Block attempts to reassign Enum members.
+
+ A simple assignment to the class namespace only changes one of the
+ several possible ways to get an Enum member from the Enum class,
+ resulting in an inconsistent Enumeration.
+ """
+ member_map = cls.__dict__.get('_member_map_', {})
+ if name in member_map:
+ raise AttributeError('cannot reassign member %r' % (name, ))
+ super().__setattr__(name, value)
+
+ def _create_(cls, class_name, names, *, module=None, qualname=None, type=None, start=1, boundary=None):
+ """
+ Convenience method to create a new Enum class.
+
+ `names` can be:
+
+ * A string containing member names, separated either with spaces or
+ commas. Values are incremented by 1 from `start`.
+ * An iterable of member names. Values are incremented by 1 from `start`.
+ * An iterable of (member name, value) pairs.
+ * A mapping of member name -> value pairs.
+ """
+ metacls = cls.__class__
+ bases = (cls, ) if type is None else (type, cls)
+ _, first_enum = cls._get_mixins_(class_name, bases)
+ classdict = metacls.__prepare__(class_name, bases)
+
+ # special processing needed for names?
+ if isinstance(names, str):
+ names = names.replace(',', ' ').split()
+ if isinstance(names, (tuple, list)) and names and isinstance(names[0], str):
+ original_names, names = names, []
+ last_values = []
+ for count, name in enumerate(original_names):
+ value = first_enum._generate_next_value_(name, start, count, last_values[:])
+ last_values.append(value)
+ names.append((name, value))
+ if names is None:
+ names = ()
+
+ # Here, names is either an iterable of (name, value) or a mapping.
+ for item in names:
+ if isinstance(item, str):
+ member_name, member_value = item, names[item]
+ else:
+ member_name, member_value = item
+ classdict[member_name] = member_value
+
+ if module is None:
+ try:
+ module = sys._getframemodulename(2)
+ except AttributeError:
+ # Fall back on _getframe if _getframemodulename is missing
+ try:
+ module = sys._getframe(2).f_globals['__name__']
+ except (AttributeError, ValueError, KeyError):
+ pass
+ if module is None:
+ _make_class_unpicklable(classdict)
+ else:
+ classdict['__module__'] = module
+ if qualname is not None:
+ classdict['__qualname__'] = qualname
+
+ return metacls.__new__(metacls, class_name, bases, classdict, boundary=boundary)
+
+ def _convert_(cls, name, module, filter, source=None, *, boundary=None, as_global=False):
+ """
+ Create a new Enum subclass that replaces a collection of global constants
+ """
+ # convert all constants from source (or module) that pass filter() to
+ # a new Enum called name, and export the enum and its members back to
+ # module;
+ # also, replace the __reduce_ex__ method so unpickling works in
+ # previous Python versions
+ module_globals = sys.modules[module].__dict__
+ if source:
+ source = source.__dict__
+ else:
+ source = module_globals
+ # _value2member_map_ is populated in the same order every time
+ # for a consistent reverse mapping of number to name when there
+ # are multiple names for the same number.
+ members = [
+ (name, value)
+ for name, value in source.items()
+ if filter(name)]
+ try:
+ # sort by value
+ members.sort(key=lambda t: (t[1], t[0]))
+ except TypeError:
+ # unless some values aren't comparable, in which case sort by name
+ members.sort(key=lambda t: t[0])
+ body = {t[0]: t[1] for t in members}
+ body['__module__'] = module
+ tmp_cls = type(name, (object, ), body)
+ cls = _simple_enum(etype=cls, boundary=boundary or KEEP)(tmp_cls)
+ if as_global:
+ global_enum(cls)
+ else:
+ sys.modules[cls.__module__].__dict__.update(cls.__members__)
+ module_globals[name] = cls
+ return cls
+
+ @classmethod
+ def _check_for_existing_members_(mcls, class_name, bases):
+ for chain in bases:
+ for base in chain.__mro__:
+ if isinstance(base, EnumType) and base._member_names_:
+ raise TypeError(
+ " cannot extend %r"
+ % (class_name, base)
+ )
+
+ @classmethod
+ def _get_mixins_(mcls, class_name, bases):
+ """
+ Returns the type for creating enum members, and the first inherited
+ enum class.
+
+ bases: the tuple of bases that was given to __new__
+ """
+ if not bases:
+ return object, Enum
+ # ensure final parent class is an Enum derivative, find any concrete
+ # data type, and check that Enum has no members
+ first_enum = bases[-1]
+ if not isinstance(first_enum, EnumType):
+ raise TypeError("new enumerations should be created as "
+ "`EnumName([mixin_type, ...] [data_type,] enum_type)`")
+ member_type = mcls._find_data_type_(class_name, bases) or object
+ return member_type, first_enum
+
+ @classmethod
+ def _find_data_repr_(mcls, class_name, bases):
+ for chain in bases:
+ for base in chain.__mro__:
+ if base is object:
+ continue
+ elif isinstance(base, EnumType):
+ # if we hit an Enum, use it's _value_repr_
+ return base._value_repr_
+ elif '__repr__' in base.__dict__:
+ # this is our data repr
+ # double-check if a dataclass with a default __repr__
+ if (
+ '__dataclass_fields__' in base.__dict__
+ and '__dataclass_params__' in base.__dict__
+ and base.__dict__['__dataclass_params__'].repr
+ ):
+ return _dataclass_repr
+ else:
+ return base.__dict__['__repr__']
+ return None
+
+ @classmethod
+ def _find_data_type_(mcls, class_name, bases):
+ # a datatype has a __new__ method, or a __dataclass_fields__ attribute
+ data_types = set()
+ base_chain = set()
+ for chain in bases:
+ candidate = None
+ for base in chain.__mro__:
+ base_chain.add(base)
+ if base is object:
+ continue
+ elif isinstance(base, EnumType):
+ if base._member_type_ is not object:
+ data_types.add(base._member_type_)
+ break
+ elif '__new__' in base.__dict__ or '__dataclass_fields__' in base.__dict__:
+ data_types.add(candidate or base)
+ break
+ else:
+ candidate = candidate or base
+ if len(data_types) > 1:
+ raise TypeError('too many data types for %r: %r' % (class_name, data_types))
+ elif data_types:
+ return data_types.pop()
+ else:
+ return None
+
+ @classmethod
+ def _find_new_(mcls, classdict, member_type, first_enum):
+ """
+ Returns the __new__ to be used for creating the enum members.
+
+ classdict: the class dictionary given to __new__
+ member_type: the data type whose __new__ will be used by default
+ first_enum: enumeration to check for an overriding __new__
+ """
+ # now find the correct __new__, checking to see of one was defined
+ # by the user; also check earlier enum classes in case a __new__ was
+ # saved as __new_member__
+ __new__ = classdict.get('__new__', None)
+
+ # should __new__ be saved as __new_member__ later?
+ save_new = first_enum is not None and __new__ is not None
+
+ if __new__ is None:
+ # check all possibles for __new_member__ before falling back to
+ # __new__
+ for method in ('__new_member__', '__new__'):
+ for possible in (member_type, first_enum):
+ target = getattr(possible, method, None)
+ if target not in {
+ None,
+ None.__new__,
+ object.__new__,
+ Enum.__new__,
+ }:
+ __new__ = target
+ break
+ if __new__ is not None:
+ break
+ else:
+ __new__ = object.__new__
+
+ # if a non-object.__new__ is used then whatever value/tuple was
+ # assigned to the enum member name will be passed to __new__ and to the
+ # new enum member's __init__
+ if first_enum is None or __new__ in (Enum.__new__, object.__new__):
+ use_args = False
+ else:
+ use_args = True
+ return __new__, save_new, use_args
+
+ def _add_member_(cls, name, member):
+ # _value_ structures are not updated
+ if name in cls._member_map_:
+ if cls._member_map_[name] is not member:
+ raise NameError('%r is already bound: %r' % (name, cls._member_map_[name]))
+ return
+ #
+ # if necessary, get redirect in place and then add it to _member_map_
+ found_descriptor = None
+ descriptor_type = None
+ class_type = None
+ for base in cls.__mro__[1:]:
+ attr = base.__dict__.get(name)
+ if attr is not None:
+ if isinstance(attr, (property, DynamicClassAttribute)):
+ found_descriptor = attr
+ class_type = base
+ descriptor_type = 'enum'
+ break
+ elif _is_descriptor(attr):
+ found_descriptor = attr
+ descriptor_type = descriptor_type or 'desc'
+ class_type = class_type or base
+ continue
+ else:
+ descriptor_type = 'attr'
+ class_type = base
+ if found_descriptor:
+ redirect = property()
+ redirect.member = member
+ redirect.__set_name__(cls, name)
+ if descriptor_type in ('enum', 'desc'):
+ # earlier descriptor found; copy fget, fset, fdel to this one.
+ redirect.fget = getattr(found_descriptor, 'fget', None)
+ redirect._get = getattr(found_descriptor, '__get__', None)
+ redirect.fset = getattr(found_descriptor, 'fset', None)
+ redirect._set = getattr(found_descriptor, '__set__', None)
+ redirect.fdel = getattr(found_descriptor, 'fdel', None)
+ redirect._del = getattr(found_descriptor, '__delete__', None)
+ redirect._attr_type = descriptor_type
+ redirect._cls_type = class_type
+ setattr(cls, name, redirect)
+ else:
+ setattr(cls, name, member)
+ # now add to _member_map_ (even aliases)
+ cls._member_map_[name] = member
+
+ @property
+ def __signature__(cls):
+ from inspect import Parameter, Signature
+ if cls._member_names_:
+ return Signature([Parameter('values', Parameter.VAR_POSITIONAL)])
+ else:
+ return Signature([Parameter('new_class_name', Parameter.POSITIONAL_ONLY),
+ Parameter('names', Parameter.POSITIONAL_OR_KEYWORD),
+ Parameter('module', Parameter.KEYWORD_ONLY, default=None),
+ Parameter('qualname', Parameter.KEYWORD_ONLY, default=None),
+ Parameter('type', Parameter.KEYWORD_ONLY, default=None),
+ Parameter('start', Parameter.KEYWORD_ONLY, default=1),
+ Parameter('boundary', Parameter.KEYWORD_ONLY, default=None)])
+
+
+EnumMeta = EnumType # keep EnumMeta name for backwards compatibility
+
+
+class Enum(metaclass=EnumType):
+ """
+ Create a collection of name/value pairs.
+
+ Example enumeration:
+
+ >>> class Color(Enum):
+ ... RED = 1
+ ... BLUE = 2
+ ... GREEN = 3
+
+ Access them by:
+
+ - attribute access:
+
+ >>> Color.RED
+
+
+ - value lookup:
+
+ >>> Color(1)
+
+
+ - name lookup:
+
+ >>> Color['RED']
+
+
+ Enumerations can be iterated over, and know how many members they have:
+
+ >>> len(Color)
+ 3
+
+ >>> list(Color)
+ [, , ]
+
+ Methods can be added to enumerations, and members can have their own
+ attributes -- see the documentation for details.
+ """
+
+ def __new__(cls, value):
+ # all enum instances are actually created during class construction
+ # without calling this method; this method is called by the metaclass'
+ # __call__ (i.e. Color(3) ), and by pickle
+ if type(value) is cls:
+ # For lookups like Color(Color.RED)
+ return value
+ # by-value search for a matching enum member
+ # see if it's in the reverse mapping (for hashable values)
+ try:
+ return cls._value2member_map_[value]
+ except KeyError:
+ # Not found, no need to do long O(n) search
+ pass
+ except TypeError:
+ # not there, now do long search -- O(n) behavior
+ for name, unhashable_values in cls._unhashable_values_map_.items():
+ if value in unhashable_values:
+ return cls[name]
+ for name, member in cls._member_map_.items():
+ if value == member._value_:
+ return cls[name]
+ # still not found -- verify that members exist, in-case somebody got here mistakenly
+ # (such as via super when trying to override __new__)
+ if not cls._member_map_:
+ if getattr(cls, '_%s__in_progress' % cls.__name__, False):
+ raise TypeError('do not use `super().__new__; call the appropriate __new__ directly') from None
+ raise TypeError("%r has no members defined" % cls)
+ #
+ # still not found -- try _missing_ hook
+ try:
+ exc = None
+ result = cls._missing_(value)
+ except Exception as e:
+ exc = e
+ result = None
+ try:
+ if isinstance(result, cls):
+ return result
+ elif (
+ Flag is not None and issubclass(cls, Flag)
+ and cls._boundary_ is EJECT and isinstance(result, int)
+ ):
+ return result
+ else:
+ ve_exc = ValueError("%r is not a valid %s" % (value, cls.__qualname__))
+ if result is None and exc is None:
+ raise ve_exc
+ elif exc is None:
+ exc = TypeError(
+ 'error in %s._missing_: returned %r instead of None or a valid member'
+ % (cls.__name__, result)
+ )
+ if not isinstance(exc, ValueError):
+ exc.__context__ = ve_exc
+ raise exc
+ finally:
+ # ensure all variables that could hold an exception are destroyed
+ exc = None
+ ve_exc = None
+
+ def _add_alias_(self, name):
+ self.__class__._add_member_(name, self)
+
+ def _add_value_alias_(self, value):
+ cls = self.__class__
+ try:
+ if value in cls._value2member_map_:
+ if cls._value2member_map_[value] is not self:
+ raise ValueError('%r is already bound: %r' % (value, cls._value2member_map_[value]))
+ return
+ except TypeError:
+ # unhashable value, do long search
+ for m in cls._member_map_.values():
+ if m._value_ == value:
+ if m is not self:
+ raise ValueError('%r is already bound: %r' % (value, cls._value2member_map_[value]))
+ return
+ try:
+ # This may fail if value is not hashable. We can't add the value
+ # to the map, and by-value lookups for this value will be
+ # linear.
+ cls._value2member_map_.setdefault(value, self)
+ cls._hashable_values_.append(value)
+ except TypeError:
+ # keep track of the value in a list so containment checks are quick
+ cls._unhashable_values_.append(value)
+ cls._unhashable_values_map_.setdefault(self.name, []).append(value)
+
+ @staticmethod
+ def _generate_next_value_(name, start, count, last_values):
+ """
+ Generate the next value when not given.
+
+ name: the name of the member
+ start: the initial start value or None
+ count: the number of existing members
+ last_values: the list of values assigned
+ """
+ if not last_values:
+ return start
+ try:
+ last_value = sorted(last_values).pop()
+ except TypeError:
+ raise TypeError('unable to sort non-numeric values') from None
+ try:
+ return last_value + 1
+ except TypeError:
+ raise TypeError('unable to increment %r' % (last_value, )) from None
+
+ @classmethod
+ def _missing_(cls, value):
+ return None
+
+ def __repr__(self):
+ v_repr = self.__class__._value_repr_ or repr
+ return "<%s.%s: %s>" % (self.__class__.__name__, self._name_, v_repr(self._value_))
+
+ def __str__(self):
+ return "%s.%s" % (self.__class__.__name__, self._name_, )
+
+ def __dir__(self):
+ """
+ Returns public methods and other interesting attributes.
+ """
+ interesting = set()
+ if self.__class__._member_type_ is not object:
+ interesting = set(object.__dir__(self))
+ for name in getattr(self, '__dict__', []):
+ if name[0] != '_' and name not in self._member_map_:
+ interesting.add(name)
+ for cls in self.__class__.mro():
+ for name, obj in cls.__dict__.items():
+ if name[0] == '_':
+ continue
+ if isinstance(obj, property):
+ # that's an enum.property
+ if obj.fget is not None or name not in self._member_map_:
+ interesting.add(name)
+ else:
+ # in case it was added by `dir(self)`
+ interesting.discard(name)
+ elif name not in self._member_map_:
+ interesting.add(name)
+ names = sorted(
+ set(['__class__', '__doc__', '__eq__', '__hash__', '__module__'])
+ | interesting
+ )
+ return names
+
+ def __format__(self, format_spec):
+ return str.__format__(str(self), format_spec)
+
+ def __hash__(self):
+ return hash(self._name_)
+
+ def __reduce_ex__(self, proto):
+ return self.__class__, (self._value_, )
+
+ def __deepcopy__(self,memo):
+ return self
+
+ def __copy__(self):
+ return self
+
+ # enum.property is used to provide access to the `name` and
+ # `value` attributes of enum members while keeping some measure of
+ # protection from modification, while still allowing for an enumeration
+ # to have members named `name` and `value`. This works because each
+ # instance of enum.property saves its companion member, which it returns
+ # on class lookup; on instance lookup it either executes a provided function
+ # or raises an AttributeError.
+
+ @property
+ def name(self):
+ """The name of the Enum member."""
+ return self._name_
+
+ @property
+ def value(self):
+ """The value of the Enum member."""
+ return self._value_
+
+
+class ReprEnum(Enum):
+ """
+ Only changes the repr(), leaving str() and format() to the mixed-in type.
+ """
+
+
+class IntEnum(int, ReprEnum):
+ """
+ Enum where members are also (and must be) ints
+ """
+
+
+class StrEnum(str, ReprEnum):
+ """
+ Enum where members are also (and must be) strings
+ """
+
+ def __new__(cls, *values):
+ "values must already be of type `str`"
+ if len(values) > 3:
+ raise TypeError('too many arguments for str(): %r' % (values, ))
+ if len(values) == 1:
+ # it must be a string
+ if not isinstance(values[0], str):
+ raise TypeError('%r is not a string' % (values[0], ))
+ if len(values) >= 2:
+ # check that encoding argument is a string
+ if not isinstance(values[1], str):
+ raise TypeError('encoding must be a string, not %r' % (values[1], ))
+ if len(values) == 3:
+ # check that errors argument is a string
+ if not isinstance(values[2], str):
+ raise TypeError('errors must be a string, not %r' % (values[2]))
+ value = str(*values)
+ member = str.__new__(cls, value)
+ member._value_ = value
+ return member
+
+ @staticmethod
+ def _generate_next_value_(name, start, count, last_values):
+ """
+ Return the lower-cased version of the member name.
+ """
+ return name.lower()
+
+
+def pickle_by_global_name(self, proto):
+ # should not be used with Flag-type enums
+ return self.name
+_reduce_ex_by_global_name = pickle_by_global_name
+
+def pickle_by_enum_name(self, proto):
+ # should not be used with Flag-type enums
+ return getattr, (self.__class__, self._name_)
+
+class FlagBoundary(StrEnum):
+ """
+ control how out of range values are handled
+ "strict" -> error is raised [default for Flag]
+ "conform" -> extra bits are discarded
+ "eject" -> lose flag status
+ "keep" -> keep flag status and all bits [default for IntFlag]
+ """
+ STRICT = auto()
+ CONFORM = auto()
+ EJECT = auto()
+ KEEP = auto()
+STRICT, CONFORM, EJECT, KEEP = FlagBoundary
+
+
+class Flag(Enum, boundary=STRICT):
+ """
+ Support for flags
+ """
+
+ _numeric_repr_ = repr
+
+ @staticmethod
+ def _generate_next_value_(name, start, count, last_values):
+ """
+ Generate the next value when not given.
+
+ name: the name of the member
+ start: the initial start value or None
+ count: the number of existing members
+ last_values: the last value assigned or None
+ """
+ if not count:
+ return start if start is not None else 1
+ last_value = max(last_values)
+ try:
+ high_bit = _high_bit(last_value)
+ except Exception:
+ raise TypeError('invalid flag value %r' % last_value) from None
+ return 2 ** (high_bit+1)
+
+ @classmethod
+ def _iter_member_by_value_(cls, value):
+ """
+ Extract all members from the value in definition (i.e. increasing value) order.
+ """
+ for val in _iter_bits_lsb(value & cls._flag_mask_):
+ yield cls._value2member_map_.get(val)
+
+ _iter_member_ = _iter_member_by_value_
+
+ @classmethod
+ def _iter_member_by_def_(cls, value):
+ """
+ Extract all members from the value in definition order.
+ """
+ yield from sorted(
+ cls._iter_member_by_value_(value),
+ key=lambda m: m._sort_order_,
+ )
+
+ @classmethod
+ def _missing_(cls, value):
+ """
+ Create a composite member containing all canonical members present in `value`.
+
+ If non-member values are present, result depends on `_boundary_` setting.
+ """
+ if not isinstance(value, int):
+ raise ValueError(
+ "%r is not a valid %s" % (value, cls.__qualname__)
+ )
+ # check boundaries
+ # - value must be in range (e.g. -16 <-> +15, i.e. ~15 <-> 15)
+ # - value must not include any skipped flags (e.g. if bit 2 is not
+ # defined, then 0d10 is invalid)
+ flag_mask = cls._flag_mask_
+ singles_mask = cls._singles_mask_
+ all_bits = cls._all_bits_
+ neg_value = None
+ if (
+ not ~all_bits <= value <= all_bits
+ or value & (all_bits ^ flag_mask)
+ ):
+ if cls._boundary_ is STRICT:
+ max_bits = max(value.bit_length(), flag_mask.bit_length())
+ raise ValueError(
+ "%r invalid value %r\n given %s\n allowed %s" % (
+ cls, value, bin(value, max_bits), bin(flag_mask, max_bits),
+ ))
+ elif cls._boundary_ is CONFORM:
+ value = value & flag_mask
+ elif cls._boundary_ is EJECT:
+ return value
+ elif cls._boundary_ is KEEP:
+ if value < 0:
+ value = (
+ max(all_bits+1, 2**(value.bit_length()))
+ + value
+ )
+ else:
+ raise ValueError(
+ '%r unknown flag boundary %r' % (cls, cls._boundary_, )
+ )
+ if value < 0:
+ neg_value = value
+ value = all_bits + 1 + value
+ # get members and unknown
+ unknown = value & ~flag_mask
+ aliases = value & ~singles_mask
+ member_value = value & singles_mask
+ if unknown and cls._boundary_ is not KEEP:
+ raise ValueError(
+ '%s(%r) --> unknown values %r [%s]'
+ % (cls.__name__, value, unknown, bin(unknown))
+ )
+ # normal Flag?
+ if cls._member_type_ is object:
+ # construct a singleton enum pseudo-member
+ pseudo_member = object.__new__(cls)
+ else:
+ pseudo_member = cls._member_type_.__new__(cls, value)
+ if not hasattr(pseudo_member, '_value_'):
+ pseudo_member._value_ = value
+ if member_value or aliases:
+ members = []
+ combined_value = 0
+ for m in cls._iter_member_(member_value):
+ members.append(m)
+ combined_value |= m._value_
+ if aliases:
+ value = member_value | aliases
+ for n, pm in cls._member_map_.items():
+ if pm not in members and pm._value_ and pm._value_ & value == pm._value_:
+ members.append(pm)
+ combined_value |= pm._value_
+ unknown = value ^ combined_value
+ pseudo_member._name_ = '|'.join([m._name_ for m in members])
+ if not combined_value:
+ pseudo_member._name_ = None
+ elif unknown and cls._boundary_ is STRICT:
+ raise ValueError('%r: no members with value %r' % (cls, unknown))
+ elif unknown:
+ pseudo_member._name_ += '|%s' % cls._numeric_repr_(unknown)
+ else:
+ pseudo_member._name_ = None
+ # use setdefault in case another thread already created a composite
+ # with this value
+ # note: zero is a special case -- always add it
+ pseudo_member = cls._value2member_map_.setdefault(value, pseudo_member)
+ if neg_value is not None:
+ cls._value2member_map_[neg_value] = pseudo_member
+ return pseudo_member
+
+ def __contains__(self, other):
+ """
+ Returns True if self has at least the same flags set as other.
+ """
+ if not isinstance(other, self.__class__):
+ raise TypeError(
+ "unsupported operand type(s) for 'in': %r and %r" % (
+ type(other).__qualname__, self.__class__.__qualname__))
+ return other._value_ & self._value_ == other._value_
+
+ def __iter__(self):
+ """
+ Returns flags in definition order.
+ """
+ yield from self._iter_member_(self._value_)
+
+ def __len__(self):
+ return self._value_.bit_count()
+
+ def __repr__(self):
+ cls_name = self.__class__.__name__
+ v_repr = self.__class__._value_repr_ or repr
+ if self._name_ is None:
+ return "<%s: %s>" % (cls_name, v_repr(self._value_))
+ else:
+ return "<%s.%s: %s>" % (cls_name, self._name_, v_repr(self._value_))
+
+ def __str__(self):
+ cls_name = self.__class__.__name__
+ if self._name_ is None:
+ return '%s(%r)' % (cls_name, self._value_)
+ else:
+ return "%s.%s" % (cls_name, self._name_)
+
+ def __bool__(self):
+ return bool(self._value_)
+
+ def _get_value(self, flag):
+ if isinstance(flag, self.__class__):
+ return flag._value_
+ elif self._member_type_ is not object and isinstance(flag, self._member_type_):
+ return flag
+ return NotImplemented
+
+ def __or__(self, other):
+ other_value = self._get_value(other)
+ if other_value is NotImplemented:
+ return NotImplemented
+
+ for flag in self, other:
+ if self._get_value(flag) is None:
+ raise TypeError(f"'{flag}' cannot be combined with other flags with |")
+ value = self._value_
+ return self.__class__(value | other_value)
+
+ def __and__(self, other):
+ other_value = self._get_value(other)
+ if other_value is NotImplemented:
+ return NotImplemented
+
+ for flag in self, other:
+ if self._get_value(flag) is None:
+ raise TypeError(f"'{flag}' cannot be combined with other flags with &")
+ value = self._value_
+ return self.__class__(value & other_value)
+
+ def __xor__(self, other):
+ other_value = self._get_value(other)
+ if other_value is NotImplemented:
+ return NotImplemented
+
+ for flag in self, other:
+ if self._get_value(flag) is None:
+ raise TypeError(f"'{flag}' cannot be combined with other flags with ^")
+ value = self._value_
+ return self.__class__(value ^ other_value)
+
+ def __invert__(self):
+ if self._get_value(self) is None:
+ raise TypeError(f"'{self}' cannot be inverted")
+
+ if self._inverted_ is None:
+ if self._boundary_ in (EJECT, KEEP):
+ self._inverted_ = self.__class__(~self._value_)
+ else:
+ self._inverted_ = self.__class__(self._singles_mask_ & ~self._value_)
+ return self._inverted_
+
+ __rand__ = __and__
+ __ror__ = __or__
+ __rxor__ = __xor__
+
+
+class IntFlag(int, ReprEnum, Flag, boundary=KEEP):
+ """
+ Support for integer-based Flags
+ """
+
+
+def _high_bit(value):
+ """
+ returns index of highest bit, or -1 if value is zero or negative
+ """
+ return value.bit_length() - 1
+
+def unique(enumeration):
+ """
+ Class decorator for enumerations ensuring unique member values.
+ """
+ duplicates = []
+ for name, member in enumeration.__members__.items():
+ if name != member.name:
+ duplicates.append((name, member.name))
+ if duplicates:
+ alias_details = ', '.join(
+ ["%s -> %s" % (alias, name) for (alias, name) in duplicates])
+ raise ValueError('duplicate values found in %r: %s' %
+ (enumeration, alias_details))
+ return enumeration
+
+def _dataclass_repr(self):
+ dcf = self.__dataclass_fields__
+ return ', '.join(
+ '%s=%r' % (k, getattr(self, k))
+ for k in dcf.keys()
+ if dcf[k].repr
+ )
+
+def global_enum_repr(self):
+ """
+ use module.enum_name instead of class.enum_name
+
+ the module is the last module in case of a multi-module name
+ """
+ module = self.__class__.__module__.split('.')[-1]
+ return '%s.%s' % (module, self._name_)
+
+def global_flag_repr(self):
+ """
+ use module.flag_name instead of class.flag_name
+
+ the module is the last module in case of a multi-module name
+ """
+ module = self.__class__.__module__.split('.')[-1]
+ cls_name = self.__class__.__name__
+ if self._name_ is None:
+ return "%s.%s(%r)" % (module, cls_name, self._value_)
+ if _is_single_bit(self._value_):
+ return '%s.%s' % (module, self._name_)
+ if self._boundary_ is not FlagBoundary.KEEP:
+ return '|'.join(['%s.%s' % (module, name) for name in self.name.split('|')])
+ else:
+ name = []
+ for n in self._name_.split('|'):
+ if n[0].isdigit():
+ name.append(n)
+ else:
+ name.append('%s.%s' % (module, n))
+ return '|'.join(name)
+
+def global_str(self):
+ """
+ use enum_name instead of class.enum_name
+ """
+ if self._name_ is None:
+ cls_name = self.__class__.__name__
+ return "%s(%r)" % (cls_name, self._value_)
+ else:
+ return self._name_
+
+def global_enum(cls, update_str=False):
+ """
+ decorator that makes the repr() of an enum member reference its module
+ instead of its class; also exports all members to the enum's module's
+ global namespace
+ """
+ if issubclass(cls, Flag):
+ cls.__repr__ = global_flag_repr
+ else:
+ cls.__repr__ = global_enum_repr
+ if not issubclass(cls, ReprEnum) or update_str:
+ cls.__str__ = global_str
+ sys.modules[cls.__module__].__dict__.update(cls.__members__)
+ return cls
+
+def _simple_enum(etype=Enum, *, boundary=None, use_args=None):
+ """
+ Class decorator that converts a normal class into an :class:`Enum`. No
+ safety checks are done, and some advanced behavior (such as
+ :func:`__init_subclass__`) is not available. Enum creation can be faster
+ using :func:`_simple_enum`.
+
+ >>> from enum import Enum, _simple_enum
+ >>> @_simple_enum(Enum)
+ ... class Color:
+ ... RED = auto()
+ ... GREEN = auto()
+ ... BLUE = auto()
+ >>> Color
+
+ """
+ def convert_class(cls):
+ nonlocal use_args
+ cls_name = cls.__name__
+ if use_args is None:
+ use_args = etype._use_args_
+ __new__ = cls.__dict__.get('__new__')
+ if __new__ is not None:
+ new_member = __new__.__func__
+ else:
+ new_member = etype._member_type_.__new__
+ attrs = {}
+ body = {}
+ if __new__ is not None:
+ body['__new_member__'] = new_member
+ body['_new_member_'] = new_member
+ body['_use_args_'] = use_args
+ body['_generate_next_value_'] = gnv = etype._generate_next_value_
+ body['_member_names_'] = member_names = []
+ body['_member_map_'] = member_map = {}
+ body['_value2member_map_'] = value2member_map = {}
+ body['_hashable_values_'] = hashable_values = []
+ body['_unhashable_values_'] = unhashable_values = []
+ body['_unhashable_values_map_'] = {}
+ body['_member_type_'] = member_type = etype._member_type_
+ body['_value_repr_'] = etype._value_repr_
+ if issubclass(etype, Flag):
+ body['_boundary_'] = boundary or etype._boundary_
+ body['_flag_mask_'] = None
+ body['_all_bits_'] = None
+ body['_singles_mask_'] = None
+ body['_inverted_'] = None
+ body['__or__'] = Flag.__or__
+ body['__xor__'] = Flag.__xor__
+ body['__and__'] = Flag.__and__
+ body['__ror__'] = Flag.__ror__
+ body['__rxor__'] = Flag.__rxor__
+ body['__rand__'] = Flag.__rand__
+ body['__invert__'] = Flag.__invert__
+ for name, obj in cls.__dict__.items():
+ if name in ('__dict__', '__weakref__'):
+ continue
+ if _is_dunder(name) or _is_private(cls_name, name) or _is_sunder(name) or _is_descriptor(obj):
+ body[name] = obj
+ else:
+ attrs[name] = obj
+ if cls.__dict__.get('__doc__') is None:
+ body['__doc__'] = 'An enumeration.'
+ #
+ # double check that repr and friends are not the mixin's or various
+ # things break (such as pickle)
+ # however, if the method is defined in the Enum itself, don't replace
+ # it
+ enum_class = type(cls_name, (etype, ), body, boundary=boundary, _simple=True)
+ for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'):
+ if name not in body:
+ # check for mixin overrides before replacing
+ enum_method = getattr(etype, name)
+ found_method = getattr(enum_class, name)
+ object_method = getattr(object, name)
+ data_type_method = getattr(member_type, name)
+ if found_method in (data_type_method, object_method):
+ setattr(enum_class, name, enum_method)
+ gnv_last_values = []
+ if issubclass(enum_class, Flag):
+ # Flag / IntFlag
+ single_bits = multi_bits = 0
+ for name, value in attrs.items():
+ if isinstance(value, auto) and auto.value is _auto_null:
+ value = gnv(name, 1, len(member_names), gnv_last_values)
+ # create basic member (possibly isolate value for alias check)
+ if use_args:
+ if not isinstance(value, tuple):
+ value = (value, )
+ member = new_member(enum_class, *value)
+ value = value[0]
+ else:
+ member = new_member(enum_class)
+ if __new__ is None:
+ member._value_ = value
+ # now check if alias
+ try:
+ contained = value2member_map.get(member._value_)
+ except TypeError:
+ contained = None
+ if member._value_ in unhashable_values or member.value in hashable_values:
+ for m in enum_class:
+ if m._value_ == member._value_:
+ contained = m
+ break
+ if contained is not None:
+ # an alias to an existing member
+ contained._add_alias_(name)
+ else:
+ # finish creating member
+ member._name_ = name
+ member.__objclass__ = enum_class
+ member.__init__(value)
+ member._sort_order_ = len(member_names)
+ if name not in ('name', 'value'):
+ setattr(enum_class, name, member)
+ member_map[name] = member
+ else:
+ enum_class._add_member_(name, member)
+ value2member_map[value] = member
+ hashable_values.append(value)
+ if _is_single_bit(value):
+ # not a multi-bit alias, record in _member_names_ and _flag_mask_
+ member_names.append(name)
+ single_bits |= value
+ else:
+ multi_bits |= value
+ gnv_last_values.append(value)
+ enum_class._flag_mask_ = single_bits | multi_bits
+ enum_class._singles_mask_ = single_bits
+ enum_class._all_bits_ = 2 ** ((single_bits|multi_bits).bit_length()) - 1
+ # set correct __iter__
+ member_list = [m._value_ for m in enum_class]
+ if member_list != sorted(member_list):
+ enum_class._iter_member_ = enum_class._iter_member_by_def_
+ else:
+ # Enum / IntEnum / StrEnum
+ for name, value in attrs.items():
+ if isinstance(value, auto):
+ if value.value is _auto_null:
+ value.value = gnv(name, 1, len(member_names), gnv_last_values)
+ value = value.value
+ # create basic member (possibly isolate value for alias check)
+ if use_args:
+ if not isinstance(value, tuple):
+ value = (value, )
+ member = new_member(enum_class, *value)
+ value = value[0]
+ else:
+ member = new_member(enum_class)
+ if __new__ is None:
+ member._value_ = value
+ # now check if alias
+ try:
+ contained = value2member_map.get(member._value_)
+ except TypeError:
+ contained = None
+ if member._value_ in unhashable_values or member._value_ in hashable_values:
+ for m in enum_class:
+ if m._value_ == member._value_:
+ contained = m
+ break
+ if contained is not None:
+ # an alias to an existing member
+ contained._add_alias_(name)
+ else:
+ # finish creating member
+ member._name_ = name
+ member.__objclass__ = enum_class
+ member.__init__(value)
+ member._sort_order_ = len(member_names)
+ if name not in ('name', 'value'):
+ setattr(enum_class, name, member)
+ member_map[name] = member
+ else:
+ enum_class._add_member_(name, member)
+ member_names.append(name)
+ gnv_last_values.append(value)
+ try:
+ # This may fail if value is not hashable. We can't add the value
+ # to the map, and by-value lookups for this value will be
+ # linear.
+ enum_class._value2member_map_.setdefault(value, member)
+ if value not in hashable_values:
+ hashable_values.append(value)
+ except TypeError:
+ # keep track of the value in a list so containment checks are quick
+ enum_class._unhashable_values_.append(value)
+ enum_class._unhashable_values_map_.setdefault(name, []).append(value)
+ if '__new__' in body:
+ enum_class.__new_member__ = enum_class.__new__
+ enum_class.__new__ = Enum.__new__
+ return enum_class
+ return convert_class
+
+@_simple_enum(StrEnum)
+class EnumCheck:
+ """
+ various conditions to check an enumeration for
+ """
+ CONTINUOUS = "no skipped integer values"
+ NAMED_FLAGS = "multi-flag aliases may not contain unnamed flags"
+ UNIQUE = "one name per value"
+CONTINUOUS, NAMED_FLAGS, UNIQUE = EnumCheck
+
+
+class verify:
+ """
+ Check an enumeration for various constraints. (see EnumCheck)
+ """
+ def __init__(self, *checks):
+ self.checks = checks
+ def __call__(self, enumeration):
+ checks = self.checks
+ cls_name = enumeration.__name__
+ if Flag is not None and issubclass(enumeration, Flag):
+ enum_type = 'flag'
+ elif issubclass(enumeration, Enum):
+ enum_type = 'enum'
+ else:
+ raise TypeError("the 'verify' decorator only works with Enum and Flag")
+ for check in checks:
+ if check is UNIQUE:
+ # check for duplicate names
+ duplicates = []
+ for name, member in enumeration.__members__.items():
+ if name != member.name:
+ duplicates.append((name, member.name))
+ if duplicates:
+ alias_details = ', '.join(
+ ["%s -> %s" % (alias, name) for (alias, name) in duplicates])
+ raise ValueError('aliases found in %r: %s' %
+ (enumeration, alias_details))
+ elif check is CONTINUOUS:
+ values = set(e.value for e in enumeration)
+ if len(values) < 2:
+ continue
+ low, high = min(values), max(values)
+ missing = []
+ if enum_type == 'flag':
+ # check for powers of two
+ for i in range(_high_bit(low)+1, _high_bit(high)):
+ if 2**i not in values:
+ missing.append(2**i)
+ elif enum_type == 'enum':
+ # check for missing consecutive integers
+ for i in range(low+1, high):
+ if i not in values:
+ missing.append(i)
+ else:
+ raise Exception('verify: unknown type %r' % enum_type)
+ if missing:
+ raise ValueError(('invalid %s %r: missing values %s' % (
+ enum_type, cls_name, ', '.join((str(m) for m in missing)))
+ )[:256])
+ # limit max length to protect against DOS attacks
+ elif check is NAMED_FLAGS:
+ # examine each alias and check for unnamed flags
+ member_names = enumeration._member_names_
+ member_values = [m.value for m in enumeration]
+ missing_names = []
+ missing_value = 0
+ for name, alias in enumeration._member_map_.items():
+ if name in member_names:
+ # not an alias
+ continue
+ if alias.value < 0:
+ # negative numbers are not checked
+ continue
+ values = list(_iter_bits_lsb(alias.value))
+ missed = [v for v in values if v not in member_values]
+ if missed:
+ missing_names.append(name)
+ for val in missed:
+ missing_value |= val
+ if missing_names:
+ if len(missing_names) == 1:
+ alias = 'alias %s is missing' % missing_names[0]
+ else:
+ alias = 'aliases %s and %s are missing' % (
+ ', '.join(missing_names[:-1]), missing_names[-1]
+ )
+ if _is_single_bit(missing_value):
+ value = 'value 0x%x' % missing_value
+ else:
+ value = 'combined values of 0x%x' % missing_value
+ raise ValueError(
+ 'invalid Flag %r: %s %s [use enum.show_flag_values(value) for details]'
+ % (cls_name, alias, value)
+ )
+ return enumeration
+
+def _test_simple_enum(checked_enum, simple_enum):
+ """
+ A function that can be used to test an enum created with :func:`_simple_enum`
+ against the version created by subclassing :class:`Enum`::
+
+ >>> from enum import Enum, _simple_enum, _test_simple_enum
+ >>> @_simple_enum(Enum)
+ ... class Color:
+ ... RED = auto()
+ ... GREEN = auto()
+ ... BLUE = auto()
+ >>> class CheckedColor(Enum):
+ ... RED = auto()
+ ... GREEN = auto()
+ ... BLUE = auto()
+ >>> _test_simple_enum(CheckedColor, Color)
+
+ If differences are found, a :exc:`TypeError` is raised.
+ """
+ failed = []
+ if checked_enum.__dict__ != simple_enum.__dict__:
+ checked_dict = checked_enum.__dict__
+ checked_keys = list(checked_dict.keys())
+ simple_dict = simple_enum.__dict__
+ simple_keys = list(simple_dict.keys())
+ member_names = set(
+ list(checked_enum._member_map_.keys())
+ + list(simple_enum._member_map_.keys())
+ )
+ for key in set(checked_keys + simple_keys):
+ if key in ('__module__', '_member_map_', '_value2member_map_', '__doc__',
+ '__static_attributes__', '__firstlineno__'):
+ # keys known to be different, or very long
+ continue
+ elif key in member_names:
+ # members are checked below
+ continue
+ elif key not in simple_keys:
+ failed.append("missing key: %r" % (key, ))
+ elif key not in checked_keys:
+ failed.append("extra key: %r" % (key, ))
+ else:
+ checked_value = checked_dict[key]
+ simple_value = simple_dict[key]
+ if callable(checked_value) or isinstance(checked_value, bltns.property):
+ continue
+ if key == '__doc__':
+ # remove all spaces/tabs
+ compressed_checked_value = checked_value.replace(' ','').replace('\t','')
+ compressed_simple_value = simple_value.replace(' ','').replace('\t','')
+ if compressed_checked_value != compressed_simple_value:
+ failed.append("%r:\n %s\n %s" % (
+ key,
+ "checked -> %r" % (checked_value, ),
+ "simple -> %r" % (simple_value, ),
+ ))
+ elif checked_value != simple_value:
+ failed.append("%r:\n %s\n %s" % (
+ key,
+ "checked -> %r" % (checked_value, ),
+ "simple -> %r" % (simple_value, ),
+ ))
+ failed.sort()
+ for name in member_names:
+ failed_member = []
+ if name not in simple_keys:
+ failed.append('missing member from simple enum: %r' % name)
+ elif name not in checked_keys:
+ failed.append('extra member in simple enum: %r' % name)
+ else:
+ checked_member_dict = checked_enum[name].__dict__
+ checked_member_keys = list(checked_member_dict.keys())
+ simple_member_dict = simple_enum[name].__dict__
+ simple_member_keys = list(simple_member_dict.keys())
+ for key in set(checked_member_keys + simple_member_keys):
+ if key in ('__module__', '__objclass__', '_inverted_'):
+ # keys known to be different or absent
+ continue
+ elif key not in simple_member_keys:
+ failed_member.append("missing key %r not in the simple enum member %r" % (key, name))
+ elif key not in checked_member_keys:
+ failed_member.append("extra key %r in simple enum member %r" % (key, name))
+ else:
+ checked_value = checked_member_dict[key]
+ simple_value = simple_member_dict[key]
+ if checked_value != simple_value:
+ failed_member.append("%r:\n %s\n %s" % (
+ key,
+ "checked member -> %r" % (checked_value, ),
+ "simple member -> %r" % (simple_value, ),
+ ))
+ if failed_member:
+ failed.append('%r member mismatch:\n %s' % (
+ name, '\n '.join(failed_member),
+ ))
+ for method in (
+ '__str__', '__repr__', '__reduce_ex__', '__format__',
+ '__getnewargs_ex__', '__getnewargs__', '__reduce_ex__', '__reduce__'
+ ):
+ if method in simple_keys and method in checked_keys:
+ # cannot compare functions, and it exists in both, so we're good
+ continue
+ elif method not in simple_keys and method not in checked_keys:
+ # method is inherited -- check it out
+ checked_method = getattr(checked_enum, method, None)
+ simple_method = getattr(simple_enum, method, None)
+ if hasattr(checked_method, '__func__'):
+ checked_method = checked_method.__func__
+ simple_method = simple_method.__func__
+ if checked_method != simple_method:
+ failed.append("%r: %-30s %s" % (
+ method,
+ "checked -> %r" % (checked_method, ),
+ "simple -> %r" % (simple_method, ),
+ ))
+ else:
+ # if the method existed in only one of the enums, it will have been caught
+ # in the first checks above
+ pass
+ if failed:
+ raise TypeError('enum mismatch:\n %s' % '\n '.join(failed))
+
+def _old_convert_(etype, name, module, filter, source=None, *, boundary=None):
+ """
+ Create a new Enum subclass that replaces a collection of global constants
+ """
+ # convert all constants from source (or module) that pass filter() to
+ # a new Enum called name, and export the enum and its members back to
+ # module;
+ # also, replace the __reduce_ex__ method so unpickling works in
+ # previous Python versions
+ module_globals = sys.modules[module].__dict__
+ if source:
+ source = source.__dict__
+ else:
+ source = module_globals
+ # _value2member_map_ is populated in the same order every time
+ # for a consistent reverse mapping of number to name when there
+ # are multiple names for the same number.
+ members = [
+ (name, value)
+ for name, value in source.items()
+ if filter(name)]
+ try:
+ # sort by value
+ members.sort(key=lambda t: (t[1], t[0]))
+ except TypeError:
+ # unless some values aren't comparable, in which case sort by name
+ members.sort(key=lambda t: t[0])
+ cls = etype(name, members, module=module, boundary=boundary or KEEP)
+ return cls
+
+_stdlib_enums = IntEnum, StrEnum, IntFlag
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/filecmp.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/filecmp.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5b8d854d77de3dfecb058994b3436f69f5dfad5
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/filecmp.py
@@ -0,0 +1,320 @@
+"""Utilities for comparing files and directories.
+
+Classes:
+ dircmp
+
+Functions:
+ cmp(f1, f2, shallow=True) -> int
+ cmpfiles(a, b, common) -> ([], [], [])
+ clear_cache()
+
+"""
+
+import os
+import stat
+from itertools import filterfalse
+from types import GenericAlias
+
+__all__ = ['clear_cache', 'cmp', 'dircmp', 'cmpfiles', 'DEFAULT_IGNORES']
+
+_cache = {}
+BUFSIZE = 8*1024
+
+DEFAULT_IGNORES = [
+ 'RCS', 'CVS', 'tags', '.git', '.hg', '.bzr', '_darcs', '__pycache__']
+
+def clear_cache():
+ """Clear the filecmp cache."""
+ _cache.clear()
+
+def cmp(f1, f2, shallow=True):
+ """Compare two files.
+
+ Arguments:
+
+ f1 -- First file name
+
+ f2 -- Second file name
+
+ shallow -- treat files as identical if their stat signatures (type, size,
+ mtime) are identical. Otherwise, files are considered different
+ if their sizes or contents differ. [default: True]
+
+ Return value:
+
+ True if the files are the same, False otherwise.
+
+ This function uses a cache for past comparisons and the results,
+ with cache entries invalidated if their stat information
+ changes. The cache may be cleared by calling clear_cache().
+
+ """
+
+ s1 = _sig(os.stat(f1))
+ s2 = _sig(os.stat(f2))
+ if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG:
+ return False
+ if shallow and s1 == s2:
+ return True
+ if s1[1] != s2[1]:
+ return False
+
+ outcome = _cache.get((f1, f2, s1, s2))
+ if outcome is None:
+ outcome = _do_cmp(f1, f2)
+ if len(_cache) > 100: # limit the maximum size of the cache
+ clear_cache()
+ _cache[f1, f2, s1, s2] = outcome
+ return outcome
+
+def _sig(st):
+ return (stat.S_IFMT(st.st_mode),
+ st.st_size,
+ st.st_mtime)
+
+def _do_cmp(f1, f2):
+ bufsize = BUFSIZE
+ with open(f1, 'rb') as fp1, open(f2, 'rb') as fp2:
+ while True:
+ b1 = fp1.read(bufsize)
+ b2 = fp2.read(bufsize)
+ if b1 != b2:
+ return False
+ if not b1:
+ return True
+
+# Directory comparison class.
+#
+class dircmp:
+ """A class that manages the comparison of 2 directories.
+
+ dircmp(a, b, ignore=None, hide=None, *, shallow=True)
+ A and B are directories.
+ IGNORE is a list of names to ignore,
+ defaults to DEFAULT_IGNORES.
+ HIDE is a list of names to hide,
+ defaults to [os.curdir, os.pardir].
+ SHALLOW specifies whether to just check the stat signature (do not read
+ the files).
+ defaults to True.
+
+ High level usage:
+ x = dircmp(dir1, dir2)
+ x.report() -> prints a report on the differences between dir1 and dir2
+ or
+ x.report_partial_closure() -> prints report on differences between dir1
+ and dir2, and reports on common immediate subdirectories.
+ x.report_full_closure() -> like report_partial_closure,
+ but fully recursive.
+
+ Attributes:
+ left_list, right_list: The files in dir1 and dir2,
+ filtered by hide and ignore.
+ common: a list of names in both dir1 and dir2.
+ left_only, right_only: names only in dir1, dir2.
+ common_dirs: subdirectories in both dir1 and dir2.
+ common_files: files in both dir1 and dir2.
+ common_funny: names in both dir1 and dir2 where the type differs between
+ dir1 and dir2, or the name is not stat-able.
+ same_files: list of identical files.
+ diff_files: list of filenames which differ.
+ funny_files: list of files which could not be compared.
+ subdirs: a dictionary of dircmp instances (or MyDirCmp instances if this
+ object is of type MyDirCmp, a subclass of dircmp), keyed by names
+ in common_dirs.
+ """
+
+ def __init__(self, a, b, ignore=None, hide=None, *, shallow=True): # Initialize
+ self.left = a
+ self.right = b
+ if hide is None:
+ self.hide = [os.curdir, os.pardir] # Names never to be shown
+ else:
+ self.hide = hide
+ if ignore is None:
+ self.ignore = DEFAULT_IGNORES
+ else:
+ self.ignore = ignore
+ self.shallow = shallow
+
+ def phase0(self): # Compare everything except common subdirectories
+ self.left_list = _filter(os.listdir(self.left),
+ self.hide+self.ignore)
+ self.right_list = _filter(os.listdir(self.right),
+ self.hide+self.ignore)
+ self.left_list.sort()
+ self.right_list.sort()
+
+ def phase1(self): # Compute common names
+ a = dict(zip(map(os.path.normcase, self.left_list), self.left_list))
+ b = dict(zip(map(os.path.normcase, self.right_list), self.right_list))
+ self.common = list(map(a.__getitem__, filter(b.__contains__, a)))
+ self.left_only = list(map(a.__getitem__, filterfalse(b.__contains__, a)))
+ self.right_only = list(map(b.__getitem__, filterfalse(a.__contains__, b)))
+
+ def phase2(self): # Distinguish files, directories, funnies
+ self.common_dirs = []
+ self.common_files = []
+ self.common_funny = []
+
+ for x in self.common:
+ a_path = os.path.join(self.left, x)
+ b_path = os.path.join(self.right, x)
+
+ ok = True
+ try:
+ a_stat = os.stat(a_path)
+ except (OSError, ValueError):
+ # See https://github.com/python/cpython/issues/122400
+ # for the rationale for protecting against ValueError.
+ # print('Can\'t stat', a_path, ':', why.args[1])
+ ok = False
+ try:
+ b_stat = os.stat(b_path)
+ except (OSError, ValueError):
+ # print('Can\'t stat', b_path, ':', why.args[1])
+ ok = False
+
+ if ok:
+ a_type = stat.S_IFMT(a_stat.st_mode)
+ b_type = stat.S_IFMT(b_stat.st_mode)
+ if a_type != b_type:
+ self.common_funny.append(x)
+ elif stat.S_ISDIR(a_type):
+ self.common_dirs.append(x)
+ elif stat.S_ISREG(a_type):
+ self.common_files.append(x)
+ else:
+ self.common_funny.append(x)
+ else:
+ self.common_funny.append(x)
+
+ def phase3(self): # Find out differences between common files
+ xx = cmpfiles(self.left, self.right, self.common_files, self.shallow)
+ self.same_files, self.diff_files, self.funny_files = xx
+
+ def phase4(self): # Find out differences between common subdirectories
+ # A new dircmp (or MyDirCmp if dircmp was subclassed) object is created
+ # for each common subdirectory,
+ # these are stored in a dictionary indexed by filename.
+ # The hide and ignore properties are inherited from the parent
+ self.subdirs = {}
+ for x in self.common_dirs:
+ a_x = os.path.join(self.left, x)
+ b_x = os.path.join(self.right, x)
+ self.subdirs[x] = self.__class__(a_x, b_x, self.ignore, self.hide,
+ shallow=self.shallow)
+
+ def phase4_closure(self): # Recursively call phase4() on subdirectories
+ self.phase4()
+ for sd in self.subdirs.values():
+ sd.phase4_closure()
+
+ def report(self): # Print a report on the differences between a and b
+ # Output format is purposely lousy
+ print('diff', self.left, self.right)
+ if self.left_only:
+ self.left_only.sort()
+ print('Only in', self.left, ':', self.left_only)
+ if self.right_only:
+ self.right_only.sort()
+ print('Only in', self.right, ':', self.right_only)
+ if self.same_files:
+ self.same_files.sort()
+ print('Identical files :', self.same_files)
+ if self.diff_files:
+ self.diff_files.sort()
+ print('Differing files :', self.diff_files)
+ if self.funny_files:
+ self.funny_files.sort()
+ print('Trouble with common files :', self.funny_files)
+ if self.common_dirs:
+ self.common_dirs.sort()
+ print('Common subdirectories :', self.common_dirs)
+ if self.common_funny:
+ self.common_funny.sort()
+ print('Common funny cases :', self.common_funny)
+
+ def report_partial_closure(self): # Print reports on self and on subdirs
+ self.report()
+ for sd in self.subdirs.values():
+ print()
+ sd.report()
+
+ def report_full_closure(self): # Report on self and subdirs recursively
+ self.report()
+ for sd in self.subdirs.values():
+ print()
+ sd.report_full_closure()
+
+ methodmap = dict(subdirs=phase4,
+ same_files=phase3, diff_files=phase3, funny_files=phase3,
+ common_dirs=phase2, common_files=phase2, common_funny=phase2,
+ common=phase1, left_only=phase1, right_only=phase1,
+ left_list=phase0, right_list=phase0)
+
+ def __getattr__(self, attr):
+ if attr not in self.methodmap:
+ raise AttributeError(attr)
+ self.methodmap[attr](self)
+ return getattr(self, attr)
+
+ __class_getitem__ = classmethod(GenericAlias)
+
+
+def cmpfiles(a, b, common, shallow=True):
+ """Compare common files in two directories.
+
+ a, b -- directory names
+ common -- list of file names found in both directories
+ shallow -- if true, do comparison based solely on stat() information
+
+ Returns a tuple of three lists:
+ files that compare equal
+ files that are different
+ filenames that aren't regular files.
+
+ """
+ res = ([], [], [])
+ for x in common:
+ ax = os.path.join(a, x)
+ bx = os.path.join(b, x)
+ res[_cmp(ax, bx, shallow)].append(x)
+ return res
+
+
+# Compare two files.
+# Return:
+# 0 for equal
+# 1 for different
+# 2 for funny cases (can't stat, NUL bytes, etc.)
+#
+def _cmp(a, b, sh, abs=abs, cmp=cmp):
+ try:
+ return not abs(cmp(a, b, sh))
+ except (OSError, ValueError):
+ return 2
+
+
+# Return a copy with items that occur in skip removed.
+#
+def _filter(flist, skip):
+ return list(filterfalse(skip.__contains__, flist))
+
+
+# Demonstration and testing.
+#
+def demo():
+ import sys
+ import getopt
+ options, args = getopt.getopt(sys.argv[1:], 'r')
+ if len(args) != 2:
+ raise getopt.GetoptError('need exactly two args', None)
+ dd = dircmp(args[0], args[1])
+ if ('-r', '') in options:
+ dd.report_full_closure()
+ else:
+ dd.report()
+
+if __name__ == '__main__':
+ demo()
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/fileinput.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/fileinput.py
new file mode 100644
index 0000000000000000000000000000000000000000..3dba3d2fbfa967b613b8928d6fb36ae73162b274
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/fileinput.py
@@ -0,0 +1,442 @@
+"""Helper class to quickly write a loop over all standard input files.
+
+Typical use is:
+
+ import fileinput
+ for line in fileinput.input(encoding="utf-8"):
+ process(line)
+
+This iterates over the lines of all files listed in sys.argv[1:],
+defaulting to sys.stdin if the list is empty. If a filename is '-' it
+is also replaced by sys.stdin and the optional arguments mode and
+openhook are ignored. To specify an alternative list of filenames,
+pass it as the argument to input(). A single file name is also allowed.
+
+Functions filename(), lineno() return the filename and cumulative line
+number of the line that has just been read; filelineno() returns its
+line number in the current file; isfirstline() returns true iff the
+line just read is the first line of its file; isstdin() returns true
+iff the line was read from sys.stdin. Function nextfile() closes the
+current file so that the next iteration will read the first line from
+the next file (if any); lines not read from the file will not count
+towards the cumulative line count; the filename is not changed until
+after the first line of the next file has been read. Function close()
+closes the sequence.
+
+Before any lines have been read, filename() returns None and both line
+numbers are zero; nextfile() has no effect. After all lines have been
+read, filename() and the line number functions return the values
+pertaining to the last line read; nextfile() has no effect.
+
+All files are opened in text mode by default, you can override this by
+setting the mode parameter to input() or FileInput.__init__().
+If an I/O error occurs during opening or reading a file, the OSError
+exception is raised.
+
+If sys.stdin is used more than once, the second and further use will
+return no lines, except perhaps for interactive use, or if it has been
+explicitly reset (e.g. using sys.stdin.seek(0)).
+
+Empty files are opened and immediately closed; the only time their
+presence in the list of filenames is noticeable at all is when the
+last file opened is empty.
+
+It is possible that the last line of a file doesn't end in a newline
+character; otherwise lines are returned including the trailing
+newline.
+
+Class FileInput is the implementation; its methods filename(),
+lineno(), fileline(), isfirstline(), isstdin(), nextfile() and close()
+correspond to the functions in the module. In addition it has a
+readline() method which returns the next input line, and a
+__getitem__() method which implements the sequence behavior. The
+sequence must be accessed in strictly sequential order; sequence
+access and readline() cannot be mixed.
+
+Optional in-place filtering: if the keyword argument inplace=True is
+passed to input() or to the FileInput constructor, the file is moved
+to a backup file and standard output is directed to the input file.
+This makes it possible to write a filter that rewrites its input file
+in place. If the keyword argument backup="." is also
+given, it specifies the extension for the backup file, and the backup
+file remains around; by default, the extension is ".bak" and it is
+deleted when the output file is closed. In-place filtering is
+disabled when standard input is read. XXX The current implementation
+does not work for MS-DOS 8+3 filesystems.
+"""
+
+import io
+import sys, os
+from types import GenericAlias
+
+__all__ = ["input", "close", "nextfile", "filename", "lineno", "filelineno",
+ "fileno", "isfirstline", "isstdin", "FileInput", "hook_compressed",
+ "hook_encoded"]
+
+_state = None
+
+def input(files=None, inplace=False, backup="", *, mode="r", openhook=None,
+ encoding=None, errors=None):
+ """Return an instance of the FileInput class, which can be iterated.
+
+ The parameters are passed to the constructor of the FileInput class.
+ The returned instance, in addition to being an iterator,
+ keeps global state for the functions of this module,.
+ """
+ global _state
+ if _state and _state._file:
+ raise RuntimeError("input() already active")
+ _state = FileInput(files, inplace, backup, mode=mode, openhook=openhook,
+ encoding=encoding, errors=errors)
+ return _state
+
+def close():
+ """Close the sequence."""
+ global _state
+ state = _state
+ _state = None
+ if state:
+ state.close()
+
+def nextfile():
+ """
+ Close the current file so that the next iteration will read the first
+ line from the next file (if any); lines not read from the file will
+ not count towards the cumulative line count. The filename is not
+ changed until after the first line of the next file has been read.
+ Before the first line has been read, this function has no effect;
+ it cannot be used to skip the first file. After the last line of the
+ last file has been read, this function has no effect.
+ """
+ if not _state:
+ raise RuntimeError("no active input()")
+ return _state.nextfile()
+
+def filename():
+ """
+ Return the name of the file currently being read.
+ Before the first line has been read, returns None.
+ """
+ if not _state:
+ raise RuntimeError("no active input()")
+ return _state.filename()
+
+def lineno():
+ """
+ Return the cumulative line number of the line that has just been read.
+ Before the first line has been read, returns 0. After the last line
+ of the last file has been read, returns the line number of that line.
+ """
+ if not _state:
+ raise RuntimeError("no active input()")
+ return _state.lineno()
+
+def filelineno():
+ """
+ Return the line number in the current file. Before the first line
+ has been read, returns 0. After the last line of the last file has
+ been read, returns the line number of that line within the file.
+ """
+ if not _state:
+ raise RuntimeError("no active input()")
+ return _state.filelineno()
+
+def fileno():
+ """
+ Return the file number of the current file. When no file is currently
+ opened, returns -1.
+ """
+ if not _state:
+ raise RuntimeError("no active input()")
+ return _state.fileno()
+
+def isfirstline():
+ """
+ Returns true the line just read is the first line of its file,
+ otherwise returns false.
+ """
+ if not _state:
+ raise RuntimeError("no active input()")
+ return _state.isfirstline()
+
+def isstdin():
+ """
+ Returns true if the last line was read from sys.stdin,
+ otherwise returns false.
+ """
+ if not _state:
+ raise RuntimeError("no active input()")
+ return _state.isstdin()
+
+class FileInput:
+ """FileInput([files[, inplace[, backup]]], *, mode=None, openhook=None)
+
+ Class FileInput is the implementation of the module; its methods
+ filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(),
+ nextfile() and close() correspond to the functions of the same name
+ in the module.
+ In addition it has a readline() method which returns the next
+ input line, and a __getitem__() method which implements the
+ sequence behavior. The sequence must be accessed in strictly
+ sequential order; random access and readline() cannot be mixed.
+ """
+
+ def __init__(self, files=None, inplace=False, backup="", *,
+ mode="r", openhook=None, encoding=None, errors=None):
+ if isinstance(files, str):
+ files = (files,)
+ elif isinstance(files, os.PathLike):
+ files = (os.fspath(files), )
+ else:
+ if files is None:
+ files = sys.argv[1:]
+ if not files:
+ files = ('-',)
+ else:
+ files = tuple(files)
+ self._files = files
+ self._inplace = inplace
+ self._backup = backup
+ self._savestdout = None
+ self._output = None
+ self._filename = None
+ self._startlineno = 0
+ self._filelineno = 0
+ self._file = None
+ self._isstdin = False
+ self._backupfilename = None
+ self._encoding = encoding
+ self._errors = errors
+
+ # We can not use io.text_encoding() here because old openhook doesn't
+ # take encoding parameter.
+ if (sys.flags.warn_default_encoding and
+ "b" not in mode and encoding is None and openhook is None):
+ import warnings
+ warnings.warn("'encoding' argument not specified.",
+ EncodingWarning, 2)
+
+ # restrict mode argument to reading modes
+ if mode not in ('r', 'rb'):
+ raise ValueError("FileInput opening mode must be 'r' or 'rb'")
+ self._mode = mode
+ self._write_mode = mode.replace('r', 'w')
+ if openhook:
+ if inplace:
+ raise ValueError("FileInput cannot use an opening hook in inplace mode")
+ if not callable(openhook):
+ raise ValueError("FileInput openhook must be callable")
+ self._openhook = openhook
+
+ def __del__(self):
+ self.close()
+
+ def close(self):
+ try:
+ self.nextfile()
+ finally:
+ self._files = ()
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, type, value, traceback):
+ self.close()
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ while True:
+ line = self._readline()
+ if line:
+ self._filelineno += 1
+ return line
+ if not self._file:
+ raise StopIteration
+ self.nextfile()
+ # repeat with next file
+
+ def nextfile(self):
+ savestdout = self._savestdout
+ self._savestdout = None
+ if savestdout:
+ sys.stdout = savestdout
+
+ output = self._output
+ self._output = None
+ try:
+ if output:
+ output.close()
+ finally:
+ file = self._file
+ self._file = None
+ try:
+ del self._readline # restore FileInput._readline
+ except AttributeError:
+ pass
+ try:
+ if file and not self._isstdin:
+ file.close()
+ finally:
+ backupfilename = self._backupfilename
+ self._backupfilename = None
+ if backupfilename and not self._backup:
+ try: os.unlink(backupfilename)
+ except OSError: pass
+
+ self._isstdin = False
+
+ def readline(self):
+ while True:
+ line = self._readline()
+ if line:
+ self._filelineno += 1
+ return line
+ if not self._file:
+ return line
+ self.nextfile()
+ # repeat with next file
+
+ def _readline(self):
+ if not self._files:
+ if 'b' in self._mode:
+ return b''
+ else:
+ return ''
+ self._filename = self._files[0]
+ self._files = self._files[1:]
+ self._startlineno = self.lineno()
+ self._filelineno = 0
+ self._file = None
+ self._isstdin = False
+ self._backupfilename = 0
+
+ # EncodingWarning is emitted in __init__() already
+ if "b" not in self._mode:
+ encoding = self._encoding or "locale"
+ else:
+ encoding = None
+
+ if self._filename == '-':
+ self._filename = ''
+ if 'b' in self._mode:
+ self._file = getattr(sys.stdin, 'buffer', sys.stdin)
+ else:
+ self._file = sys.stdin
+ self._isstdin = True
+ else:
+ if self._inplace:
+ self._backupfilename = (
+ os.fspath(self._filename) + (self._backup or ".bak"))
+ try:
+ os.unlink(self._backupfilename)
+ except OSError:
+ pass
+ # The next few lines may raise OSError
+ os.rename(self._filename, self._backupfilename)
+ self._file = open(self._backupfilename, self._mode,
+ encoding=encoding, errors=self._errors)
+ try:
+ perm = os.fstat(self._file.fileno()).st_mode
+ except OSError:
+ self._output = open(self._filename, self._write_mode,
+ encoding=encoding, errors=self._errors)
+ else:
+ mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
+ if hasattr(os, 'O_BINARY'):
+ mode |= os.O_BINARY
+
+ fd = os.open(self._filename, mode, perm)
+ self._output = os.fdopen(fd, self._write_mode,
+ encoding=encoding, errors=self._errors)
+ try:
+ os.chmod(self._filename, perm)
+ except OSError:
+ pass
+ self._savestdout = sys.stdout
+ sys.stdout = self._output
+ else:
+ # This may raise OSError
+ if self._openhook:
+ # Custom hooks made previous to Python 3.10 didn't have
+ # encoding argument
+ if self._encoding is None:
+ self._file = self._openhook(self._filename, self._mode)
+ else:
+ self._file = self._openhook(
+ self._filename, self._mode, encoding=self._encoding, errors=self._errors)
+ else:
+ self._file = open(self._filename, self._mode, encoding=encoding, errors=self._errors)
+ self._readline = self._file.readline # hide FileInput._readline
+ return self._readline()
+
+ def filename(self):
+ return self._filename
+
+ def lineno(self):
+ return self._startlineno + self._filelineno
+
+ def filelineno(self):
+ return self._filelineno
+
+ def fileno(self):
+ if self._file:
+ try:
+ return self._file.fileno()
+ except ValueError:
+ return -1
+ else:
+ return -1
+
+ def isfirstline(self):
+ return self._filelineno == 1
+
+ def isstdin(self):
+ return self._isstdin
+
+ __class_getitem__ = classmethod(GenericAlias)
+
+
+def hook_compressed(filename, mode, *, encoding=None, errors=None):
+ if encoding is None and "b" not in mode: # EncodingWarning is emitted in FileInput() already.
+ encoding = "locale"
+ ext = os.path.splitext(filename)[1]
+ if ext == '.gz':
+ import gzip
+ stream = gzip.open(filename, mode)
+ elif ext == '.bz2':
+ import bz2
+ stream = bz2.BZ2File(filename, mode)
+ else:
+ return open(filename, mode, encoding=encoding, errors=errors)
+
+ # gzip and bz2 are binary mode by default.
+ if "b" not in mode:
+ stream = io.TextIOWrapper(stream, encoding=encoding, errors=errors)
+ return stream
+
+
+def hook_encoded(encoding, errors=None):
+ def openhook(filename, mode):
+ return open(filename, mode, encoding=encoding, errors=errors)
+ return openhook
+
+
+def _test():
+ import getopt
+ inplace = False
+ backup = False
+ opts, args = getopt.getopt(sys.argv[1:], "ib:")
+ for o, a in opts:
+ if o == '-i': inplace = True
+ if o == '-b': backup = a
+ for line in input(args, inplace=inplace, backup=backup):
+ if line[-1:] == '\n': line = line[:-1]
+ if line[-1:] == '\r': line = line[:-1]
+ print("%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
+ isfirstline() and "*" or "", line))
+ print("%d: %s[%d]" % (lineno(), filename(), filelineno()))
+
+if __name__ == '__main__':
+ _test()
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/fnmatch.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/fnmatch.py
new file mode 100644
index 0000000000000000000000000000000000000000..10e1c936688d8f84c87977ed592c4beaf88e4336
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/fnmatch.py
@@ -0,0 +1,209 @@
+"""Filename matching with shell patterns.
+
+fnmatch(FILENAME, PATTERN) matches according to the local convention.
+fnmatchcase(FILENAME, PATTERN) always takes case in account.
+
+The functions operate by translating the pattern into a regular
+expression. They cache the compiled regular expressions for speed.
+
+The function translate(PATTERN) returns a regular expression
+corresponding to PATTERN. (It does not compile it.)
+"""
+
+import functools
+import itertools
+import os
+import posixpath
+import re
+
+__all__ = ["filter", "filterfalse", "fnmatch", "fnmatchcase", "translate"]
+
+
+def fnmatch(name, pat):
+ """Test whether FILENAME matches PATTERN.
+
+ Patterns are Unix shell style:
+
+ * matches everything
+ ? matches any single character
+ [seq] matches any character in seq
+ [!seq] matches any char not in seq
+
+ An initial period in FILENAME is not special.
+ Both FILENAME and PATTERN are first case-normalized
+ if the operating system requires it.
+ If you don't want this, use fnmatchcase(FILENAME, PATTERN).
+ """
+ name = os.path.normcase(name)
+ pat = os.path.normcase(pat)
+ return fnmatchcase(name, pat)
+
+
+@functools.lru_cache(maxsize=32768, typed=True)
+def _compile_pattern(pat):
+ if isinstance(pat, bytes):
+ pat_str = str(pat, 'ISO-8859-1')
+ res_str = translate(pat_str)
+ res = bytes(res_str, 'ISO-8859-1')
+ else:
+ res = translate(pat)
+ return re.compile(res).match
+
+
+def filter(names, pat):
+ """Construct a list from those elements of the iterable NAMES that match PAT."""
+ result = []
+ pat = os.path.normcase(pat)
+ match = _compile_pattern(pat)
+ if os.path is posixpath:
+ # normcase on posix is NOP. Optimize it away from the loop.
+ for name in names:
+ if match(name):
+ result.append(name)
+ else:
+ for name in names:
+ if match(os.path.normcase(name)):
+ result.append(name)
+ return result
+
+
+def filterfalse(names, pat):
+ """Construct a list from those elements of the iterable NAMES that do not match PAT."""
+ pat = os.path.normcase(pat)
+ match = _compile_pattern(pat)
+ if os.path is posixpath:
+ # normcase on posix is NOP. Optimize it away from the loop.
+ return list(itertools.filterfalse(match, names))
+
+ result = []
+ for name in names:
+ if match(os.path.normcase(name)) is None:
+ result.append(name)
+ return result
+
+
+def fnmatchcase(name, pat):
+ """Test whether FILENAME matches PATTERN, including case.
+
+ This is a version of fnmatch() which doesn't case-normalize
+ its arguments.
+ """
+ match = _compile_pattern(pat)
+ return match(name) is not None
+
+
+def translate(pat):
+ """Translate a shell PATTERN to a regular expression.
+
+ There is no way to quote meta-characters.
+ """
+
+ parts, star_indices = _translate(pat, '*', '.')
+ return _join_translated_parts(parts, star_indices)
+
+
+_re_setops_sub = re.compile(r'([&~|])').sub
+_re_escape = functools.lru_cache(maxsize=512)(re.escape)
+
+
+def _translate(pat, star, question_mark):
+ res = []
+ add = res.append
+ star_indices = []
+
+ i, n = 0, len(pat)
+ while i < n:
+ c = pat[i]
+ i = i+1
+ if c == '*':
+ # store the position of the wildcard
+ star_indices.append(len(res))
+ add(star)
+ # compress consecutive `*` into one
+ while i < n and pat[i] == '*':
+ i += 1
+ elif c == '?':
+ add(question_mark)
+ elif c == '[':
+ j = i
+ if j < n and pat[j] == '!':
+ j = j+1
+ if j < n and pat[j] == ']':
+ j = j+1
+ while j < n and pat[j] != ']':
+ j = j+1
+ if j >= n:
+ add('\\[')
+ else:
+ stuff = pat[i:j]
+ if '-' not in stuff:
+ stuff = stuff.replace('\\', r'\\')
+ else:
+ chunks = []
+ k = i+2 if pat[i] == '!' else i+1
+ while True:
+ k = pat.find('-', k, j)
+ if k < 0:
+ break
+ chunks.append(pat[i:k])
+ i = k+1
+ k = k+3
+ chunk = pat[i:j]
+ if chunk:
+ chunks.append(chunk)
+ else:
+ chunks[-1] += '-'
+ # Remove empty ranges -- invalid in RE.
+ for k in range(len(chunks)-1, 0, -1):
+ if chunks[k-1][-1] > chunks[k][0]:
+ chunks[k-1] = chunks[k-1][:-1] + chunks[k][1:]
+ del chunks[k]
+ # Escape backslashes and hyphens for set difference (--).
+ # Hyphens that create ranges shouldn't be escaped.
+ stuff = '-'.join(s.replace('\\', r'\\').replace('-', r'\-')
+ for s in chunks)
+ i = j+1
+ if not stuff:
+ # Empty range: never match.
+ add('(?!)')
+ elif stuff == '!':
+ # Negated empty range: match any character.
+ add('.')
+ else:
+ # Escape set operations (&&, ~~ and ||).
+ stuff = _re_setops_sub(r'\\\1', stuff)
+ if stuff[0] == '!':
+ stuff = '^' + stuff[1:]
+ elif stuff[0] in ('^', '['):
+ stuff = '\\' + stuff
+ add(f'[{stuff}]')
+ else:
+ add(_re_escape(c))
+ assert i == n
+ return res, star_indices
+
+
+def _join_translated_parts(parts, star_indices):
+ if not star_indices:
+ return fr'(?s:{"".join(parts)})\z'
+ iter_star_indices = iter(star_indices)
+ j = next(iter_star_indices)
+ buffer = parts[:j] # fixed pieces at the start
+ append, extend = buffer.append, buffer.extend
+ i = j + 1
+ for j in iter_star_indices:
+ # Now deal with STAR fixed STAR fixed ...
+ # For an interior `STAR fixed` pairing, we want to do a minimal
+ # .*? match followed by `fixed`, with no possibility of backtracking.
+ # Atomic groups ("(?>...)") allow us to spell that directly.
+ # Note: people rely on the undocumented ability to join multiple
+ # translate() results together via "|" to build large regexps matching
+ # "one of many" shell patterns.
+ append('(?>.*?')
+ extend(parts[i:j])
+ append(')')
+ i = j + 1
+ append('.*')
+ extend(parts[i:])
+ res = ''.join(buffer)
+ return fr'(?s:{res})\z'
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/fractions.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/fractions.py
new file mode 100644
index 0000000000000000000000000000000000000000..a497ee19935345cd22d1f778c094328bf0888ec2
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/fractions.py
@@ -0,0 +1,1078 @@
+# Originally contributed by Sjoerd Mullender.
+# Significantly modified by Jeffrey Yasskin .
+
+"""Fraction, infinite-precision, rational numbers."""
+
+import functools
+import math
+import numbers
+import operator
+import re
+import sys
+
+__all__ = ['Fraction']
+
+
+# Constants related to the hash implementation; hash(x) is based
+# on the reduction of x modulo the prime _PyHASH_MODULUS.
+_PyHASH_MODULUS = sys.hash_info.modulus
+# Value to be used for rationals that reduce to infinity modulo
+# _PyHASH_MODULUS.
+_PyHASH_INF = sys.hash_info.inf
+
+@functools.lru_cache(maxsize = 1 << 14)
+def _hash_algorithm(numerator, denominator):
+
+ # To make sure that the hash of a Fraction agrees with the hash
+ # of a numerically equal integer, float or Decimal instance, we
+ # follow the rules for numeric hashes outlined in the
+ # documentation. (See library docs, 'Built-in Types').
+
+ try:
+ dinv = pow(denominator, -1, _PyHASH_MODULUS)
+ except ValueError:
+ # ValueError means there is no modular inverse.
+ hash_ = _PyHASH_INF
+ else:
+ # The general algorithm now specifies that the absolute value of
+ # the hash is
+ # (|N| * dinv) % P
+ # where N is self._numerator and P is _PyHASH_MODULUS. That's
+ # optimized here in two ways: first, for a non-negative int i,
+ # hash(i) == i % P, but the int hash implementation doesn't need
+ # to divide, and is faster than doing % P explicitly. So we do
+ # hash(|N| * dinv)
+ # instead. Second, N is unbounded, so its product with dinv may
+ # be arbitrarily expensive to compute. The final answer is the
+ # same if we use the bounded |N| % P instead, which can again
+ # be done with an int hash() call. If 0 <= i < P, hash(i) == i,
+ # so this nested hash() call wastes a bit of time making a
+ # redundant copy when |N| < P, but can save an arbitrarily large
+ # amount of computation for large |N|.
+ hash_ = hash(hash(abs(numerator)) * dinv)
+ result = hash_ if numerator >= 0 else -hash_
+ return -2 if result == -1 else result
+
+_RATIONAL_FORMAT = re.compile(r"""
+ \A\s* # optional whitespace at the start,
+ (?P[-+]?) # an optional sign, then
+ (?=\d|\.\d) # lookahead for digit or .digit
+ (?P\d*|\d+(_\d+)*) # numerator (possibly empty)
+ (?: # followed by
+ (?:\s*/\s*(?P\d+(_\d+)*))? # an optional denominator
+ | # or
+ (?:\.(?P\d*|\d+(_\d+)*))? # an optional fractional part
+ (?:E(?P[-+]?\d+(_\d+)*))? # and optional exponent
+ )
+ \s*\z # and optional whitespace to finish
+""", re.VERBOSE | re.IGNORECASE)
+
+
+# Helpers for formatting
+
+def _round_to_exponent(n, d, exponent, no_neg_zero=False):
+ """Round a rational number to the nearest multiple of a given power of 10.
+
+ Rounds the rational number n/d to the nearest integer multiple of
+ 10**exponent, rounding to the nearest even integer multiple in the case of
+ a tie. Returns a pair (sign: bool, significand: int) representing the
+ rounded value (-1)**sign * significand * 10**exponent.
+
+ If no_neg_zero is true, then the returned sign will always be False when
+ the significand is zero. Otherwise, the sign reflects the sign of the
+ input.
+
+ d must be positive, but n and d need not be relatively prime.
+ """
+ if exponent >= 0:
+ d *= 10**exponent
+ else:
+ n *= 10**-exponent
+
+ # The divmod quotient is correct for round-ties-towards-positive-infinity;
+ # In the case of a tie, we zero out the least significant bit of q.
+ q, r = divmod(n + (d >> 1), d)
+ if r == 0 and d & 1 == 0:
+ q &= -2
+
+ sign = q < 0 if no_neg_zero else n < 0
+ return sign, abs(q)
+
+
+def _round_to_figures(n, d, figures):
+ """Round a rational number to a given number of significant figures.
+
+ Rounds the rational number n/d to the given number of significant figures
+ using the round-ties-to-even rule, and returns a triple
+ (sign: bool, significand: int, exponent: int) representing the rounded
+ value (-1)**sign * significand * 10**exponent.
+
+ In the special case where n = 0, returns a significand of zero and
+ an exponent of 1 - figures, for compatibility with formatting.
+ Otherwise, the returned significand satisfies
+ 10**(figures - 1) <= significand < 10**figures.
+
+ d must be positive, but n and d need not be relatively prime.
+ figures must be positive.
+ """
+ # Special case for n == 0.
+ if n == 0:
+ return False, 0, 1 - figures
+
+ # Find integer m satisfying 10**(m - 1) <= abs(n)/d <= 10**m. (If abs(n)/d
+ # is a power of 10, either of the two possible values for m is fine.)
+ str_n, str_d = str(abs(n)), str(d)
+ m = len(str_n) - len(str_d) + (str_d <= str_n)
+
+ # Round to a multiple of 10**(m - figures). The significand we get
+ # satisfies 10**(figures - 1) <= significand <= 10**figures.
+ exponent = m - figures
+ sign, significand = _round_to_exponent(n, d, exponent)
+
+ # Adjust in the case where significand == 10**figures, to ensure that
+ # 10**(figures - 1) <= significand < 10**figures.
+ if len(str(significand)) == figures + 1:
+ significand //= 10
+ exponent += 1
+
+ return sign, significand, exponent
+
+
+# Pattern for matching non-float-style format specifications.
+_GENERAL_FORMAT_SPECIFICATION_MATCHER = re.compile(r"""
+ (?:
+ (?P.)?
+ (?P[<>=^])
+ )?
+ (?P[-+ ]?)
+ # Alt flag forces a slash and denominator in the output, even for
+ # integer-valued Fraction objects.
+ (?P\#)?
+ # We don't implement the zeropad flag since there's no single obvious way
+ # to interpret it.
+ (?P0|[1-9][0-9]*)?
+ (?P[,_])?
+""", re.DOTALL | re.VERBOSE).fullmatch
+
+
+# Pattern for matching float-style format specifications;
+# supports 'e', 'E', 'f', 'F', 'g', 'G' and '%' presentation types.
+_FLOAT_FORMAT_SPECIFICATION_MATCHER = re.compile(r"""
+ (?:
+ (?P.)?
+ (?P[<>=^])
+ )?
+ (?P[-+ ]?)
+ (?Pz)?
+ (?P\#)?
+ # A '0' that's *not* followed by another digit is parsed as a minimum width
+ # rather than a zeropad flag.
+ (?P0(?=[0-9]))?
+ (?P[0-9]+)?
+ (?P[,_])?
+ (?:\.
+ (?=[,_0-9]) # lookahead for digit or separator
+ (?P[0-9]+)?
+ (?P[,_])?
+ )?
+ (?P[eEfFgG%])
+""", re.DOTALL | re.VERBOSE).fullmatch
+
+
+class Fraction(numbers.Rational):
+ """This class implements rational numbers.
+
+ In the two-argument form of the constructor, Fraction(8, 6) will
+ produce a rational number equivalent to 4/3. Both arguments must
+ be Rational. The numerator defaults to 0 and the denominator
+ defaults to 1 so that Fraction(3) == 3 and Fraction() == 0.
+
+ Fractions can also be constructed from:
+
+ - numeric strings similar to those accepted by the
+ float constructor (for example, '-2.3' or '1e10')
+
+ - strings of the form '123/456'
+
+ - float and Decimal instances
+
+ - other Rational instances (including integers)
+
+ """
+
+ __slots__ = ('_numerator', '_denominator')
+
+ # We're immutable, so use __new__ not __init__
+ def __new__(cls, numerator=0, denominator=None):
+ """Constructs a Rational.
+
+ Takes a string like '3/2' or '1.5', another Rational instance, a
+ numerator/denominator pair, or a float.
+
+ Examples
+ --------
+
+ >>> Fraction(10, -8)
+ Fraction(-5, 4)
+ >>> Fraction(Fraction(1, 7), 5)
+ Fraction(1, 35)
+ >>> Fraction(Fraction(1, 7), Fraction(2, 3))
+ Fraction(3, 14)
+ >>> Fraction('314')
+ Fraction(314, 1)
+ >>> Fraction('-35/4')
+ Fraction(-35, 4)
+ >>> Fraction('3.1415') # conversion from numeric string
+ Fraction(6283, 2000)
+ >>> Fraction('-47e-2') # string may include a decimal exponent
+ Fraction(-47, 100)
+ >>> Fraction(1.47) # direct construction from float (exact conversion)
+ Fraction(6620291452234629, 4503599627370496)
+ >>> Fraction(2.25)
+ Fraction(9, 4)
+ >>> Fraction(Decimal('1.47'))
+ Fraction(147, 100)
+
+ """
+ self = super(Fraction, cls).__new__(cls)
+
+ if denominator is None:
+ if type(numerator) is int:
+ self._numerator = numerator
+ self._denominator = 1
+ return self
+
+ elif isinstance(numerator, numbers.Rational):
+ self._numerator = numerator.numerator
+ self._denominator = numerator.denominator
+ return self
+
+ elif (isinstance(numerator, float) or
+ (not isinstance(numerator, type) and
+ hasattr(numerator, 'as_integer_ratio'))):
+ # Exact conversion
+ self._numerator, self._denominator = numerator.as_integer_ratio()
+ return self
+
+ elif isinstance(numerator, str):
+ # Handle construction from strings.
+ m = _RATIONAL_FORMAT.match(numerator)
+ if m is None:
+ raise ValueError('Invalid literal for Fraction: %r' %
+ numerator)
+ numerator = int(m.group('num') or '0')
+ denom = m.group('denom')
+ if denom:
+ denominator = int(denom)
+ else:
+ denominator = 1
+ decimal = m.group('decimal')
+ if decimal:
+ decimal = decimal.replace('_', '')
+ scale = 10**len(decimal)
+ numerator = numerator * scale + int(decimal)
+ denominator *= scale
+ exp = m.group('exp')
+ if exp:
+ exp = int(exp)
+ if exp >= 0:
+ numerator *= 10**exp
+ else:
+ denominator *= 10**-exp
+ if m.group('sign') == '-':
+ numerator = -numerator
+
+ else:
+ raise TypeError("argument should be a string or a Rational "
+ "instance or have the as_integer_ratio() method")
+
+ elif type(numerator) is int is type(denominator):
+ pass # *very* normal case
+
+ elif (isinstance(numerator, numbers.Rational) and
+ isinstance(denominator, numbers.Rational)):
+ numerator, denominator = (
+ numerator.numerator * denominator.denominator,
+ denominator.numerator * numerator.denominator
+ )
+ else:
+ raise TypeError("both arguments should be "
+ "Rational instances")
+
+ if denominator == 0:
+ raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
+ g = math.gcd(numerator, denominator)
+ if denominator < 0:
+ g = -g
+ numerator //= g
+ denominator //= g
+ self._numerator = numerator
+ self._denominator = denominator
+ return self
+
+ @classmethod
+ def from_number(cls, number):
+ """Converts a finite real number to a rational number, exactly.
+
+ Beware that Fraction.from_number(0.3) != Fraction(3, 10).
+
+ """
+ if type(number) is int:
+ return cls._from_coprime_ints(number, 1)
+
+ elif isinstance(number, numbers.Rational):
+ return cls._from_coprime_ints(number.numerator, number.denominator)
+
+ elif (isinstance(number, float) or
+ (not isinstance(number, type) and
+ hasattr(number, 'as_integer_ratio'))):
+ return cls._from_coprime_ints(*number.as_integer_ratio())
+
+ else:
+ raise TypeError("argument should be a Rational instance or "
+ "have the as_integer_ratio() method")
+
+ @classmethod
+ def from_float(cls, f):
+ """Converts a finite float to a rational number, exactly.
+
+ Beware that Fraction.from_float(0.3) != Fraction(3, 10).
+
+ """
+ if isinstance(f, numbers.Integral):
+ return cls(f)
+ elif not isinstance(f, float):
+ raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
+ (cls.__name__, f, type(f).__name__))
+ return cls._from_coprime_ints(*f.as_integer_ratio())
+
+ @classmethod
+ def from_decimal(cls, dec):
+ """Converts a finite Decimal instance to a rational number, exactly."""
+ from decimal import Decimal
+ if isinstance(dec, numbers.Integral):
+ dec = Decimal(int(dec))
+ elif not isinstance(dec, Decimal):
+ raise TypeError(
+ "%s.from_decimal() only takes Decimals, not %r (%s)" %
+ (cls.__name__, dec, type(dec).__name__))
+ return cls._from_coprime_ints(*dec.as_integer_ratio())
+
+ @classmethod
+ def _from_coprime_ints(cls, numerator, denominator, /):
+ """Convert a pair of ints to a rational number, for internal use.
+
+ The ratio of integers should be in lowest terms and the denominator
+ should be positive.
+ """
+ obj = super(Fraction, cls).__new__(cls)
+ obj._numerator = numerator
+ obj._denominator = denominator
+ return obj
+
+ def is_integer(self):
+ """Return True if the Fraction is an integer."""
+ return self._denominator == 1
+
+ def as_integer_ratio(self):
+ """Return a pair of integers, whose ratio is equal to the original Fraction.
+
+ The ratio is in lowest terms and has a positive denominator.
+ """
+ return (self._numerator, self._denominator)
+
+ def limit_denominator(self, max_denominator=1000000):
+ """Closest Fraction to self with denominator at most max_denominator.
+
+ >>> Fraction('3.141592653589793').limit_denominator(10)
+ Fraction(22, 7)
+ >>> Fraction('3.141592653589793').limit_denominator(100)
+ Fraction(311, 99)
+ >>> Fraction(4321, 8765).limit_denominator(10000)
+ Fraction(4321, 8765)
+
+ """
+ # Algorithm notes: For any real number x, define a *best upper
+ # approximation* to x to be a rational number p/q such that:
+ #
+ # (1) p/q >= x, and
+ # (2) if p/q > r/s >= x then s > q, for any rational r/s.
+ #
+ # Define *best lower approximation* similarly. Then it can be
+ # proved that a rational number is a best upper or lower
+ # approximation to x if, and only if, it is a convergent or
+ # semiconvergent of the (unique shortest) continued fraction
+ # associated to x.
+ #
+ # To find a best rational approximation with denominator <= M,
+ # we find the best upper and lower approximations with
+ # denominator <= M and take whichever of these is closer to x.
+ # In the event of a tie, the bound with smaller denominator is
+ # chosen. If both denominators are equal (which can happen
+ # only when max_denominator == 1 and self is midway between
+ # two integers) the lower bound---i.e., the floor of self, is
+ # taken.
+
+ if max_denominator < 1:
+ raise ValueError("max_denominator should be at least 1")
+ if self._denominator <= max_denominator:
+ return Fraction(self)
+
+ p0, q0, p1, q1 = 0, 1, 1, 0
+ n, d = self._numerator, self._denominator
+ while True:
+ a = n//d
+ q2 = q0+a*q1
+ if q2 > max_denominator:
+ break
+ p0, q0, p1, q1 = p1, q1, p0+a*p1, q2
+ n, d = d, n-a*d
+ k = (max_denominator-q0)//q1
+
+ # Determine which of the candidates (p0+k*p1)/(q0+k*q1) and p1/q1 is
+ # closer to self. The distance between them is 1/(q1*(q0+k*q1)), while
+ # the distance from p1/q1 to self is d/(q1*self._denominator). So we
+ # need to compare 2*(q0+k*q1) with self._denominator/d.
+ if 2*d*(q0+k*q1) <= self._denominator:
+ return Fraction._from_coprime_ints(p1, q1)
+ else:
+ return Fraction._from_coprime_ints(p0+k*p1, q0+k*q1)
+
+ @property
+ def numerator(a):
+ return a._numerator
+
+ @property
+ def denominator(a):
+ return a._denominator
+
+ def __repr__(self):
+ """repr(self)"""
+ return '%s(%s, %s)' % (self.__class__.__name__,
+ self._numerator, self._denominator)
+
+ def __str__(self):
+ """str(self)"""
+ if self._denominator == 1:
+ return str(self._numerator)
+ else:
+ return '%s/%s' % (self._numerator, self._denominator)
+
+ def _format_general(self, match):
+ """Helper method for __format__.
+
+ Handles fill, alignment, signs, and thousands separators in the
+ case of no presentation type.
+ """
+ # Validate and parse the format specifier.
+ fill = match["fill"] or " "
+ align = match["align"] or ">"
+ pos_sign = "" if match["sign"] == "-" else match["sign"]
+ alternate_form = bool(match["alt"])
+ minimumwidth = int(match["minimumwidth"] or "0")
+ thousands_sep = match["thousands_sep"] or ''
+
+ # Determine the body and sign representation.
+ n, d = self._numerator, self._denominator
+ if d > 1 or alternate_form:
+ body = f"{abs(n):{thousands_sep}}/{d:{thousands_sep}}"
+ else:
+ body = f"{abs(n):{thousands_sep}}"
+ sign = '-' if n < 0 else pos_sign
+
+ # Pad with fill character if necessary and return.
+ padding = fill * (minimumwidth - len(sign) - len(body))
+ if align == ">":
+ return padding + sign + body
+ elif align == "<":
+ return sign + body + padding
+ elif align == "^":
+ half = len(padding) // 2
+ return padding[:half] + sign + body + padding[half:]
+ else: # align == "="
+ return sign + padding + body
+
+ def _format_float_style(self, match):
+ """Helper method for __format__; handles float presentation types."""
+ fill = match["fill"] or " "
+ align = match["align"] or ">"
+ pos_sign = "" if match["sign"] == "-" else match["sign"]
+ no_neg_zero = bool(match["no_neg_zero"])
+ alternate_form = bool(match["alt"])
+ zeropad = bool(match["zeropad"])
+ minimumwidth = int(match["minimumwidth"] or "0")
+ thousands_sep = match["thousands_sep"]
+ precision = int(match["precision"] or "6")
+ frac_sep = match["frac_separators"] or ""
+ presentation_type = match["presentation_type"]
+ trim_zeros = presentation_type in "gG" and not alternate_form
+ trim_point = not alternate_form
+ exponent_indicator = "E" if presentation_type in "EFG" else "e"
+
+ if align == '=' and fill == '0':
+ zeropad = True
+
+ # Round to get the digits we need, figure out where to place the point,
+ # and decide whether to use scientific notation. 'point_pos' is the
+ # relative to the _end_ of the digit string: that is, it's the number
+ # of digits that should follow the point.
+ if presentation_type in "fF%":
+ exponent = -precision
+ if presentation_type == "%":
+ exponent -= 2
+ negative, significand = _round_to_exponent(
+ self._numerator, self._denominator, exponent, no_neg_zero)
+ scientific = False
+ point_pos = precision
+ else: # presentation_type in "eEgG"
+ figures = (
+ max(precision, 1)
+ if presentation_type in "gG"
+ else precision + 1
+ )
+ negative, significand, exponent = _round_to_figures(
+ self._numerator, self._denominator, figures)
+ scientific = (
+ presentation_type in "eE"
+ or exponent > 0
+ or exponent + figures <= -4
+ )
+ point_pos = figures - 1 if scientific else -exponent
+
+ # Get the suffix - the part following the digits, if any.
+ if presentation_type == "%":
+ suffix = "%"
+ elif scientific:
+ suffix = f"{exponent_indicator}{exponent + point_pos:+03d}"
+ else:
+ suffix = ""
+
+ # String of output digits, padded sufficiently with zeros on the left
+ # so that we'll have at least one digit before the decimal point.
+ digits = f"{significand:0{point_pos + 1}d}"
+
+ # Before padding, the output has the form f"{sign}{leading}{trailing}",
+ # where `leading` includes thousands separators if necessary and
+ # `trailing` includes the decimal separator where appropriate.
+ sign = "-" if negative else pos_sign
+ leading = digits[: len(digits) - point_pos]
+ frac_part = digits[len(digits) - point_pos :]
+ if trim_zeros:
+ frac_part = frac_part.rstrip("0")
+ separator = "" if trim_point and not frac_part else "."
+ if frac_sep:
+ frac_part = frac_sep.join(frac_part[pos:pos + 3]
+ for pos in range(0, len(frac_part), 3))
+ trailing = separator + frac_part + suffix
+
+ # Do zero padding if required.
+ if zeropad:
+ min_leading = minimumwidth - len(sign) - len(trailing)
+ # When adding thousands separators, they'll be added to the
+ # zero-padded portion too, so we need to compensate.
+ leading = leading.zfill(
+ 3 * min_leading // 4 + 1 if thousands_sep else min_leading
+ )
+
+ # Insert thousands separators if required.
+ if thousands_sep:
+ first_pos = 1 + (len(leading) - 1) % 3
+ leading = leading[:first_pos] + "".join(
+ thousands_sep + leading[pos : pos + 3]
+ for pos in range(first_pos, len(leading), 3)
+ )
+
+ # We now have a sign and a body. Pad with fill character if necessary
+ # and return.
+ body = leading + trailing
+ padding = fill * (minimumwidth - len(sign) - len(body))
+ if align == ">":
+ return padding + sign + body
+ elif align == "<":
+ return sign + body + padding
+ elif align == "^":
+ half = len(padding) // 2
+ return padding[:half] + sign + body + padding[half:]
+ else: # align == "="
+ return sign + padding + body
+
+ def __format__(self, format_spec, /):
+ """Format this fraction according to the given format specification."""
+
+ if match := _GENERAL_FORMAT_SPECIFICATION_MATCHER(format_spec):
+ return self._format_general(match)
+
+ if match := _FLOAT_FORMAT_SPECIFICATION_MATCHER(format_spec):
+ # Refuse the temptation to guess if both alignment _and_
+ # zero padding are specified.
+ if match["align"] is None or match["zeropad"] is None:
+ return self._format_float_style(match)
+
+ raise ValueError(
+ f"Invalid format specifier {format_spec!r} "
+ f"for object of type {type(self).__name__!r}"
+ )
+
+ def _operator_fallbacks(monomorphic_operator, fallback_operator,
+ handle_complex=True):
+ """Generates forward and reverse operators given a purely-rational
+ operator and a function from the operator module.
+
+ Use this like:
+ __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
+
+ In general, we want to implement the arithmetic operations so
+ that mixed-mode operations either call an implementation whose
+ author knew about the types of both arguments, or convert both
+ to the nearest built in type and do the operation there. In
+ Fraction, that means that we define __add__ and __radd__ as:
+
+ def __add__(self, other):
+ # Both types have numerators/denominator attributes,
+ # so do the operation directly
+ if isinstance(other, (int, Fraction)):
+ return Fraction(self.numerator * other.denominator +
+ other.numerator * self.denominator,
+ self.denominator * other.denominator)
+ # float and complex don't have those operations, but we
+ # know about those types, so special case them.
+ elif isinstance(other, float):
+ return float(self) + other
+ elif isinstance(other, complex):
+ return complex(self) + other
+ # Let the other type take over.
+ return NotImplemented
+
+ def __radd__(self, other):
+ # radd handles more types than add because there's
+ # nothing left to fall back to.
+ if isinstance(other, numbers.Rational):
+ return Fraction(self.numerator * other.denominator +
+ other.numerator * self.denominator,
+ self.denominator * other.denominator)
+ elif isinstance(other, Real):
+ return float(other) + float(self)
+ elif isinstance(other, Complex):
+ return complex(other) + complex(self)
+ return NotImplemented
+
+
+ There are 5 different cases for a mixed-type addition on
+ Fraction. I'll refer to all of the above code that doesn't
+ refer to Fraction, float, or complex as "boilerplate". 'r'
+ will be an instance of Fraction, which is a subtype of
+ Rational (r : Fraction <: Rational), and b : B <:
+ Complex. The first three involve 'r + b':
+
+ 1. If B <: Fraction, int, float, or complex, we handle
+ that specially, and all is well.
+ 2. If Fraction falls back to the boilerplate code, and it
+ were to return a value from __add__, we'd miss the
+ possibility that B defines a more intelligent __radd__,
+ so the boilerplate should return NotImplemented from
+ __add__. In particular, we don't handle Rational
+ here, even though we could get an exact answer, in case
+ the other type wants to do something special.
+ 3. If B <: Fraction, Python tries B.__radd__ before
+ Fraction.__add__. This is ok, because it was
+ implemented with knowledge of Fraction, so it can
+ handle those instances before delegating to Real or
+ Complex.
+
+ The next two situations describe 'b + r'. We assume that b
+ didn't know about Fraction in its implementation, and that it
+ uses similar boilerplate code:
+
+ 4. If B <: Rational, then __radd_ converts both to the
+ builtin rational type (hey look, that's us) and
+ proceeds.
+ 5. Otherwise, __radd__ tries to find the nearest common
+ base ABC, and fall back to its builtin type. Since this
+ class doesn't subclass a concrete type, there's no
+ implementation to fall back to, so we need to try as
+ hard as possible to return an actual value, or the user
+ will get a TypeError.
+
+ """
+ def forward(a, b):
+ if isinstance(b, Fraction):
+ return monomorphic_operator(a, b)
+ elif isinstance(b, int):
+ return monomorphic_operator(a, Fraction(b))
+ elif isinstance(b, float):
+ return fallback_operator(float(a), b)
+ elif handle_complex and isinstance(b, complex):
+ return fallback_operator(float(a), b)
+ else:
+ return NotImplemented
+ forward.__name__ = '__' + fallback_operator.__name__ + '__'
+ forward.__doc__ = monomorphic_operator.__doc__
+
+ def reverse(b, a):
+ if isinstance(a, numbers.Rational):
+ # Includes ints.
+ return monomorphic_operator(Fraction(a), b)
+ elif isinstance(a, numbers.Real):
+ return fallback_operator(float(a), float(b))
+ elif handle_complex and isinstance(a, numbers.Complex):
+ return fallback_operator(complex(a), float(b))
+ else:
+ return NotImplemented
+ reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
+ reverse.__doc__ = monomorphic_operator.__doc__
+
+ return forward, reverse
+
+ # Rational arithmetic algorithms: Knuth, TAOCP, Volume 2, 4.5.1.
+ #
+ # Assume input fractions a and b are normalized.
+ #
+ # 1) Consider addition/subtraction.
+ #
+ # Let g = gcd(da, db). Then
+ #
+ # na nb na*db ± nb*da
+ # a ± b == -- ± -- == ------------- ==
+ # da db da*db
+ #
+ # na*(db//g) ± nb*(da//g) t
+ # == ----------------------- == -
+ # (da*db)//g d
+ #
+ # Now, if g > 1, we're working with smaller integers.
+ #
+ # Note, that t, (da//g) and (db//g) are pairwise coprime.
+ #
+ # Indeed, (da//g) and (db//g) share no common factors (they were
+ # removed) and da is coprime with na (since input fractions are
+ # normalized), hence (da//g) and na are coprime. By symmetry,
+ # (db//g) and nb are coprime too. Then,
+ #
+ # gcd(t, da//g) == gcd(na*(db//g), da//g) == 1
+ # gcd(t, db//g) == gcd(nb*(da//g), db//g) == 1
+ #
+ # Above allows us optimize reduction of the result to lowest
+ # terms. Indeed,
+ #
+ # g2 = gcd(t, d) == gcd(t, (da//g)*(db//g)*g) == gcd(t, g)
+ #
+ # t//g2 t//g2
+ # a ± b == ----------------------- == ----------------
+ # (da//g)*(db//g)*(g//g2) (da//g)*(db//g2)
+ #
+ # is a normalized fraction. This is useful because the unnormalized
+ # denominator d could be much larger than g.
+ #
+ # We should special-case g == 1 (and g2 == 1), since 60.8% of
+ # randomly-chosen integers are coprime:
+ # https://en.wikipedia.org/wiki/Coprime_integers#Probability_of_coprimality
+ # Note, that g2 == 1 always for fractions, obtained from floats: here
+ # g is a power of 2 and the unnormalized numerator t is an odd integer.
+ #
+ # 2) Consider multiplication
+ #
+ # Let g1 = gcd(na, db) and g2 = gcd(nb, da), then
+ #
+ # na*nb na*nb (na//g1)*(nb//g2)
+ # a*b == ----- == ----- == -----------------
+ # da*db db*da (db//g1)*(da//g2)
+ #
+ # Note, that after divisions we're multiplying smaller integers.
+ #
+ # Also, the resulting fraction is normalized, because each of
+ # two factors in the numerator is coprime to each of the two factors
+ # in the denominator.
+ #
+ # Indeed, pick (na//g1). It's coprime with (da//g2), because input
+ # fractions are normalized. It's also coprime with (db//g1), because
+ # common factors are removed by g1 == gcd(na, db).
+ #
+ # As for addition/subtraction, we should special-case g1 == 1
+ # and g2 == 1 for same reason. That happens also for multiplying
+ # rationals, obtained from floats.
+
+ def _add(a, b):
+ """a + b"""
+ na, da = a._numerator, a._denominator
+ nb, db = b._numerator, b._denominator
+ g = math.gcd(da, db)
+ if g == 1:
+ return Fraction._from_coprime_ints(na * db + da * nb, da * db)
+ s = da // g
+ t = na * (db // g) + nb * s
+ g2 = math.gcd(t, g)
+ if g2 == 1:
+ return Fraction._from_coprime_ints(t, s * db)
+ return Fraction._from_coprime_ints(t // g2, s * (db // g2))
+
+ __add__, __radd__ = _operator_fallbacks(_add, operator.add)
+
+ def _sub(a, b):
+ """a - b"""
+ na, da = a._numerator, a._denominator
+ nb, db = b._numerator, b._denominator
+ g = math.gcd(da, db)
+ if g == 1:
+ return Fraction._from_coprime_ints(na * db - da * nb, da * db)
+ s = da // g
+ t = na * (db // g) - nb * s
+ g2 = math.gcd(t, g)
+ if g2 == 1:
+ return Fraction._from_coprime_ints(t, s * db)
+ return Fraction._from_coprime_ints(t // g2, s * (db // g2))
+
+ __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
+
+ def _mul(a, b):
+ """a * b"""
+ na, da = a._numerator, a._denominator
+ nb, db = b._numerator, b._denominator
+ g1 = math.gcd(na, db)
+ if g1 > 1:
+ na //= g1
+ db //= g1
+ g2 = math.gcd(nb, da)
+ if g2 > 1:
+ nb //= g2
+ da //= g2
+ return Fraction._from_coprime_ints(na * nb, db * da)
+
+ __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
+
+ def _div(a, b):
+ """a / b"""
+ # Same as _mul(), with inversed b.
+ nb, db = b._numerator, b._denominator
+ if nb == 0:
+ raise ZeroDivisionError('Fraction(%s, 0)' % db)
+ na, da = a._numerator, a._denominator
+ g1 = math.gcd(na, nb)
+ if g1 > 1:
+ na //= g1
+ nb //= g1
+ g2 = math.gcd(db, da)
+ if g2 > 1:
+ da //= g2
+ db //= g2
+ n, d = na * db, nb * da
+ if d < 0:
+ n, d = -n, -d
+ return Fraction._from_coprime_ints(n, d)
+
+ __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
+
+ def _floordiv(a, b):
+ """a // b"""
+ return (a.numerator * b.denominator) // (a.denominator * b.numerator)
+
+ __floordiv__, __rfloordiv__ = _operator_fallbacks(_floordiv, operator.floordiv, False)
+
+ def _divmod(a, b):
+ """(a // b, a % b)"""
+ da, db = a.denominator, b.denominator
+ div, n_mod = divmod(a.numerator * db, da * b.numerator)
+ return div, Fraction(n_mod, da * db)
+
+ __divmod__, __rdivmod__ = _operator_fallbacks(_divmod, divmod, False)
+
+ def _mod(a, b):
+ """a % b"""
+ da, db = a.denominator, b.denominator
+ return Fraction((a.numerator * db) % (b.numerator * da), da * db)
+
+ __mod__, __rmod__ = _operator_fallbacks(_mod, operator.mod, False)
+
+ def __pow__(a, b, modulo=None):
+ """a ** b
+
+ If b is not an integer, the result will be a float or complex
+ since roots are generally irrational. If b is an integer, the
+ result will be rational.
+
+ """
+ if modulo is not None:
+ return NotImplemented
+ if isinstance(b, numbers.Rational):
+ if b.denominator == 1:
+ power = b.numerator
+ if power >= 0:
+ return Fraction._from_coprime_ints(a._numerator ** power,
+ a._denominator ** power)
+ elif a._numerator > 0:
+ return Fraction._from_coprime_ints(a._denominator ** -power,
+ a._numerator ** -power)
+ elif a._numerator == 0:
+ raise ZeroDivisionError('Fraction(%s, 0)' %
+ a._denominator ** -power)
+ else:
+ return Fraction._from_coprime_ints((-a._denominator) ** -power,
+ (-a._numerator) ** -power)
+ else:
+ # A fractional power will generally produce an
+ # irrational number.
+ return float(a) ** float(b)
+ elif isinstance(b, (float, complex)):
+ return float(a) ** b
+ else:
+ return NotImplemented
+
+ def __rpow__(b, a, modulo=None):
+ """a ** b"""
+ if modulo is not None:
+ return NotImplemented
+ if b._denominator == 1 and b._numerator >= 0:
+ # If a is an int, keep it that way if possible.
+ return a ** b._numerator
+
+ if isinstance(a, numbers.Rational):
+ return Fraction(a.numerator, a.denominator) ** b
+
+ if b._denominator == 1:
+ return a ** b._numerator
+
+ return a ** float(b)
+
+ def __pos__(a):
+ """+a: Coerces a subclass instance to Fraction"""
+ return Fraction._from_coprime_ints(a._numerator, a._denominator)
+
+ def __neg__(a):
+ """-a"""
+ return Fraction._from_coprime_ints(-a._numerator, a._denominator)
+
+ def __abs__(a):
+ """abs(a)"""
+ return Fraction._from_coprime_ints(abs(a._numerator), a._denominator)
+
+ def __int__(a, _index=operator.index):
+ """int(a)"""
+ if a._numerator < 0:
+ return _index(-(-a._numerator // a._denominator))
+ else:
+ return _index(a._numerator // a._denominator)
+
+ def __trunc__(a):
+ """math.trunc(a)"""
+ if a._numerator < 0:
+ return -(-a._numerator // a._denominator)
+ else:
+ return a._numerator // a._denominator
+
+ def __floor__(a):
+ """math.floor(a)"""
+ return a._numerator // a._denominator
+
+ def __ceil__(a):
+ """math.ceil(a)"""
+ # The negations cleverly convince floordiv to return the ceiling.
+ return -(-a._numerator // a._denominator)
+
+ def __round__(self, ndigits=None):
+ """round(self, ndigits)
+
+ Rounds half toward even.
+ """
+ if ndigits is None:
+ d = self._denominator
+ floor, remainder = divmod(self._numerator, d)
+ if remainder * 2 < d:
+ return floor
+ elif remainder * 2 > d:
+ return floor + 1
+ # Deal with the half case:
+ elif floor % 2 == 0:
+ return floor
+ else:
+ return floor + 1
+ shift = 10**abs(ndigits)
+ # See _operator_fallbacks.forward to check that the results of
+ # these operations will always be Fraction and therefore have
+ # round().
+ if ndigits > 0:
+ return Fraction(round(self * shift), shift)
+ else:
+ return Fraction(round(self / shift) * shift)
+
+ def __hash__(self):
+ """hash(self)"""
+ return _hash_algorithm(self._numerator, self._denominator)
+
+ def __eq__(a, b):
+ """a == b"""
+ if type(b) is int:
+ return a._numerator == b and a._denominator == 1
+ if isinstance(b, numbers.Rational):
+ return (a._numerator == b.numerator and
+ a._denominator == b.denominator)
+ if isinstance(b, numbers.Complex) and b.imag == 0:
+ b = b.real
+ if isinstance(b, float):
+ if math.isnan(b) or math.isinf(b):
+ # comparisons with an infinity or nan should behave in
+ # the same way for any finite a, so treat a as zero.
+ return 0.0 == b
+ else:
+ return a == a.from_float(b)
+ else:
+ # Since a doesn't know how to compare with b, let's give b
+ # a chance to compare itself with a.
+ return NotImplemented
+
+ def _richcmp(self, other, op):
+ """Helper for comparison operators, for internal use only.
+
+ Implement comparison between a Rational instance `self`, and
+ either another Rational instance or a float `other`. If
+ `other` is not a Rational instance or a float, return
+ NotImplemented. `op` should be one of the six standard
+ comparison operators.
+
+ """
+ # convert other to a Rational instance where reasonable.
+ if isinstance(other, numbers.Rational):
+ return op(self._numerator * other.denominator,
+ self._denominator * other.numerator)
+ if isinstance(other, float):
+ if math.isnan(other) or math.isinf(other):
+ return op(0.0, other)
+ else:
+ return op(self, self.from_float(other))
+ else:
+ return NotImplemented
+
+ def __lt__(a, b):
+ """a < b"""
+ return a._richcmp(b, operator.lt)
+
+ def __gt__(a, b):
+ """a > b"""
+ return a._richcmp(b, operator.gt)
+
+ def __le__(a, b):
+ """a <= b"""
+ return a._richcmp(b, operator.le)
+
+ def __ge__(a, b):
+ """a >= b"""
+ return a._richcmp(b, operator.ge)
+
+ def __bool__(a):
+ """a != 0"""
+ # bpo-39274: Use bool() because (a._numerator != 0) can return an
+ # object which is not a bool.
+ return bool(a._numerator)
+
+ # support for pickling, copy, and deepcopy
+
+ def __reduce__(self):
+ return (self.__class__, (self._numerator, self._denominator))
+
+ def __copy__(self):
+ if type(self) == Fraction:
+ return self # I'm immutable; therefore I am my own clone
+ return self.__class__(self._numerator, self._denominator)
+
+ def __deepcopy__(self, memo):
+ if type(self) == Fraction:
+ return self # My components are also immutable
+ return self.__class__(self._numerator, self._denominator)
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/ftplib.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/ftplib.py
new file mode 100644
index 0000000000000000000000000000000000000000..50771e8c17c2503a49e741dad5e550d27d91be9c
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/ftplib.py
@@ -0,0 +1,966 @@
+"""An FTP client class and some helper functions.
+
+Based on RFC 959: File Transfer Protocol (FTP), by J. Postel and J. Reynolds
+
+Example:
+
+>>> from ftplib import FTP
+>>> ftp = FTP('ftp.python.org') # connect to host, default port
+>>> ftp.login() # default, i.e.: user anonymous, passwd anonymous@
+'230 Guest login ok, access restrictions apply.'
+>>> ftp.retrlines('LIST') # list directory contents
+total 9
+drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .
+drwxr-xr-x 8 root wheel 1024 Jan 3 1994 ..
+drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin
+drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc
+d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming
+drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib
+drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub
+drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr
+-rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg
+'226 Transfer complete.'
+>>> ftp.quit()
+'221 Goodbye.'
+>>>
+
+A nice test that reveals some of the network dialogue would be:
+python ftplib.py -d localhost -l -p -l
+"""
+
+#
+# Changes and improvements suggested by Steve Majewski.
+# Modified by Jack to work on the mac.
+# Modified by Siebren to support docstrings and PASV.
+# Modified by Phil Schwartz to add storbinary and storlines callbacks.
+# Modified by Giampaolo Rodola' to add TLS support.
+#
+
+import sys
+import socket
+from socket import _GLOBAL_DEFAULT_TIMEOUT
+
+__all__ = ["FTP", "error_reply", "error_temp", "error_perm", "error_proto",
+ "all_errors"]
+
+# Magic number from
+MSG_OOB = 0x1 # Process data out of band
+
+
+# The standard FTP server control port
+FTP_PORT = 21
+# The sizehint parameter passed to readline() calls
+MAXLINE = 8192
+
+
+# Exception raised when an error or invalid response is received
+class Error(Exception): pass
+class error_reply(Error): pass # unexpected [123]xx reply
+class error_temp(Error): pass # 4xx errors
+class error_perm(Error): pass # 5xx errors
+class error_proto(Error): pass # response does not begin with [1-5]
+
+
+# All exceptions (hopefully) that may be raised here and that aren't
+# (always) programming errors on our side
+all_errors = (Error, OSError, EOFError)
+
+
+# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
+CRLF = '\r\n'
+B_CRLF = b'\r\n'
+
+# The class itself
+class FTP:
+ '''An FTP client class.
+
+ To create a connection, call the class using these arguments:
+ host, user, passwd, acct, timeout, source_address, encoding
+
+ The first four arguments are all strings, and have default value ''.
+ The parameter ´timeout´ must be numeric and defaults to None if not
+ passed, meaning that no timeout will be set on any ftp socket(s).
+ If a timeout is passed, then this is now the default timeout for all ftp
+ socket operations for this instance.
+ The last parameter is the encoding of filenames, which defaults to utf-8.
+
+ Then use self.connect() with optional host and port argument.
+
+ To download a file, use ftp.retrlines('RETR ' + filename),
+ or ftp.retrbinary() with slightly different arguments.
+ To upload a file, use ftp.storlines() or ftp.storbinary(),
+ which have an open file as argument (see their definitions
+ below for details).
+ The download/upload functions first issue appropriate TYPE
+ and PORT or PASV commands.
+ '''
+
+ debugging = 0
+ host = ''
+ port = FTP_PORT
+ maxline = MAXLINE
+ sock = None
+ file = None
+ welcome = None
+ passiveserver = True
+ # Disables https://bugs.python.org/issue43285 security if set to True.
+ trust_server_pasv_ipv4_address = False
+
+ def __init__(self, host='', user='', passwd='', acct='',
+ timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None, *,
+ encoding='utf-8'):
+ """Initialization method (called by class instantiation).
+ Initialize host to localhost, port to standard ftp port.
+ Optional arguments are host (for connect()),
+ and user, passwd, acct (for login()).
+ """
+ self.encoding = encoding
+ self.source_address = source_address
+ self.timeout = timeout
+ if host:
+ self.connect(host)
+ if user:
+ self.login(user, passwd, acct)
+
+ def __enter__(self):
+ return self
+
+ # Context management protocol: try to quit() if active
+ def __exit__(self, *args):
+ if self.sock is not None:
+ try:
+ self.quit()
+ except (OSError, EOFError):
+ pass
+ finally:
+ if self.sock is not None:
+ self.close()
+
+ def connect(self, host='', port=0, timeout=-999, source_address=None):
+ '''Connect to host. Arguments are:
+ - host: hostname to connect to (string, default previous host)
+ - port: port to connect to (integer, default previous port)
+ - timeout: the timeout to set against the ftp socket(s)
+ - source_address: a 2-tuple (host, port) for the socket to bind
+ to as its source address before connecting.
+ '''
+ if host != '':
+ self.host = host
+ if port > 0:
+ self.port = port
+ if timeout != -999:
+ self.timeout = timeout
+ if self.timeout is not None and not self.timeout:
+ raise ValueError('Non-blocking socket (timeout=0) is not supported')
+ if source_address is not None:
+ self.source_address = source_address
+ sys.audit("ftplib.connect", self, self.host, self.port)
+ self.sock = socket.create_connection((self.host, self.port), self.timeout,
+ source_address=self.source_address)
+ self.af = self.sock.family
+ self.file = self.sock.makefile('r', encoding=self.encoding)
+ self.welcome = self.getresp()
+ return self.welcome
+
+ def getwelcome(self):
+ '''Get the welcome message from the server.
+ (this is read and squirreled away by connect())'''
+ if self.debugging:
+ print('*welcome*', self.sanitize(self.welcome))
+ return self.welcome
+
+ def set_debuglevel(self, level):
+ '''Set the debugging level.
+ The required argument level means:
+ 0: no debugging output (default)
+ 1: print commands and responses but not body text etc.
+ 2: also print raw lines read and sent before stripping CR/LF'''
+ self.debugging = level
+ debug = set_debuglevel
+
+ def set_pasv(self, val):
+ '''Use passive or active mode for data transfers.
+ With a false argument, use the normal PORT mode,
+ With a true argument, use the PASV command.'''
+ self.passiveserver = val
+
+ # Internal: "sanitize" a string for printing
+ def sanitize(self, s):
+ if s[:5] in {'pass ', 'PASS '}:
+ i = len(s.rstrip('\r\n'))
+ s = s[:5] + '*'*(i-5) + s[i:]
+ return repr(s)
+
+ # Internal: send one line to the server, appending CRLF
+ def putline(self, line):
+ if '\r' in line or '\n' in line:
+ raise ValueError('an illegal newline character should not be contained')
+ sys.audit("ftplib.sendcmd", self, line)
+ line = line + CRLF
+ if self.debugging > 1:
+ print('*put*', self.sanitize(line))
+ self.sock.sendall(line.encode(self.encoding))
+
+ # Internal: send one command to the server (through putline())
+ def putcmd(self, line):
+ if self.debugging: print('*cmd*', self.sanitize(line))
+ self.putline(line)
+
+ # Internal: return one line from the server, stripping CRLF.
+ # Raise EOFError if the connection is closed
+ def getline(self):
+ line = self.file.readline(self.maxline + 1)
+ if len(line) > self.maxline:
+ raise Error("got more than %d bytes" % self.maxline)
+ if self.debugging > 1:
+ print('*get*', self.sanitize(line))
+ if not line:
+ raise EOFError
+ if line[-2:] == CRLF:
+ line = line[:-2]
+ elif line[-1:] in CRLF:
+ line = line[:-1]
+ return line
+
+ # Internal: get a response from the server, which may possibly
+ # consist of multiple lines. Return a single string with no
+ # trailing CRLF. If the response consists of multiple lines,
+ # these are separated by '\n' characters in the string
+ def getmultiline(self):
+ line = self.getline()
+ if line[3:4] == '-':
+ code = line[:3]
+ while 1:
+ nextline = self.getline()
+ line = line + ('\n' + nextline)
+ if nextline[:3] == code and \
+ nextline[3:4] != '-':
+ break
+ return line
+
+ # Internal: get a response from the server.
+ # Raise various errors if the response indicates an error
+ def getresp(self):
+ resp = self.getmultiline()
+ if self.debugging:
+ print('*resp*', self.sanitize(resp))
+ self.lastresp = resp[:3]
+ c = resp[:1]
+ if c in {'1', '2', '3'}:
+ return resp
+ if c == '4':
+ raise error_temp(resp)
+ if c == '5':
+ raise error_perm(resp)
+ raise error_proto(resp)
+
+ def voidresp(self):
+ """Expect a response beginning with '2'."""
+ resp = self.getresp()
+ if resp[:1] != '2':
+ raise error_reply(resp)
+ return resp
+
+ def abort(self):
+ '''Abort a file transfer. Uses out-of-band data.
+ This does not follow the procedure from the RFC to send Telnet
+ IP and Synch; that doesn't seem to work with the servers I've
+ tried. Instead, just send the ABOR command as OOB data.'''
+ line = b'ABOR' + B_CRLF
+ if self.debugging > 1:
+ print('*put urgent*', self.sanitize(line))
+ self.sock.sendall(line, MSG_OOB)
+ resp = self.getmultiline()
+ if resp[:3] not in {'426', '225', '226'}:
+ raise error_proto(resp)
+ return resp
+
+ def sendcmd(self, cmd):
+ '''Send a command and return the response.'''
+ self.putcmd(cmd)
+ return self.getresp()
+
+ def voidcmd(self, cmd):
+ """Send a command and expect a response beginning with '2'."""
+ self.putcmd(cmd)
+ return self.voidresp()
+
+ def sendport(self, host, port):
+ '''Send a PORT command with the current host and the given
+ port number.
+ '''
+ hbytes = host.split('.')
+ pbytes = [repr(port//256), repr(port%256)]
+ bytes = hbytes + pbytes
+ cmd = 'PORT ' + ','.join(bytes)
+ return self.voidcmd(cmd)
+
+ def sendeprt(self, host, port):
+ '''Send an EPRT command with the current host and the given port number.'''
+ af = 0
+ if self.af == socket.AF_INET:
+ af = 1
+ if self.af == socket.AF_INET6:
+ af = 2
+ if af == 0:
+ raise error_proto('unsupported address family')
+ fields = ['', repr(af), host, repr(port), '']
+ cmd = 'EPRT ' + '|'.join(fields)
+ return self.voidcmd(cmd)
+
+ def makeport(self):
+ '''Create a new socket and send a PORT command for it.'''
+ sock = socket.create_server(("", 0), family=self.af, backlog=1)
+ port = sock.getsockname()[1] # Get proper port
+ host = self.sock.getsockname()[0] # Get proper host
+ if self.af == socket.AF_INET:
+ resp = self.sendport(host, port)
+ else:
+ resp = self.sendeprt(host, port)
+ if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT:
+ sock.settimeout(self.timeout)
+ return sock
+
+ def makepasv(self):
+ """Internal: Does the PASV or EPSV handshake -> (address, port)"""
+ if self.af == socket.AF_INET:
+ untrusted_host, port = parse227(self.sendcmd('PASV'))
+ if self.trust_server_pasv_ipv4_address:
+ host = untrusted_host
+ else:
+ host = self.sock.getpeername()[0]
+ else:
+ host, port = parse229(self.sendcmd('EPSV'), self.sock.getpeername())
+ return host, port
+
+ def ntransfercmd(self, cmd, rest=None):
+ """Initiate a transfer over the data connection.
+
+ If the transfer is active, send a port command and the
+ transfer command, and accept the connection. If the server is
+ passive, send a pasv command, connect to it, and start the
+ transfer command. Either way, return the socket for the
+ connection and the expected size of the transfer. The
+ expected size may be None if it could not be determined.
+
+ Optional 'rest' argument can be a string that is sent as the
+ argument to a REST command. This is essentially a server
+ marker used to tell the server to skip over any data up to the
+ given marker.
+ """
+ size = None
+ if self.passiveserver:
+ host, port = self.makepasv()
+ conn = socket.create_connection((host, port), self.timeout,
+ source_address=self.source_address)
+ try:
+ if rest is not None:
+ self.sendcmd("REST %s" % rest)
+ resp = self.sendcmd(cmd)
+ # Some servers apparently send a 200 reply to
+ # a LIST or STOR command, before the 150 reply
+ # (and way before the 226 reply). This seems to
+ # be in violation of the protocol (which only allows
+ # 1xx or error messages for LIST), so we just discard
+ # this response.
+ if resp[0] == '2':
+ resp = self.getresp()
+ if resp[0] != '1':
+ raise error_reply(resp)
+ except:
+ conn.close()
+ raise
+ else:
+ with self.makeport() as sock:
+ if rest is not None:
+ self.sendcmd("REST %s" % rest)
+ resp = self.sendcmd(cmd)
+ # See above.
+ if resp[0] == '2':
+ resp = self.getresp()
+ if resp[0] != '1':
+ raise error_reply(resp)
+ conn, sockaddr = sock.accept()
+ if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT:
+ conn.settimeout(self.timeout)
+ if resp[:3] == '150':
+ # this is conditional in case we received a 125
+ size = parse150(resp)
+ return conn, size
+
+ def transfercmd(self, cmd, rest=None):
+ """Like ntransfercmd() but returns only the socket."""
+ return self.ntransfercmd(cmd, rest)[0]
+
+ def login(self, user = '', passwd = '', acct = ''):
+ '''Login, default anonymous.'''
+ if not user:
+ user = 'anonymous'
+ if not passwd:
+ passwd = ''
+ if not acct:
+ acct = ''
+ if user == 'anonymous' and passwd in {'', '-'}:
+ # If there is no anonymous ftp password specified
+ # then we'll just use anonymous@
+ # We don't send any other thing because:
+ # - We want to remain anonymous
+ # - We want to stop SPAM
+ # - We don't want to let ftp sites to discriminate by the user,
+ # host or country.
+ passwd = passwd + 'anonymous@'
+ resp = self.sendcmd('USER ' + user)
+ if resp[0] == '3':
+ resp = self.sendcmd('PASS ' + passwd)
+ if resp[0] == '3':
+ resp = self.sendcmd('ACCT ' + acct)
+ if resp[0] != '2':
+ raise error_reply(resp)
+ return resp
+
+ def retrbinary(self, cmd, callback, blocksize=8192, rest=None):
+ """Retrieve data in binary mode. A new port is created for you.
+
+ Args:
+ cmd: A RETR command.
+ callback: A single parameter callable to be called on each
+ block of data read.
+ blocksize: The maximum number of bytes to read from the
+ socket at one time. [default: 8192]
+ rest: Passed to transfercmd(). [default: None]
+
+ Returns:
+ The response code.
+ """
+ self.voidcmd('TYPE I')
+ with self.transfercmd(cmd, rest) as conn:
+ while data := conn.recv(blocksize):
+ callback(data)
+ # shutdown ssl layer
+ if _SSLSocket is not None and isinstance(conn, _SSLSocket):
+ conn.unwrap()
+ return self.voidresp()
+
+ def retrlines(self, cmd, callback = None):
+ """Retrieve data in line mode. A new port is created for you.
+
+ Args:
+ cmd: A RETR, LIST, or NLST command.
+ callback: An optional single parameter callable that is called
+ for each line with the trailing CRLF stripped.
+ [default: print_line()]
+
+ Returns:
+ The response code.
+ """
+ if callback is None:
+ callback = print_line
+ resp = self.sendcmd('TYPE A')
+ with self.transfercmd(cmd) as conn, \
+ conn.makefile('r', encoding=self.encoding) as fp:
+ while 1:
+ line = fp.readline(self.maxline + 1)
+ if len(line) > self.maxline:
+ raise Error("got more than %d bytes" % self.maxline)
+ if self.debugging > 2:
+ print('*retr*', repr(line))
+ if not line:
+ break
+ if line[-2:] == CRLF:
+ line = line[:-2]
+ elif line[-1:] == '\n':
+ line = line[:-1]
+ callback(line)
+ # shutdown ssl layer
+ if _SSLSocket is not None and isinstance(conn, _SSLSocket):
+ conn.unwrap()
+ return self.voidresp()
+
+ def storbinary(self, cmd, fp, blocksize=8192, callback=None, rest=None):
+ """Store a file in binary mode. A new port is created for you.
+
+ Args:
+ cmd: A STOR command.
+ fp: A file-like object with a read(num_bytes) method.
+ blocksize: The maximum data size to read from fp and send over
+ the connection at once. [default: 8192]
+ callback: An optional single parameter callable that is called on
+ each block of data after it is sent. [default: None]
+ rest: Passed to transfercmd(). [default: None]
+
+ Returns:
+ The response code.
+ """
+ self.voidcmd('TYPE I')
+ with self.transfercmd(cmd, rest) as conn:
+ while buf := fp.read(blocksize):
+ conn.sendall(buf)
+ if callback:
+ callback(buf)
+ # shutdown ssl layer
+ if _SSLSocket is not None and isinstance(conn, _SSLSocket):
+ conn.unwrap()
+ return self.voidresp()
+
+ def storlines(self, cmd, fp, callback=None):
+ """Store a file in line mode. A new port is created for you.
+
+ Args:
+ cmd: A STOR command.
+ fp: A file-like object with a readline() method.
+ callback: An optional single parameter callable that is called on
+ each line after it is sent. [default: None]
+
+ Returns:
+ The response code.
+ """
+ self.voidcmd('TYPE A')
+ with self.transfercmd(cmd) as conn:
+ while 1:
+ buf = fp.readline(self.maxline + 1)
+ if len(buf) > self.maxline:
+ raise Error("got more than %d bytes" % self.maxline)
+ if not buf:
+ break
+ if buf[-2:] != B_CRLF:
+ if buf[-1] in B_CRLF: buf = buf[:-1]
+ buf = buf + B_CRLF
+ conn.sendall(buf)
+ if callback:
+ callback(buf)
+ # shutdown ssl layer
+ if _SSLSocket is not None and isinstance(conn, _SSLSocket):
+ conn.unwrap()
+ return self.voidresp()
+
+ def acct(self, password):
+ '''Send new account name.'''
+ cmd = 'ACCT ' + password
+ return self.voidcmd(cmd)
+
+ def nlst(self, *args):
+ '''Return a list of files in a given directory (default the current).'''
+ cmd = 'NLST'
+ for arg in args:
+ cmd = cmd + (' ' + arg)
+ files = []
+ self.retrlines(cmd, files.append)
+ return files
+
+ def dir(self, *args):
+ '''List a directory in long form.
+ By default list current directory to stdout.
+ Optional last argument is callback function; all
+ non-empty arguments before it are concatenated to the
+ LIST command. (This *should* only be used for a pathname.)'''
+ cmd = 'LIST'
+ func = None
+ if args[-1:] and not isinstance(args[-1], str):
+ args, func = args[:-1], args[-1]
+ for arg in args:
+ if arg:
+ cmd = cmd + (' ' + arg)
+ self.retrlines(cmd, func)
+
+ def mlsd(self, path="", facts=[]):
+ '''List a directory in a standardized format by using MLSD
+ command (RFC-3659). If path is omitted the current directory
+ is assumed. "facts" is a list of strings representing the type
+ of information desired (e.g. ["type", "size", "perm"]).
+
+ Return a generator object yielding a tuple of two elements
+ for every file found in path.
+ First element is the file name, the second one is a dictionary
+ including a variable number of "facts" depending on the server
+ and whether "facts" argument has been provided.
+ '''
+ if facts:
+ self.sendcmd("OPTS MLST " + ";".join(facts) + ";")
+ if path:
+ cmd = "MLSD %s" % path
+ else:
+ cmd = "MLSD"
+ lines = []
+ self.retrlines(cmd, lines.append)
+ for line in lines:
+ facts_found, _, name = line.rstrip(CRLF).partition(' ')
+ entry = {}
+ for fact in facts_found[:-1].split(";"):
+ key, _, value = fact.partition("=")
+ entry[key.lower()] = value
+ yield (name, entry)
+
+ def rename(self, fromname, toname):
+ '''Rename a file.'''
+ resp = self.sendcmd('RNFR ' + fromname)
+ if resp[0] != '3':
+ raise error_reply(resp)
+ return self.voidcmd('RNTO ' + toname)
+
+ def delete(self, filename):
+ '''Delete a file.'''
+ resp = self.sendcmd('DELE ' + filename)
+ if resp[:3] in {'250', '200'}:
+ return resp
+ else:
+ raise error_reply(resp)
+
+ def cwd(self, dirname):
+ '''Change to a directory.'''
+ if dirname == '..':
+ try:
+ return self.voidcmd('CDUP')
+ except error_perm as msg:
+ if msg.args[0][:3] != '500':
+ raise
+ elif dirname == '':
+ dirname = '.' # does nothing, but could return error
+ cmd = 'CWD ' + dirname
+ return self.voidcmd(cmd)
+
+ def size(self, filename):
+ '''Retrieve the size of a file.'''
+ # The SIZE command is defined in RFC-3659
+ resp = self.sendcmd('SIZE ' + filename)
+ if resp[:3] == '213':
+ s = resp[3:].strip()
+ return int(s)
+
+ def mkd(self, dirname):
+ '''Make a directory, return its full pathname.'''
+ resp = self.voidcmd('MKD ' + dirname)
+ # fix around non-compliant implementations such as IIS shipped
+ # with Windows server 2003
+ if not resp.startswith('257'):
+ return ''
+ return parse257(resp)
+
+ def rmd(self, dirname):
+ '''Remove a directory.'''
+ return self.voidcmd('RMD ' + dirname)
+
+ def pwd(self):
+ '''Return current working directory.'''
+ resp = self.voidcmd('PWD')
+ # fix around non-compliant implementations such as IIS shipped
+ # with Windows server 2003
+ if not resp.startswith('257'):
+ return ''
+ return parse257(resp)
+
+ def quit(self):
+ '''Quit, and close the connection.'''
+ resp = self.voidcmd('QUIT')
+ self.close()
+ return resp
+
+ def close(self):
+ '''Close the connection without assuming anything about it.'''
+ try:
+ file = self.file
+ self.file = None
+ if file is not None:
+ file.close()
+ finally:
+ sock = self.sock
+ self.sock = None
+ if sock is not None:
+ sock.close()
+
+try:
+ import ssl
+except ImportError:
+ _SSLSocket = None
+else:
+ _SSLSocket = ssl.SSLSocket
+
+ class FTP_TLS(FTP):
+ '''A FTP subclass which adds TLS support to FTP as described
+ in RFC-4217.
+
+ Connect as usual to port 21 implicitly securing the FTP control
+ connection before authenticating.
+
+ Securing the data connection requires user to explicitly ask
+ for it by calling prot_p() method.
+
+ Usage example:
+ >>> from ftplib import FTP_TLS
+ >>> ftps = FTP_TLS('ftp.python.org')
+ >>> ftps.login() # login anonymously previously securing control channel
+ '230 Guest login ok, access restrictions apply.'
+ >>> ftps.prot_p() # switch to secure data connection
+ '200 Protection level set to P'
+ >>> ftps.retrlines('LIST') # list directory content securely
+ total 9
+ drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .
+ drwxr-xr-x 8 root wheel 1024 Jan 3 1994 ..
+ drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin
+ drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc
+ d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming
+ drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib
+ drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub
+ drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr
+ -rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg
+ '226 Transfer complete.'
+ >>> ftps.quit()
+ '221 Goodbye.'
+ >>>
+ '''
+
+ def __init__(self, host='', user='', passwd='', acct='',
+ *, context=None, timeout=_GLOBAL_DEFAULT_TIMEOUT,
+ source_address=None, encoding='utf-8'):
+ if context is None:
+ context = ssl._create_stdlib_context()
+ self.context = context
+ self._prot_p = False
+ super().__init__(host, user, passwd, acct,
+ timeout, source_address, encoding=encoding)
+
+ def login(self, user='', passwd='', acct='', secure=True):
+ if secure and not isinstance(self.sock, ssl.SSLSocket):
+ self.auth()
+ return super().login(user, passwd, acct)
+
+ def auth(self):
+ '''Set up secure control connection by using TLS/SSL.'''
+ if isinstance(self.sock, ssl.SSLSocket):
+ raise ValueError("Already using TLS")
+ if self.context.protocol >= ssl.PROTOCOL_TLS:
+ resp = self.voidcmd('AUTH TLS')
+ else:
+ resp = self.voidcmd('AUTH SSL')
+ self.sock = self.context.wrap_socket(self.sock, server_hostname=self.host)
+ self.file = self.sock.makefile(mode='r', encoding=self.encoding)
+ return resp
+
+ def ccc(self):
+ '''Switch back to a clear-text control connection.'''
+ if not isinstance(self.sock, ssl.SSLSocket):
+ raise ValueError("not using TLS")
+ resp = self.voidcmd('CCC')
+ self.sock = self.sock.unwrap()
+ return resp
+
+ def prot_p(self):
+ '''Set up secure data connection.'''
+ # PROT defines whether or not the data channel is to be protected.
+ # Though RFC-2228 defines four possible protection levels,
+ # RFC-4217 only recommends two, Clear and Private.
+ # Clear (PROT C) means that no security is to be used on the
+ # data-channel, Private (PROT P) means that the data-channel
+ # should be protected by TLS.
+ # PBSZ command MUST still be issued, but must have a parameter of
+ # '0' to indicate that no buffering is taking place and the data
+ # connection should not be encapsulated.
+ self.voidcmd('PBSZ 0')
+ resp = self.voidcmd('PROT P')
+ self._prot_p = True
+ return resp
+
+ def prot_c(self):
+ '''Set up clear text data connection.'''
+ resp = self.voidcmd('PROT C')
+ self._prot_p = False
+ return resp
+
+ # --- Overridden FTP methods
+
+ def ntransfercmd(self, cmd, rest=None):
+ conn, size = super().ntransfercmd(cmd, rest)
+ if self._prot_p:
+ conn = self.context.wrap_socket(conn,
+ server_hostname=self.host)
+ return conn, size
+
+ def abort(self):
+ # overridden as we can't pass MSG_OOB flag to sendall()
+ line = b'ABOR' + B_CRLF
+ self.sock.sendall(line)
+ resp = self.getmultiline()
+ if resp[:3] not in {'426', '225', '226'}:
+ raise error_proto(resp)
+ return resp
+
+ __all__.append('FTP_TLS')
+ all_errors = (Error, OSError, EOFError, ssl.SSLError)
+
+
+_150_re = None
+
+def parse150(resp):
+ '''Parse the '150' response for a RETR request.
+ Returns the expected transfer size or None; size is not guaranteed to
+ be present in the 150 message.
+ '''
+ if resp[:3] != '150':
+ raise error_reply(resp)
+ global _150_re
+ if _150_re is None:
+ import re
+ _150_re = re.compile(
+ r"150 .* \((\d+) bytes\)", re.IGNORECASE | re.ASCII)
+ m = _150_re.match(resp)
+ if not m:
+ return None
+ return int(m.group(1))
+
+
+_227_re = None
+
+def parse227(resp):
+ '''Parse the '227' response for a PASV request.
+ Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)'
+ Return ('host.addr.as.numbers', port#) tuple.'''
+ if resp[:3] != '227':
+ raise error_reply(resp)
+ global _227_re
+ if _227_re is None:
+ import re
+ _227_re = re.compile(r'(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)', re.ASCII)
+ m = _227_re.search(resp)
+ if not m:
+ raise error_proto(resp)
+ numbers = m.groups()
+ host = '.'.join(numbers[:4])
+ port = (int(numbers[4]) << 8) + int(numbers[5])
+ return host, port
+
+
+def parse229(resp, peer):
+ '''Parse the '229' response for an EPSV request.
+ Raises error_proto if it does not contain '(|||port|)'
+ Return ('host.addr.as.numbers', port#) tuple.'''
+ if resp[:3] != '229':
+ raise error_reply(resp)
+ left = resp.find('(')
+ if left < 0: raise error_proto(resp)
+ right = resp.find(')', left + 1)
+ if right < 0:
+ raise error_proto(resp) # should contain '(|||port|)'
+ if resp[left + 1] != resp[right - 1]:
+ raise error_proto(resp)
+ parts = resp[left + 1:right].split(resp[left+1])
+ if len(parts) != 5:
+ raise error_proto(resp)
+ host = peer[0]
+ port = int(parts[3])
+ return host, port
+
+
+def parse257(resp):
+ '''Parse the '257' response for a MKD or PWD request.
+ This is a response to a MKD or PWD request: a directory name.
+ Returns the directoryname in the 257 reply.'''
+ if resp[:3] != '257':
+ raise error_reply(resp)
+ if resp[3:5] != ' "':
+ return '' # Not compliant to RFC 959, but UNIX ftpd does this
+ dirname = ''
+ i = 5
+ n = len(resp)
+ while i < n:
+ c = resp[i]
+ i = i+1
+ if c == '"':
+ if i >= n or resp[i] != '"':
+ break
+ i = i+1
+ dirname = dirname + c
+ return dirname
+
+
+def print_line(line):
+ '''Default retrlines callback to print a line.'''
+ print(line)
+
+
+def ftpcp(source, sourcename, target, targetname = '', type = 'I'):
+ '''Copy file from one FTP-instance to another.'''
+ if not targetname:
+ targetname = sourcename
+ type = 'TYPE ' + type
+ source.voidcmd(type)
+ target.voidcmd(type)
+ sourcehost, sourceport = parse227(source.sendcmd('PASV'))
+ target.sendport(sourcehost, sourceport)
+ # RFC 959: the user must "listen" [...] BEFORE sending the
+ # transfer request.
+ # So: STOR before RETR, because here the target is a "user".
+ treply = target.sendcmd('STOR ' + targetname)
+ if treply[:3] not in {'125', '150'}:
+ raise error_proto # RFC 959
+ sreply = source.sendcmd('RETR ' + sourcename)
+ if sreply[:3] not in {'125', '150'}:
+ raise error_proto # RFC 959
+ source.voidresp()
+ target.voidresp()
+
+
+def test():
+ '''Test program.
+ Usage: ftplib [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ...
+
+ Options:
+ -d increase debugging level
+ -r[file] set alternate ~/.netrc file
+
+ Commands:
+ -l[dir] list directory
+ -d[dir] change the current directory
+ -p toggle passive and active mode
+ file retrieve the file and write it to stdout
+ '''
+
+ if len(sys.argv) < 2:
+ print(test.__doc__)
+ sys.exit(0)
+
+ import netrc
+
+ debugging = 0
+ rcfile = None
+ while sys.argv[1] == '-d':
+ debugging = debugging+1
+ del sys.argv[1]
+ if sys.argv[1][:2] == '-r':
+ # get name of alternate ~/.netrc file:
+ rcfile = sys.argv[1][2:]
+ del sys.argv[1]
+ host = sys.argv[1]
+ ftp = FTP(host)
+ ftp.set_debuglevel(debugging)
+ userid = passwd = acct = ''
+ try:
+ netrcobj = netrc.netrc(rcfile)
+ except OSError:
+ if rcfile is not None:
+ print("Could not open account file -- using anonymous login.",
+ file=sys.stderr)
+ else:
+ try:
+ userid, acct, passwd = netrcobj.authenticators(host)
+ except (KeyError, TypeError):
+ # no account for host
+ print("No account -- using anonymous login.", file=sys.stderr)
+ ftp.login(userid, passwd, acct)
+ for file in sys.argv[2:]:
+ if file[:2] == '-l':
+ ftp.dir(file[2:])
+ elif file[:2] == '-d':
+ cmd = 'CWD'
+ if file[2:]: cmd = cmd + ' ' + file[2:]
+ resp = ftp.sendcmd(cmd)
+ elif file == '-p':
+ ftp.set_pasv(not ftp.passiveserver)
+ else:
+ ftp.retrbinary('RETR ' + file, \
+ sys.stdout.buffer.write, 1024)
+ sys.stdout.buffer.flush()
+ sys.stdout.flush()
+ ftp.quit()
+
+
+if __name__ == '__main__':
+ test()
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/functools.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/functools.py
new file mode 100644
index 0000000000000000000000000000000000000000..df4660eef3fe820d2396b69ec4541f6e66c8be4b
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/functools.py
@@ -0,0 +1,1165 @@
+"""functools.py - Tools for working with functions and callable objects
+"""
+# Python module wrapper for _functools C module
+# to allow utilities written in Python to be added
+# to the functools module.
+# Written by Nick Coghlan ,
+# Raymond Hettinger ,
+# and Łukasz Langa .
+# Copyright (C) 2006 Python Software Foundation.
+# See C source code for _functools credits/copyright
+
+__all__ = ['update_wrapper', 'wraps', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES',
+ 'total_ordering', 'cache', 'cmp_to_key', 'lru_cache', 'reduce',
+ 'partial', 'partialmethod', 'singledispatch', 'singledispatchmethod',
+ 'cached_property', 'Placeholder']
+
+from abc import get_cache_token
+from collections import namedtuple
+# import weakref # Deferred to single_dispatch()
+from operator import itemgetter
+from reprlib import recursive_repr
+from types import GenericAlias, MethodType, MappingProxyType, UnionType
+from _thread import RLock
+
+################################################################################
+### update_wrapper() and wraps() decorator
+################################################################################
+
+# update_wrapper() and wraps() are tools to help write
+# wrapper functions that can handle naive introspection
+
+WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__qualname__', '__doc__',
+ '__annotate__', '__type_params__')
+WRAPPER_UPDATES = ('__dict__',)
+def update_wrapper(wrapper,
+ wrapped,
+ assigned = WRAPPER_ASSIGNMENTS,
+ updated = WRAPPER_UPDATES):
+ """Update a wrapper function to look like the wrapped function
+
+ wrapper is the function to be updated
+ wrapped is the original function
+ assigned is a tuple naming the attributes assigned directly
+ from the wrapped function to the wrapper function (defaults to
+ functools.WRAPPER_ASSIGNMENTS)
+ updated is a tuple naming the attributes of the wrapper that
+ are updated with the corresponding attribute from the wrapped
+ function (defaults to functools.WRAPPER_UPDATES)
+ """
+ for attr in assigned:
+ try:
+ value = getattr(wrapped, attr)
+ except AttributeError:
+ pass
+ else:
+ setattr(wrapper, attr, value)
+ for attr in updated:
+ getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
+ # Issue #17482: set __wrapped__ last so we don't inadvertently copy it
+ # from the wrapped function when updating __dict__
+ wrapper.__wrapped__ = wrapped
+ # Return the wrapper so this can be used as a decorator via partial()
+ return wrapper
+
+def wraps(wrapped,
+ assigned = WRAPPER_ASSIGNMENTS,
+ updated = WRAPPER_UPDATES):
+ """Decorator factory to apply update_wrapper() to a wrapper function
+
+ Returns a decorator that invokes update_wrapper() with the decorated
+ function as the wrapper argument and the arguments to wraps() as the
+ remaining arguments. Default arguments are as for update_wrapper().
+ This is a convenience function to simplify applying partial() to
+ update_wrapper().
+ """
+ return partial(update_wrapper, wrapped=wrapped,
+ assigned=assigned, updated=updated)
+
+
+################################################################################
+### total_ordering class decorator
+################################################################################
+
+# The total ordering functions all invoke the root magic method directly
+# rather than using the corresponding operator. This avoids possible
+# infinite recursion that could occur when the operator dispatch logic
+# detects a NotImplemented result and then calls a reflected method.
+
+def _gt_from_lt(self, other):
+ 'Return a > b. Computed by @total_ordering from (not a < b) and (a != b).'
+ op_result = type(self).__lt__(self, other)
+ if op_result is NotImplemented:
+ return op_result
+ return not op_result and self != other
+
+def _le_from_lt(self, other):
+ 'Return a <= b. Computed by @total_ordering from (a < b) or (a == b).'
+ op_result = type(self).__lt__(self, other)
+ if op_result is NotImplemented:
+ return op_result
+ return op_result or self == other
+
+def _ge_from_lt(self, other):
+ 'Return a >= b. Computed by @total_ordering from (not a < b).'
+ op_result = type(self).__lt__(self, other)
+ if op_result is NotImplemented:
+ return op_result
+ return not op_result
+
+def _ge_from_le(self, other):
+ 'Return a >= b. Computed by @total_ordering from (not a <= b) or (a == b).'
+ op_result = type(self).__le__(self, other)
+ if op_result is NotImplemented:
+ return op_result
+ return not op_result or self == other
+
+def _lt_from_le(self, other):
+ 'Return a < b. Computed by @total_ordering from (a <= b) and (a != b).'
+ op_result = type(self).__le__(self, other)
+ if op_result is NotImplemented:
+ return op_result
+ return op_result and self != other
+
+def _gt_from_le(self, other):
+ 'Return a > b. Computed by @total_ordering from (not a <= b).'
+ op_result = type(self).__le__(self, other)
+ if op_result is NotImplemented:
+ return op_result
+ return not op_result
+
+def _lt_from_gt(self, other):
+ 'Return a < b. Computed by @total_ordering from (not a > b) and (a != b).'
+ op_result = type(self).__gt__(self, other)
+ if op_result is NotImplemented:
+ return op_result
+ return not op_result and self != other
+
+def _ge_from_gt(self, other):
+ 'Return a >= b. Computed by @total_ordering from (a > b) or (a == b).'
+ op_result = type(self).__gt__(self, other)
+ if op_result is NotImplemented:
+ return op_result
+ return op_result or self == other
+
+def _le_from_gt(self, other):
+ 'Return a <= b. Computed by @total_ordering from (not a > b).'
+ op_result = type(self).__gt__(self, other)
+ if op_result is NotImplemented:
+ return op_result
+ return not op_result
+
+def _le_from_ge(self, other):
+ 'Return a <= b. Computed by @total_ordering from (not a >= b) or (a == b).'
+ op_result = type(self).__ge__(self, other)
+ if op_result is NotImplemented:
+ return op_result
+ return not op_result or self == other
+
+def _gt_from_ge(self, other):
+ 'Return a > b. Computed by @total_ordering from (a >= b) and (a != b).'
+ op_result = type(self).__ge__(self, other)
+ if op_result is NotImplemented:
+ return op_result
+ return op_result and self != other
+
+def _lt_from_ge(self, other):
+ 'Return a < b. Computed by @total_ordering from (not a >= b).'
+ op_result = type(self).__ge__(self, other)
+ if op_result is NotImplemented:
+ return op_result
+ return not op_result
+
+_convert = {
+ '__lt__': [('__gt__', _gt_from_lt),
+ ('__le__', _le_from_lt),
+ ('__ge__', _ge_from_lt)],
+ '__le__': [('__ge__', _ge_from_le),
+ ('__lt__', _lt_from_le),
+ ('__gt__', _gt_from_le)],
+ '__gt__': [('__lt__', _lt_from_gt),
+ ('__ge__', _ge_from_gt),
+ ('__le__', _le_from_gt)],
+ '__ge__': [('__le__', _le_from_ge),
+ ('__gt__', _gt_from_ge),
+ ('__lt__', _lt_from_ge)]
+}
+
+def total_ordering(cls):
+ """Class decorator that fills in missing ordering methods"""
+ # Find user-defined comparisons (not those inherited from object).
+ roots = {op for op in _convert if getattr(cls, op, None) is not getattr(object, op, None)}
+ if not roots:
+ raise ValueError('must define at least one ordering operation: < > <= >=')
+ root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__
+ for opname, opfunc in _convert[root]:
+ if opname not in roots:
+ opfunc.__name__ = opname
+ setattr(cls, opname, opfunc)
+ return cls
+
+
+################################################################################
+### cmp_to_key() function converter
+################################################################################
+
+def cmp_to_key(mycmp):
+ """Convert a cmp= function into a key= function"""
+ class K(object):
+ __slots__ = ['obj']
+ def __init__(self, obj):
+ self.obj = obj
+ def __lt__(self, other):
+ return mycmp(self.obj, other.obj) < 0
+ def __gt__(self, other):
+ return mycmp(self.obj, other.obj) > 0
+ def __eq__(self, other):
+ return mycmp(self.obj, other.obj) == 0
+ def __le__(self, other):
+ return mycmp(self.obj, other.obj) <= 0
+ def __ge__(self, other):
+ return mycmp(self.obj, other.obj) >= 0
+ __hash__ = None
+ return K
+
+try:
+ from _functools import cmp_to_key
+except ImportError:
+ pass
+
+
+################################################################################
+### reduce() sequence to a single item
+################################################################################
+
+_initial_missing = object()
+
+def reduce(function, sequence, initial=_initial_missing):
+ """
+ reduce(function, iterable, /[, initial]) -> value
+
+ Apply a function of two arguments cumulatively to the items of an iterable, from left to right.
+
+ This effectively reduces the iterable to a single value. If initial is present,
+ it is placed before the items of the iterable in the calculation, and serves as
+ a default when the iterable is empty.
+
+ For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
+ calculates ((((1 + 2) + 3) + 4) + 5).
+ """
+
+ it = iter(sequence)
+
+ if initial is _initial_missing:
+ try:
+ value = next(it)
+ except StopIteration:
+ raise TypeError(
+ "reduce() of empty iterable with no initial value") from None
+ else:
+ value = initial
+
+ for element in it:
+ value = function(value, element)
+
+ return value
+
+
+################################################################################
+### partial() argument application
+################################################################################
+
+
+class _PlaceholderType:
+ """The type of the Placeholder singleton.
+
+ Used as a placeholder for partial arguments.
+ """
+ __instance = None
+ __slots__ = ()
+
+ def __init_subclass__(cls, *args, **kwargs):
+ raise TypeError(f"type '{cls.__name__}' is not an acceptable base type")
+
+ def __new__(cls):
+ if cls.__instance is None:
+ cls.__instance = object.__new__(cls)
+ return cls.__instance
+
+ def __repr__(self):
+ return 'Placeholder'
+
+ def __reduce__(self):
+ return 'Placeholder'
+
+Placeholder = _PlaceholderType()
+
+def _partial_prepare_merger(args):
+ if not args:
+ return 0, None
+ nargs = len(args)
+ order = []
+ j = nargs
+ for i, a in enumerate(args):
+ if a is Placeholder:
+ order.append(j)
+ j += 1
+ else:
+ order.append(i)
+ phcount = j - nargs
+ merger = itemgetter(*order) if phcount else None
+ return phcount, merger
+
+def _partial_new(cls, func, /, *args, **keywords):
+ if issubclass(cls, partial):
+ base_cls = partial
+ if not callable(func):
+ raise TypeError("the first argument must be callable")
+ else:
+ base_cls = partialmethod
+ # func could be a descriptor like classmethod which isn't callable
+ if not callable(func) and not hasattr(func, "__get__"):
+ raise TypeError(f"the first argument {func!r} must be a callable "
+ "or a descriptor")
+ if args and args[-1] is Placeholder:
+ raise TypeError("trailing Placeholders are not allowed")
+ for value in keywords.values():
+ if value is Placeholder:
+ raise TypeError("Placeholder cannot be passed as a keyword argument")
+ if isinstance(func, base_cls):
+ pto_phcount = func._phcount
+ tot_args = func.args
+ if args:
+ tot_args += args
+ if pto_phcount:
+ # merge args with args of `func` which is `partial`
+ nargs = len(args)
+ if nargs < pto_phcount:
+ tot_args += (Placeholder,) * (pto_phcount - nargs)
+ tot_args = func._merger(tot_args)
+ if nargs > pto_phcount:
+ tot_args += args[pto_phcount:]
+ phcount, merger = _partial_prepare_merger(tot_args)
+ else: # works for both pto_phcount == 0 and != 0
+ phcount, merger = pto_phcount, func._merger
+ keywords = {**func.keywords, **keywords}
+ func = func.func
+ else:
+ tot_args = args
+ phcount, merger = _partial_prepare_merger(tot_args)
+
+ self = object.__new__(cls)
+ self.func = func
+ self.args = tot_args
+ self.keywords = keywords
+ self._phcount = phcount
+ self._merger = merger
+ return self
+
+def _partial_repr(self):
+ cls = type(self)
+ module = cls.__module__
+ qualname = cls.__qualname__
+ args = [repr(self.func)]
+ args.extend(map(repr, self.args))
+ args.extend(f"{k}={v!r}" for k, v in self.keywords.items())
+ return f"{module}.{qualname}({', '.join(args)})"
+
+# Purely functional, no descriptor behaviour
+class partial:
+ """New function with partial application of the given arguments
+ and keywords.
+ """
+
+ __slots__ = ("func", "args", "keywords", "_phcount", "_merger",
+ "__dict__", "__weakref__")
+
+ __new__ = _partial_new
+ __repr__ = recursive_repr()(_partial_repr)
+
+ def __call__(self, /, *args, **keywords):
+ phcount = self._phcount
+ if phcount:
+ try:
+ pto_args = self._merger(self.args + args)
+ args = args[phcount:]
+ except IndexError:
+ raise TypeError("missing positional arguments "
+ "in 'partial' call; expected "
+ f"at least {phcount}, got {len(args)}")
+ else:
+ pto_args = self.args
+ keywords = {**self.keywords, **keywords}
+ return self.func(*pto_args, *args, **keywords)
+
+ def __get__(self, obj, objtype=None):
+ if obj is None:
+ return self
+ return MethodType(self, obj)
+
+ def __reduce__(self):
+ return type(self), (self.func,), (self.func, self.args,
+ self.keywords or None, self.__dict__ or None)
+
+ def __setstate__(self, state):
+ if not isinstance(state, tuple):
+ raise TypeError("argument to __setstate__ must be a tuple")
+ if len(state) != 4:
+ raise TypeError(f"expected 4 items in state, got {len(state)}")
+ func, args, kwds, namespace = state
+ if (not callable(func) or not isinstance(args, tuple) or
+ (kwds is not None and not isinstance(kwds, dict)) or
+ (namespace is not None and not isinstance(namespace, dict))):
+ raise TypeError("invalid partial state")
+
+ if args and args[-1] is Placeholder:
+ raise TypeError("trailing Placeholders are not allowed")
+ phcount, merger = _partial_prepare_merger(args)
+
+ args = tuple(args) # just in case it's a subclass
+ if kwds is None:
+ kwds = {}
+ elif type(kwds) is not dict: # XXX does it need to be *exactly* dict?
+ kwds = dict(kwds)
+ if namespace is None:
+ namespace = {}
+
+ self.__dict__ = namespace
+ self.func = func
+ self.args = args
+ self.keywords = kwds
+ self._phcount = phcount
+ self._merger = merger
+
+ __class_getitem__ = classmethod(GenericAlias)
+
+
+try:
+ from _functools import partial, Placeholder, _PlaceholderType
+except ImportError:
+ pass
+
+# Descriptor version
+class partialmethod:
+ """Method descriptor with partial application of the given arguments
+ and keywords.
+
+ Supports wrapping existing descriptors and handles non-descriptor
+ callables as instance methods.
+ """
+ __new__ = _partial_new
+ __repr__ = _partial_repr
+
+ def _make_unbound_method(self):
+ def _method(cls_or_self, /, *args, **keywords):
+ phcount = self._phcount
+ if phcount:
+ try:
+ pto_args = self._merger(self.args + args)
+ args = args[phcount:]
+ except IndexError:
+ raise TypeError("missing positional arguments "
+ "in 'partialmethod' call; expected "
+ f"at least {phcount}, got {len(args)}")
+ else:
+ pto_args = self.args
+ keywords = {**self.keywords, **keywords}
+ return self.func(cls_or_self, *pto_args, *args, **keywords)
+ _method.__isabstractmethod__ = self.__isabstractmethod__
+ _method.__partialmethod__ = self
+ return _method
+
+ def __get__(self, obj, cls=None):
+ get = getattr(self.func, "__get__", None)
+ result = None
+ if get is not None:
+ new_func = get(obj, cls)
+ if new_func is not self.func:
+ # Assume __get__ returning something new indicates the
+ # creation of an appropriate callable
+ result = partial(new_func, *self.args, **self.keywords)
+ try:
+ result.__self__ = new_func.__self__
+ except AttributeError:
+ pass
+ if result is None:
+ # If the underlying descriptor didn't do anything, treat this
+ # like an instance method
+ result = self._make_unbound_method().__get__(obj, cls)
+ return result
+
+ @property
+ def __isabstractmethod__(self):
+ return getattr(self.func, "__isabstractmethod__", False)
+
+ __class_getitem__ = classmethod(GenericAlias)
+
+
+# Helper functions
+
+def _unwrap_partial(func):
+ while isinstance(func, partial):
+ func = func.func
+ return func
+
+def _unwrap_partialmethod(func):
+ prev = None
+ while func is not prev:
+ prev = func
+ while isinstance(getattr(func, "__partialmethod__", None), partialmethod):
+ func = func.__partialmethod__
+ while isinstance(func, partialmethod):
+ func = getattr(func, 'func')
+ func = _unwrap_partial(func)
+ return func
+
+################################################################################
+### LRU Cache function decorator
+################################################################################
+
+_CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"])
+
+def _make_key(args, kwds, typed,
+ kwd_mark = (object(),),
+ fasttypes = {int, str},
+ tuple=tuple, type=type, len=len):
+ """Make a cache key from optionally typed positional and keyword arguments
+
+ The key is constructed in a way that is flat as possible rather than
+ as a nested structure that would take more memory.
+
+ If there is only a single argument and its data type is known to cache
+ its hash value, then that argument is returned without a wrapper. This
+ saves space and improves lookup speed.
+
+ """
+ # All of code below relies on kwds preserving the order input by the user.
+ # Formerly, we sorted() the kwds before looping. The new way is *much*
+ # faster; however, it means that f(x=1, y=2) will now be treated as a
+ # distinct call from f(y=2, x=1) which will be cached separately.
+ key = args
+ if kwds:
+ key += kwd_mark
+ for item in kwds.items():
+ key += item
+ if typed:
+ key += tuple(type(v) for v in args)
+ if kwds:
+ key += tuple(type(v) for v in kwds.values())
+ elif len(key) == 1 and type(key[0]) in fasttypes:
+ return key[0]
+ return key
+
+def lru_cache(maxsize=128, typed=False):
+ """Least-recently-used cache decorator.
+
+ If *maxsize* is set to None, the LRU features are disabled and the cache
+ can grow without bound.
+
+ If *typed* is True, arguments of different types will be cached separately.
+ For example, f(decimal.Decimal("3.0")) and f(3.0) will be treated as
+ distinct calls with distinct results. Some types such as str and int may
+ be cached separately even when typed is false.
+
+ Arguments to the cached function must be hashable.
+
+ View the cache statistics named tuple (hits, misses, maxsize, currsize)
+ with f.cache_info(). Clear the cache and statistics with f.cache_clear().
+ Access the underlying function with f.__wrapped__.
+
+ See: https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)
+
+ """
+
+ # Users should only access the lru_cache through its public API:
+ # cache_info, cache_clear, and f.__wrapped__
+ # The internals of the lru_cache are encapsulated for thread safety and
+ # to allow the implementation to change (including a possible C version).
+
+ if isinstance(maxsize, int):
+ # Negative maxsize is treated as 0
+ if maxsize < 0:
+ maxsize = 0
+ elif callable(maxsize) and isinstance(typed, bool):
+ # The user_function was passed in directly via the maxsize argument
+ user_function, maxsize = maxsize, 128
+ wrapper = _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo)
+ wrapper.cache_parameters = lambda : {'maxsize': maxsize, 'typed': typed}
+ return update_wrapper(wrapper, user_function)
+ elif maxsize is not None:
+ raise TypeError(
+ 'Expected first argument to be an integer, a callable, or None')
+
+ def decorating_function(user_function):
+ wrapper = _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo)
+ wrapper.cache_parameters = lambda : {'maxsize': maxsize, 'typed': typed}
+ return update_wrapper(wrapper, user_function)
+
+ return decorating_function
+
+def _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo):
+ # Constants shared by all lru cache instances:
+ sentinel = object() # unique object used to signal cache misses
+ make_key = _make_key # build a key from the function arguments
+ PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields
+
+ cache = {}
+ hits = misses = 0
+ full = False
+ cache_get = cache.get # bound method to lookup a key or return None
+ cache_len = cache.__len__ # get cache size without calling len()
+ lock = RLock() # because linkedlist updates aren't threadsafe
+ root = [] # root of the circular doubly linked list
+ root[:] = [root, root, None, None] # initialize by pointing to self
+
+ if maxsize == 0:
+
+ def wrapper(*args, **kwds):
+ # No caching -- just a statistics update
+ nonlocal misses
+ misses += 1
+ result = user_function(*args, **kwds)
+ return result
+
+ elif maxsize is None:
+
+ def wrapper(*args, **kwds):
+ # Simple caching without ordering or size limit
+ nonlocal hits, misses
+ key = make_key(args, kwds, typed)
+ result = cache_get(key, sentinel)
+ if result is not sentinel:
+ hits += 1
+ return result
+ misses += 1
+ result = user_function(*args, **kwds)
+ cache[key] = result
+ return result
+
+ else:
+
+ def wrapper(*args, **kwds):
+ # Size limited caching that tracks accesses by recency
+ nonlocal root, hits, misses, full
+ key = make_key(args, kwds, typed)
+ with lock:
+ link = cache_get(key)
+ if link is not None:
+ # Move the link to the front of the circular queue
+ link_prev, link_next, _key, result = link
+ link_prev[NEXT] = link_next
+ link_next[PREV] = link_prev
+ last = root[PREV]
+ last[NEXT] = root[PREV] = link
+ link[PREV] = last
+ link[NEXT] = root
+ hits += 1
+ return result
+ misses += 1
+ result = user_function(*args, **kwds)
+ with lock:
+ if key in cache:
+ # Getting here means that this same key was added to the
+ # cache while the lock was released. Since the link
+ # update is already done, we need only return the
+ # computed result and update the count of misses.
+ pass
+ elif full:
+ # Use the old root to store the new key and result.
+ oldroot = root
+ oldroot[KEY] = key
+ oldroot[RESULT] = result
+ # Empty the oldest link and make it the new root.
+ # Keep a reference to the old key and old result to
+ # prevent their ref counts from going to zero during the
+ # update. That will prevent potentially arbitrary object
+ # clean-up code (i.e. __del__) from running while we're
+ # still adjusting the links.
+ root = oldroot[NEXT]
+ oldkey = root[KEY]
+ oldresult = root[RESULT]
+ root[KEY] = root[RESULT] = None
+ # Now update the cache dictionary.
+ del cache[oldkey]
+ # Save the potentially reentrant cache[key] assignment
+ # for last, after the root and links have been put in
+ # a consistent state.
+ cache[key] = oldroot
+ else:
+ # Put result in a new link at the front of the queue.
+ last = root[PREV]
+ link = [last, root, key, result]
+ last[NEXT] = root[PREV] = cache[key] = link
+ # Use the cache_len bound method instead of the len() function
+ # which could potentially be wrapped in an lru_cache itself.
+ full = (cache_len() >= maxsize)
+ return result
+
+ def cache_info():
+ """Report cache statistics"""
+ with lock:
+ return _CacheInfo(hits, misses, maxsize, cache_len())
+
+ def cache_clear():
+ """Clear the cache and cache statistics"""
+ nonlocal hits, misses, full
+ with lock:
+ cache.clear()
+ root[:] = [root, root, None, None]
+ hits = misses = 0
+ full = False
+
+ wrapper.cache_info = cache_info
+ wrapper.cache_clear = cache_clear
+ return wrapper
+
+try:
+ from _functools import _lru_cache_wrapper
+except ImportError:
+ pass
+
+
+################################################################################
+### cache -- simplified access to the infinity cache
+################################################################################
+
+def cache(user_function, /):
+ 'Simple lightweight unbounded cache. Sometimes called "memoize".'
+ return lru_cache(maxsize=None)(user_function)
+
+
+################################################################################
+### singledispatch() - single-dispatch generic function decorator
+################################################################################
+
+def _c3_merge(sequences):
+ """Merges MROs in *sequences* to a single MRO using the C3 algorithm.
+
+ Adapted from https://docs.python.org/3/howto/mro.html.
+
+ """
+ result = []
+ while True:
+ sequences = [s for s in sequences if s] # purge empty sequences
+ if not sequences:
+ return result
+ for s1 in sequences: # find merge candidates among seq heads
+ candidate = s1[0]
+ for s2 in sequences:
+ if candidate in s2[1:]:
+ candidate = None
+ break # reject the current head, it appears later
+ else:
+ break
+ if candidate is None:
+ raise RuntimeError("Inconsistent hierarchy")
+ result.append(candidate)
+ # remove the chosen candidate
+ for seq in sequences:
+ if seq[0] == candidate:
+ del seq[0]
+
+def _c3_mro(cls, abcs=None):
+ """Computes the method resolution order using extended C3 linearization.
+
+ If no *abcs* are given, the algorithm works exactly like the built-in C3
+ linearization used for method resolution.
+
+ If given, *abcs* is a list of abstract base classes that should be inserted
+ into the resulting MRO. Unrelated ABCs are ignored and don't end up in the
+ result. The algorithm inserts ABCs where their functionality is introduced,
+ i.e. issubclass(cls, abc) returns True for the class itself but returns
+ False for all its direct base classes. Implicit ABCs for a given class
+ (either registered or inferred from the presence of a special method like
+ __len__) are inserted directly after the last ABC explicitly listed in the
+ MRO of said class. If two implicit ABCs end up next to each other in the
+ resulting MRO, their ordering depends on the order of types in *abcs*.
+
+ """
+ for i, base in enumerate(reversed(cls.__bases__)):
+ if hasattr(base, '__abstractmethods__'):
+ boundary = len(cls.__bases__) - i
+ break # Bases up to the last explicit ABC are considered first.
+ else:
+ boundary = 0
+ abcs = list(abcs) if abcs else []
+ explicit_bases = list(cls.__bases__[:boundary])
+ abstract_bases = []
+ other_bases = list(cls.__bases__[boundary:])
+ for base in abcs:
+ if issubclass(cls, base) and not any(
+ issubclass(b, base) for b in cls.__bases__
+ ):
+ # If *cls* is the class that introduces behaviour described by
+ # an ABC *base*, insert said ABC to its MRO.
+ abstract_bases.append(base)
+ for base in abstract_bases:
+ abcs.remove(base)
+ explicit_c3_mros = [_c3_mro(base, abcs=abcs) for base in explicit_bases]
+ abstract_c3_mros = [_c3_mro(base, abcs=abcs) for base in abstract_bases]
+ other_c3_mros = [_c3_mro(base, abcs=abcs) for base in other_bases]
+ return _c3_merge(
+ [[cls]] +
+ explicit_c3_mros + abstract_c3_mros + other_c3_mros +
+ [explicit_bases] + [abstract_bases] + [other_bases]
+ )
+
+def _compose_mro(cls, types):
+ """Calculates the method resolution order for a given class *cls*.
+
+ Includes relevant abstract base classes (with their respective bases) from
+ the *types* iterable. Uses a modified C3 linearization algorithm.
+
+ """
+ bases = set(cls.__mro__)
+ # Remove entries which are already present in the __mro__ or unrelated.
+ def is_related(typ):
+ return (typ not in bases and hasattr(typ, '__mro__')
+ and not isinstance(typ, GenericAlias)
+ and issubclass(cls, typ))
+ types = [n for n in types if is_related(n)]
+ # Remove entries which are strict bases of other entries (they will end up
+ # in the MRO anyway.
+ def is_strict_base(typ):
+ for other in types:
+ if typ != other and typ in other.__mro__:
+ return True
+ return False
+ types = [n for n in types if not is_strict_base(n)]
+ # Subclasses of the ABCs in *types* which are also implemented by
+ # *cls* can be used to stabilize ABC ordering.
+ type_set = set(types)
+ mro = []
+ for typ in types:
+ found = []
+ for sub in typ.__subclasses__():
+ if sub not in bases and issubclass(cls, sub):
+ found.append([s for s in sub.__mro__ if s in type_set])
+ if not found:
+ mro.append(typ)
+ continue
+ # Favor subclasses with the biggest number of useful bases
+ found.sort(key=len, reverse=True)
+ for sub in found:
+ for subcls in sub:
+ if subcls not in mro:
+ mro.append(subcls)
+ return _c3_mro(cls, abcs=mro)
+
+def _find_impl(cls, registry):
+ """Returns the best matching implementation from *registry* for type *cls*.
+
+ Where there is no registered implementation for a specific type, its method
+ resolution order is used to find a more generic implementation.
+
+ Note: if *registry* does not contain an implementation for the base
+ *object* type, this function may return None.
+
+ """
+ mro = _compose_mro(cls, registry.keys())
+ match = None
+ for t in mro:
+ if match is not None:
+ # If *match* is an implicit ABC but there is another unrelated,
+ # equally matching implicit ABC, refuse the temptation to guess.
+ if (t in registry and t not in cls.__mro__
+ and match not in cls.__mro__
+ and not issubclass(match, t)):
+ raise RuntimeError("Ambiguous dispatch: {} or {}".format(
+ match, t))
+ break
+ if t in registry:
+ match = t
+ return registry.get(match)
+
+def singledispatch(func):
+ """Single-dispatch generic function decorator.
+
+ Transforms a function into a generic function, which can have different
+ behaviours depending upon the type of its first argument. The decorated
+ function acts as the default implementation, and additional
+ implementations can be registered using the register() attribute of the
+ generic function.
+ """
+ # There are many programs that use functools without singledispatch, so we
+ # trade-off making singledispatch marginally slower for the benefit of
+ # making start-up of such applications slightly faster.
+ import weakref
+
+ registry = {}
+ dispatch_cache = weakref.WeakKeyDictionary()
+ cache_token = None
+
+ def dispatch(cls):
+ """generic_func.dispatch(cls) ->
+
+ Runs the dispatch algorithm to return the best available implementation
+ for the given *cls* registered on *generic_func*.
+
+ """
+ nonlocal cache_token
+ if cache_token is not None:
+ current_token = get_cache_token()
+ if cache_token != current_token:
+ dispatch_cache.clear()
+ cache_token = current_token
+ try:
+ impl = dispatch_cache[cls]
+ except KeyError:
+ try:
+ impl = registry[cls]
+ except KeyError:
+ impl = _find_impl(cls, registry)
+ dispatch_cache[cls] = impl
+ return impl
+
+ def _is_valid_dispatch_type(cls):
+ if isinstance(cls, type):
+ return True
+ return (isinstance(cls, UnionType) and
+ all(isinstance(arg, type) for arg in cls.__args__))
+
+ def register(cls, func=None):
+ """generic_func.register(cls, func) -> func
+
+ Registers a new implementation for the given *cls* on a *generic_func*.
+
+ """
+ nonlocal cache_token
+ if _is_valid_dispatch_type(cls):
+ if func is None:
+ return lambda f: register(cls, f)
+ else:
+ if func is not None:
+ raise TypeError(
+ f"Invalid first argument to `register()`. "
+ f"{cls!r} is not a class or union type."
+ )
+ ann = getattr(cls, '__annotate__', None)
+ if ann is None:
+ raise TypeError(
+ f"Invalid first argument to `register()`: {cls!r}. "
+ f"Use either `@register(some_class)` or plain `@register` "
+ f"on an annotated function."
+ )
+ func = cls
+
+ # only import typing if annotation parsing is necessary
+ from typing import get_type_hints
+ from annotationlib import Format, ForwardRef
+ argname, cls = next(iter(get_type_hints(func, format=Format.FORWARDREF).items()))
+ if not _is_valid_dispatch_type(cls):
+ if isinstance(cls, UnionType):
+ raise TypeError(
+ f"Invalid annotation for {argname!r}. "
+ f"{cls!r} not all arguments are classes."
+ )
+ elif isinstance(cls, ForwardRef):
+ raise TypeError(
+ f"Invalid annotation for {argname!r}. "
+ f"{cls!r} is an unresolved forward reference."
+ )
+ else:
+ raise TypeError(
+ f"Invalid annotation for {argname!r}. "
+ f"{cls!r} is not a class."
+ )
+
+ if isinstance(cls, UnionType):
+ for arg in cls.__args__:
+ registry[arg] = func
+ else:
+ registry[cls] = func
+ if cache_token is None and hasattr(cls, '__abstractmethods__'):
+ cache_token = get_cache_token()
+ dispatch_cache.clear()
+ return func
+
+ def wrapper(*args, **kw):
+ if not args:
+ raise TypeError(f'{funcname} requires at least '
+ '1 positional argument')
+ return dispatch(args[0].__class__)(*args, **kw)
+
+ funcname = getattr(func, '__name__', 'singledispatch function')
+ registry[object] = func
+ wrapper.register = register
+ wrapper.dispatch = dispatch
+ wrapper.registry = MappingProxyType(registry)
+ wrapper._clear_cache = dispatch_cache.clear
+ update_wrapper(wrapper, func)
+ return wrapper
+
+
+# Descriptor version
+class singledispatchmethod:
+ """Single-dispatch generic method descriptor.
+
+ Supports wrapping existing descriptors.
+ """
+
+ def __init__(self, func):
+ if not callable(func) and not hasattr(func, "__get__"):
+ raise TypeError(f"{func!r} is not callable or a descriptor")
+
+ self.dispatcher = singledispatch(func)
+ self.func = func
+
+ def register(self, cls, method=None):
+ """generic_method.register(cls, func) -> func
+
+ Registers a new implementation for the given *cls* on a *generic_method*.
+ """
+ return self.dispatcher.register(cls, func=method)
+
+ def __get__(self, obj, cls=None):
+ return _singledispatchmethod_get(self, obj, cls)
+
+ @property
+ def __isabstractmethod__(self):
+ return getattr(self.func, '__isabstractmethod__', False)
+
+ def __repr__(self):
+ try:
+ name = self.func.__qualname__
+ except AttributeError:
+ try:
+ name = self.func.__name__
+ except AttributeError:
+ name = '?'
+ return f''
+
+class _singledispatchmethod_get:
+ def __init__(self, unbound, obj, cls):
+ self._unbound = unbound
+ self._dispatch = unbound.dispatcher.dispatch
+ self._obj = obj
+ self._cls = cls
+ # Set instance attributes which cannot be handled in __getattr__()
+ # because they conflict with type descriptors.
+ func = unbound.func
+ try:
+ self.__module__ = func.__module__
+ except AttributeError:
+ pass
+ try:
+ self.__doc__ = func.__doc__
+ except AttributeError:
+ pass
+
+ def __repr__(self):
+ try:
+ name = self.__qualname__
+ except AttributeError:
+ try:
+ name = self.__name__
+ except AttributeError:
+ name = '?'
+ if self._obj is not None:
+ return f''
+ else:
+ return f''
+
+ def __call__(self, /, *args, **kwargs):
+ if not args:
+ funcname = getattr(self._unbound.func, '__name__',
+ 'singledispatchmethod method')
+ raise TypeError(f'{funcname} requires at least '
+ '1 positional argument')
+ return self._dispatch(args[0].__class__).__get__(self._obj, self._cls)(*args, **kwargs)
+
+ def __getattr__(self, name):
+ # Resolve these attributes lazily to speed up creation of
+ # the _singledispatchmethod_get instance.
+ if name not in {'__name__', '__qualname__', '__isabstractmethod__',
+ '__annotations__', '__type_params__'}:
+ raise AttributeError
+ return getattr(self._unbound.func, name)
+
+ @property
+ def __wrapped__(self):
+ return self._unbound.func
+
+ @property
+ def register(self):
+ return self._unbound.register
+
+
+################################################################################
+### cached_property() - property result cached as instance attribute
+################################################################################
+
+_NOT_FOUND = object()
+
+class cached_property:
+ def __init__(self, func):
+ self.func = func
+ self.attrname = None
+ self.__doc__ = func.__doc__
+ self.__module__ = func.__module__
+
+ def __set_name__(self, owner, name):
+ if self.attrname is None:
+ self.attrname = name
+ elif name != self.attrname:
+ raise TypeError(
+ "Cannot assign the same cached_property to two different names "
+ f"({self.attrname!r} and {name!r})."
+ )
+
+ def __get__(self, instance, owner=None):
+ if instance is None:
+ return self
+ if self.attrname is None:
+ raise TypeError(
+ "Cannot use cached_property instance without calling __set_name__ on it.")
+ try:
+ cache = instance.__dict__
+ except AttributeError: # not all objects have __dict__ (e.g. class defines slots)
+ msg = (
+ f"No '__dict__' attribute on {type(instance).__name__!r} "
+ f"instance to cache {self.attrname!r} property."
+ )
+ raise TypeError(msg) from None
+ val = cache.get(self.attrname, _NOT_FOUND)
+ if val is _NOT_FOUND:
+ val = self.func(instance)
+ try:
+ cache[self.attrname] = val
+ except TypeError:
+ msg = (
+ f"The '__dict__' attribute on {type(instance).__name__!r} instance "
+ f"does not support item assignment for caching {self.attrname!r} property."
+ )
+ raise TypeError(msg) from None
+ return val
+
+ __class_getitem__ = classmethod(GenericAlias)
+
+def _warn_python_reduce_kwargs(py_reduce):
+ @wraps(py_reduce)
+ def wrapper(*args, **kwargs):
+ if 'function' in kwargs or 'sequence' in kwargs:
+ import os
+ import warnings
+ warnings.warn(
+ 'Calling functools.reduce with keyword arguments '
+ '"function" or "sequence" '
+ 'is deprecated in Python 3.14 and will be '
+ 'forbidden in Python 3.16.',
+ DeprecationWarning,
+ skip_file_prefixes=(os.path.dirname(__file__),))
+ return py_reduce(*args, **kwargs)
+ return wrapper
+
+reduce = _warn_python_reduce_kwargs(reduce)
+del _warn_python_reduce_kwargs
+
+# The import of the C accelerated version of reduce() has been moved
+# here due to gh-121676. In Python 3.16, _warn_python_reduce_kwargs()
+# should be removed and the import block should be moved back right
+# after the definition of reduce().
+try:
+ from _functools import reduce
+except ImportError:
+ pass
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/genericpath.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/genericpath.py
new file mode 100644
index 0000000000000000000000000000000000000000..9363f564aab7a6d8378e23fb60a9e9ddcb1c45d9
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/genericpath.py
@@ -0,0 +1,200 @@
+"""
+Path operations common to more than one OS
+Do not use directly. The OS specific modules import the appropriate
+functions from this module themselves.
+"""
+import os
+import stat
+
+__all__ = ['commonprefix', 'exists', 'getatime', 'getctime', 'getmtime',
+ 'getsize', 'isdevdrive', 'isdir', 'isfile', 'isjunction', 'islink',
+ 'lexists', 'samefile', 'sameopenfile', 'samestat', 'ALLOW_MISSING']
+
+
+# Does a path exist?
+# This is false for dangling symbolic links on systems that support them.
+def exists(path):
+ """Test whether a path exists. Returns False for broken symbolic links"""
+ try:
+ os.stat(path)
+ except (OSError, ValueError):
+ return False
+ return True
+
+
+# Being true for dangling symbolic links is also useful.
+def lexists(path):
+ """Test whether a path exists. Returns True for broken symbolic links"""
+ try:
+ os.lstat(path)
+ except (OSError, ValueError):
+ return False
+ return True
+
+# This follows symbolic links, so both islink() and isdir() can be true
+# for the same path on systems that support symlinks
+def isfile(path):
+ """Test whether a path is a regular file"""
+ try:
+ st = os.stat(path)
+ except (OSError, ValueError):
+ return False
+ return stat.S_ISREG(st.st_mode)
+
+
+# Is a path a directory?
+# This follows symbolic links, so both islink() and isdir()
+# can be true for the same path on systems that support symlinks
+def isdir(s):
+ """Return true if the pathname refers to an existing directory."""
+ try:
+ st = os.stat(s)
+ except (OSError, ValueError):
+ return False
+ return stat.S_ISDIR(st.st_mode)
+
+
+# Is a path a symbolic link?
+# This will always return false on systems where os.lstat doesn't exist.
+
+def islink(path):
+ """Test whether a path is a symbolic link"""
+ try:
+ st = os.lstat(path)
+ except (OSError, ValueError, AttributeError):
+ return False
+ return stat.S_ISLNK(st.st_mode)
+
+
+# Is a path a junction?
+def isjunction(path):
+ """Test whether a path is a junction
+ Junctions are not supported on the current platform"""
+ os.fspath(path)
+ return False
+
+
+def isdevdrive(path):
+ """Determines whether the specified path is on a Windows Dev Drive.
+ Dev Drives are not supported on the current platform"""
+ os.fspath(path)
+ return False
+
+
+def getsize(filename):
+ """Return the size of a file, reported by os.stat()."""
+ return os.stat(filename).st_size
+
+
+def getmtime(filename):
+ """Return the last modification time of a file, reported by os.stat()."""
+ return os.stat(filename).st_mtime
+
+
+def getatime(filename):
+ """Return the last access time of a file, reported by os.stat()."""
+ return os.stat(filename).st_atime
+
+
+def getctime(filename):
+ """Return the metadata change time of a file, reported by os.stat()."""
+ return os.stat(filename).st_ctime
+
+
+# Return the longest prefix of all list elements.
+def commonprefix(m):
+ "Given a list of pathnames, returns the longest common leading component"
+ if not m: return ''
+ # Some people pass in a list of pathname parts to operate in an OS-agnostic
+ # fashion; don't try to translate in that case as that's an abuse of the
+ # API and they are already doing what they need to be OS-agnostic and so
+ # they most likely won't be using an os.PathLike object in the sublists.
+ if not isinstance(m[0], (list, tuple)):
+ m = tuple(map(os.fspath, m))
+ s1 = min(m)
+ s2 = max(m)
+ for i, c in enumerate(s1):
+ if c != s2[i]:
+ return s1[:i]
+ return s1
+
+# Are two stat buffers (obtained from stat, fstat or lstat)
+# describing the same file?
+def samestat(s1, s2):
+ """Test whether two stat buffers reference the same file"""
+ return (s1.st_ino == s2.st_ino and
+ s1.st_dev == s2.st_dev)
+
+
+# Are two filenames really pointing to the same file?
+def samefile(f1, f2):
+ """Test whether two pathnames reference the same actual file or directory
+
+ This is determined by the device number and i-node number and
+ raises an exception if an os.stat() call on either pathname fails.
+ """
+ s1 = os.stat(f1)
+ s2 = os.stat(f2)
+ return samestat(s1, s2)
+
+
+# Are two open files really referencing the same file?
+# (Not necessarily the same file descriptor!)
+def sameopenfile(fp1, fp2):
+ """Test whether two open file objects reference the same file"""
+ s1 = os.fstat(fp1)
+ s2 = os.fstat(fp2)
+ return samestat(s1, s2)
+
+
+# Split a path in root and extension.
+# The extension is everything starting at the last dot in the last
+# pathname component; the root is everything before that.
+# It is always true that root + ext == p.
+
+# Generic implementation of splitext, to be parametrized with
+# the separators
+def _splitext(p, sep, altsep, extsep):
+ """Split the extension from a pathname.
+
+ Extension is everything from the last dot to the end, ignoring
+ leading dots. Returns "(root, ext)"; ext may be empty."""
+ # NOTE: This code must work for text and bytes strings.
+
+ sepIndex = p.rfind(sep)
+ if altsep:
+ altsepIndex = p.rfind(altsep)
+ sepIndex = max(sepIndex, altsepIndex)
+
+ dotIndex = p.rfind(extsep)
+ if dotIndex > sepIndex:
+ # skip all leading dots
+ filenameIndex = sepIndex + 1
+ while filenameIndex < dotIndex:
+ if p[filenameIndex:filenameIndex+1] != extsep:
+ return p[:dotIndex], p[dotIndex:]
+ filenameIndex += 1
+
+ return p, p[:0]
+
+def _check_arg_types(funcname, *args):
+ hasstr = hasbytes = False
+ for s in args:
+ if isinstance(s, str):
+ hasstr = True
+ elif isinstance(s, bytes):
+ hasbytes = True
+ else:
+ raise TypeError(f'{funcname}() argument must be str, bytes, or '
+ f'os.PathLike object, not {s.__class__.__name__!r}') from None
+ if hasstr and hasbytes:
+ raise TypeError("Can't mix strings and bytes in path components") from None
+
+# A singleton with a true boolean value.
+@object.__new__
+class ALLOW_MISSING:
+ """Special value for use in realpath()."""
+ def __repr__(self):
+ return 'os.path.ALLOW_MISSING'
+ def __reduce__(self):
+ return self.__class__.__name__
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/getopt.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/getopt.py
new file mode 100644
index 0000000000000000000000000000000000000000..25f3e2439b3e352488d5e2f7879d9627b7aa3a30
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/getopt.py
@@ -0,0 +1,232 @@
+"""Parser for command line options.
+
+This module helps scripts to parse the command line arguments in
+sys.argv. It supports the same conventions as the Unix getopt()
+function (including the special meanings of arguments of the form '-'
+and '--'). Long options similar to those supported by GNU software
+may be used as well via an optional third argument. This module
+provides two functions and an exception:
+
+getopt() -- Parse command line options
+gnu_getopt() -- Like getopt(), but allow option and non-option arguments
+to be intermixed.
+GetoptError -- exception (class) raised with 'opt' attribute, which is the
+option involved with the exception.
+"""
+
+# Long option support added by Lars Wirzenius .
+#
+# Gerrit Holl moved the string-based exceptions
+# to class-based exceptions.
+#
+# Peter Åstrand added gnu_getopt().
+#
+# TODO for gnu_getopt():
+#
+# - GNU getopt_long_only mechanism
+# - an option string with a W followed by semicolon should
+# treat "-W foo" as "--foo"
+
+__all__ = ["GetoptError","error","getopt","gnu_getopt"]
+
+import os
+from gettext import gettext as _
+
+
+class GetoptError(Exception):
+ opt = ''
+ msg = ''
+ def __init__(self, msg, opt=''):
+ self.msg = msg
+ self.opt = opt
+ Exception.__init__(self, msg, opt)
+
+ def __str__(self):
+ return self.msg
+
+error = GetoptError # backward compatibility
+
+def getopt(args, shortopts, longopts = []):
+ """getopt(args, options[, long_options]) -> opts, args
+
+ Parses command line options and parameter list. args is the
+ argument list to be parsed, without the leading reference to the
+ running program. Typically, this means "sys.argv[1:]". shortopts
+ is the string of option letters that the script wants to
+ recognize, with options that require an argument followed by a
+ colon and options that accept an optional argument followed by
+ two colons (i.e., the same format that Unix getopt() uses). If
+ specified, longopts is a list of strings with the names of the
+ long options which should be supported. The leading '--'
+ characters should not be included in the option name. Options
+ which require an argument should be followed by an equal sign
+ ('='). Options which accept an optional argument should be
+ followed by an equal sign and question mark ('=?').
+
+ The return value consists of two elements: the first is a list of
+ (option, value) pairs; the second is the list of program arguments
+ left after the option list was stripped (this is a trailing slice
+ of the first argument). Each option-and-value pair returned has
+ the option as its first element, prefixed with a hyphen (e.g.,
+ '-x'), and the option argument as its second element, or an empty
+ string if the option has no argument. The options occur in the
+ list in the same order in which they were found, thus allowing
+ multiple occurrences. Long and short options may be mixed.
+
+ """
+
+ opts = []
+ if isinstance(longopts, str):
+ longopts = [longopts]
+ else:
+ longopts = list(longopts)
+ while args and args[0].startswith('-') and args[0] != '-':
+ if args[0] == '--':
+ args = args[1:]
+ break
+ if args[0].startswith('--'):
+ opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
+ else:
+ opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
+
+ return opts, args
+
+def gnu_getopt(args, shortopts, longopts = []):
+ """getopt(args, options[, long_options]) -> opts, args
+
+ This function works like getopt(), except that GNU style scanning
+ mode is used by default. This means that option and non-option
+ arguments may be intermixed. The getopt() function stops
+ processing options as soon as a non-option argument is
+ encountered.
+
+ If the first character of the option string is '+', or if the
+ environment variable POSIXLY_CORRECT is set, then option
+ processing stops as soon as a non-option argument is encountered.
+
+ """
+
+ opts = []
+ prog_args = []
+ if isinstance(longopts, str):
+ longopts = [longopts]
+ else:
+ longopts = list(longopts)
+
+ return_in_order = False
+ if shortopts.startswith('-'):
+ shortopts = shortopts[1:]
+ all_options_first = False
+ return_in_order = True
+ # Allow options after non-option arguments?
+ elif shortopts.startswith('+'):
+ shortopts = shortopts[1:]
+ all_options_first = True
+ elif os.environ.get("POSIXLY_CORRECT"):
+ all_options_first = True
+ else:
+ all_options_first = False
+
+ while args:
+ if args[0] == '--':
+ prog_args += args[1:]
+ break
+
+ if args[0][:2] == '--':
+ if return_in_order and prog_args:
+ opts.append((None, prog_args))
+ prog_args = []
+ opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
+ elif args[0][:1] == '-' and args[0] != '-':
+ if return_in_order and prog_args:
+ opts.append((None, prog_args))
+ prog_args = []
+ opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
+ else:
+ if all_options_first:
+ prog_args += args
+ break
+ else:
+ prog_args.append(args[0])
+ args = args[1:]
+
+ return opts, prog_args
+
+def do_longs(opts, opt, longopts, args):
+ try:
+ i = opt.index('=')
+ except ValueError:
+ optarg = None
+ else:
+ opt, optarg = opt[:i], opt[i+1:]
+
+ has_arg, opt = long_has_args(opt, longopts)
+ if has_arg:
+ if optarg is None and has_arg != '?':
+ if not args:
+ raise GetoptError(_('option --%s requires argument') % opt, opt)
+ optarg, args = args[0], args[1:]
+ elif optarg is not None:
+ raise GetoptError(_('option --%s must not have an argument') % opt, opt)
+ opts.append(('--' + opt, optarg or ''))
+ return opts, args
+
+# Return:
+# has_arg?
+# full option name
+def long_has_args(opt, longopts):
+ possibilities = [o for o in longopts if o.startswith(opt)]
+ if not possibilities:
+ raise GetoptError(_('option --%s not recognized') % opt, opt)
+ # Is there an exact match?
+ if opt in possibilities:
+ return False, opt
+ elif opt + '=' in possibilities:
+ return True, opt
+ elif opt + '=?' in possibilities:
+ return '?', opt
+ # Possibilities must be unique to be accepted
+ if len(possibilities) > 1:
+ raise GetoptError(
+ _("option --%s not a unique prefix; possible options: %s")
+ % (opt, ", ".join(possibilities)),
+ opt,
+ )
+ assert len(possibilities) == 1
+ unique_match = possibilities[0]
+ if unique_match.endswith('=?'):
+ return '?', unique_match[:-2]
+ has_arg = unique_match.endswith('=')
+ if has_arg:
+ unique_match = unique_match[:-1]
+ return has_arg, unique_match
+
+def do_shorts(opts, optstring, shortopts, args):
+ while optstring != '':
+ opt, optstring = optstring[0], optstring[1:]
+ has_arg = short_has_arg(opt, shortopts)
+ if has_arg:
+ if optstring == '' and has_arg != '?':
+ if not args:
+ raise GetoptError(_('option -%s requires argument') % opt,
+ opt)
+ optstring, args = args[0], args[1:]
+ optarg, optstring = optstring, ''
+ else:
+ optarg = ''
+ opts.append(('-' + opt, optarg))
+ return opts, args
+
+def short_has_arg(opt, shortopts):
+ for i in range(len(shortopts)):
+ if opt == shortopts[i] != ':':
+ if not shortopts.startswith(':', i+1):
+ return False
+ if shortopts.startswith('::', i+1):
+ return '?'
+ return True
+ raise GetoptError(_('option -%s not recognized') % opt, opt)
+
+if __name__ == '__main__':
+ import sys
+ print(getopt(sys.argv[1:], "a:b", ["alpha=", "beta"]))
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/getpass.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/getpass.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d9bb1f0d146a48ba9622f84b008e7f69f7584b9
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/getpass.py
@@ -0,0 +1,256 @@
+"""Utilities to get a password and/or the current user name.
+
+getpass(prompt[, stream[, echo_char]]) - Prompt for a password, with echo
+turned off and optional keyboard feedback.
+getuser() - Get the user name from the environment or password database.
+
+GetPassWarning - This UserWarning is issued when getpass() cannot prevent
+ echoing of the password contents while reading.
+
+On Windows, the msvcrt module will be used.
+
+"""
+
+# Authors: Piers Lauder (original)
+# Guido van Rossum (Windows support and cleanup)
+# Gregory P. Smith (tty support & GetPassWarning)
+
+import contextlib
+import io
+import os
+import sys
+
+__all__ = ["getpass","getuser","GetPassWarning"]
+
+
+class GetPassWarning(UserWarning): pass
+
+
+def unix_getpass(prompt='Password: ', stream=None, *, echo_char=None):
+ """Prompt for a password, with echo turned off.
+
+ Args:
+ prompt: Written on stream to ask for the input. Default: 'Password: '
+ stream: A writable file object to display the prompt. Defaults to
+ the tty. If no tty is available defaults to sys.stderr.
+ echo_char: A single ASCII character to mask input (e.g., '*').
+ If None, input is hidden.
+ Returns:
+ The seKr3t input.
+ Raises:
+ EOFError: If our input tty or stdin was closed.
+ GetPassWarning: When we were unable to turn echo off on the input.
+
+ Always restores terminal settings before returning.
+ """
+ _check_echo_char(echo_char)
+
+ passwd = None
+ with contextlib.ExitStack() as stack:
+ try:
+ # Always try reading and writing directly on the tty first.
+ fd = os.open('/dev/tty', os.O_RDWR|os.O_NOCTTY)
+ tty = io.FileIO(fd, 'w+')
+ stack.enter_context(tty)
+ input = io.TextIOWrapper(tty)
+ stack.enter_context(input)
+ if not stream:
+ stream = input
+ except OSError:
+ # If that fails, see if stdin can be controlled.
+ stack.close()
+ try:
+ fd = sys.stdin.fileno()
+ except (AttributeError, ValueError):
+ fd = None
+ passwd = fallback_getpass(prompt, stream)
+ input = sys.stdin
+ if not stream:
+ stream = sys.stderr
+
+ if fd is not None:
+ try:
+ old = termios.tcgetattr(fd) # a copy to save
+ new = old[:]
+ new[3] &= ~termios.ECHO # 3 == 'lflags'
+ if echo_char:
+ new[3] &= ~termios.ICANON
+ tcsetattr_flags = termios.TCSAFLUSH
+ if hasattr(termios, 'TCSASOFT'):
+ tcsetattr_flags |= termios.TCSASOFT
+ try:
+ termios.tcsetattr(fd, tcsetattr_flags, new)
+ passwd = _raw_input(prompt, stream, input=input,
+ echo_char=echo_char)
+
+ finally:
+ termios.tcsetattr(fd, tcsetattr_flags, old)
+ stream.flush() # issue7208
+ except termios.error:
+ if passwd is not None:
+ # _raw_input succeeded. The final tcsetattr failed. Reraise
+ # instead of leaving the terminal in an unknown state.
+ raise
+ # We can't control the tty or stdin. Give up and use normal IO.
+ # fallback_getpass() raises an appropriate warning.
+ if stream is not input:
+ # clean up unused file objects before blocking
+ stack.close()
+ passwd = fallback_getpass(prompt, stream)
+
+ stream.write('\n')
+ return passwd
+
+
+def win_getpass(prompt='Password: ', stream=None, *, echo_char=None):
+ """Prompt for password with echo off, using Windows getwch()."""
+ if sys.stdin is not sys.__stdin__:
+ return fallback_getpass(prompt, stream)
+ _check_echo_char(echo_char)
+
+ for c in prompt:
+ msvcrt.putwch(c)
+ pw = ""
+ while 1:
+ c = msvcrt.getwch()
+ if c == '\r' or c == '\n':
+ break
+ if c == '\003':
+ raise KeyboardInterrupt
+ if c == '\b':
+ if echo_char and pw:
+ msvcrt.putwch('\b')
+ msvcrt.putwch(' ')
+ msvcrt.putwch('\b')
+ pw = pw[:-1]
+ else:
+ pw = pw + c
+ if echo_char:
+ msvcrt.putwch(echo_char)
+ msvcrt.putwch('\r')
+ msvcrt.putwch('\n')
+ return pw
+
+
+def fallback_getpass(prompt='Password: ', stream=None, *, echo_char=None):
+ _check_echo_char(echo_char)
+ import warnings
+ warnings.warn("Can not control echo on the terminal.", GetPassWarning,
+ stacklevel=2)
+ if not stream:
+ stream = sys.stderr
+ print("Warning: Password input may be echoed.", file=stream)
+ return _raw_input(prompt, stream, echo_char=echo_char)
+
+
+def _check_echo_char(echo_char):
+ # Single-character ASCII excluding control characters
+ if echo_char is None:
+ return
+ if not isinstance(echo_char, str):
+ raise TypeError("'echo_char' must be a str or None, not "
+ f"{type(echo_char).__name__}")
+ if not (
+ len(echo_char) == 1
+ and echo_char.isprintable()
+ and echo_char.isascii()
+ ):
+ raise ValueError("'echo_char' must be a single printable ASCII "
+ f"character, got: {echo_char!r}")
+
+
+def _raw_input(prompt="", stream=None, input=None, echo_char=None):
+ # This doesn't save the string in the GNU readline history.
+ if not stream:
+ stream = sys.stderr
+ if not input:
+ input = sys.stdin
+ prompt = str(prompt)
+ if prompt:
+ try:
+ stream.write(prompt)
+ except UnicodeEncodeError:
+ # Use replace error handler to get as much as possible printed.
+ prompt = prompt.encode(stream.encoding, 'replace')
+ prompt = prompt.decode(stream.encoding)
+ stream.write(prompt)
+ stream.flush()
+ # NOTE: The Python C API calls flockfile() (and unlock) during readline.
+ if echo_char:
+ return _readline_with_echo_char(stream, input, echo_char)
+ line = input.readline()
+ if not line:
+ raise EOFError
+ if line[-1] == '\n':
+ line = line[:-1]
+ return line
+
+
+def _readline_with_echo_char(stream, input, echo_char):
+ passwd = ""
+ eof_pressed = False
+ while True:
+ char = input.read(1)
+ if char == '\n' or char == '\r':
+ break
+ elif char == '\x03':
+ raise KeyboardInterrupt
+ elif char == '\x7f' or char == '\b':
+ if passwd:
+ stream.write("\b \b")
+ stream.flush()
+ passwd = passwd[:-1]
+ elif char == '\x04':
+ if eof_pressed:
+ break
+ else:
+ eof_pressed = True
+ elif char == '\x00':
+ continue
+ else:
+ passwd += char
+ stream.write(echo_char)
+ stream.flush()
+ eof_pressed = False
+ return passwd
+
+
+def getuser():
+ """Get the username from the environment or password database.
+
+ First try various environment variables, then the password
+ database. This works on Windows as long as USERNAME is set.
+ Any failure to find a username raises OSError.
+
+ .. versionchanged:: 3.13
+ Previously, various exceptions beyond just :exc:`OSError`
+ were raised.
+ """
+
+ for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
+ user = os.environ.get(name)
+ if user:
+ return user
+
+ try:
+ import pwd
+ return pwd.getpwuid(os.getuid())[0]
+ except (ImportError, KeyError) as e:
+ raise OSError('No username set in the environment') from e
+
+
+# Bind the name getpass to the appropriate function
+try:
+ import termios
+ # it's possible there is an incompatible termios from the
+ # McMillan Installer, make sure we have a UNIX-compatible termios
+ termios.tcgetattr, termios.tcsetattr
+except (ImportError, AttributeError):
+ try:
+ import msvcrt
+ except ImportError:
+ getpass = fallback_getpass
+ else:
+ getpass = win_getpass
+else:
+ getpass = unix_getpass
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/gettext.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/gettext.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c11ab2b1eb57091affba895a6fe8bc34de84ecc
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/gettext.py
@@ -0,0 +1,657 @@
+"""Internationalization and localization support.
+
+This module provides internationalization (I18N) and localization (L10N)
+support for your Python programs by providing an interface to the GNU gettext
+message catalog library.
+
+I18N refers to the operation by which a program is made aware of multiple
+languages. L10N refers to the adaptation of your program, once
+internationalized, to the local language and cultural habits.
+
+"""
+
+# This module represents the integration of work, contributions, feedback, and
+# suggestions from the following people:
+#
+# Martin von Loewis, who wrote the initial implementation of the underlying
+# C-based libintlmodule (later renamed _gettext), along with a skeletal
+# gettext.py implementation.
+#
+# Peter Funk, who wrote fintl.py, a fairly complete wrapper around intlmodule,
+# which also included a pure-Python implementation to read .mo files if
+# intlmodule wasn't available.
+#
+# James Henstridge, who also wrote a gettext.py module, which has some
+# interesting, but currently unsupported experimental features: the notion of
+# a Catalog class and instances, and the ability to add to a catalog file via
+# a Python API.
+#
+# Barry Warsaw integrated these modules, wrote the .install() API and code,
+# and conformed all C and Python code to Python's coding standards.
+#
+# Francois Pinard and Marc-Andre Lemburg also contributed valuably to this
+# module.
+#
+# J. David Ibanez implemented plural forms. Bruno Haible fixed some bugs.
+#
+# TODO:
+# - Lazy loading of .mo files. Currently the entire catalog is loaded into
+# memory, but that's probably bad for large translated programs. Instead,
+# the lexical sort of original strings in GNU .mo files should be exploited
+# to do binary searches and lazy initializations. Or you might want to use
+# the undocumented double-hash algorithm for .mo files with hash tables, but
+# you'll need to study the GNU gettext code to do this.
+
+
+import operator
+import os
+import sys
+
+
+__all__ = ['NullTranslations', 'GNUTranslations', 'Catalog',
+ 'bindtextdomain', 'find', 'translation', 'install',
+ 'textdomain', 'dgettext', 'dngettext', 'gettext',
+ 'ngettext', 'pgettext', 'dpgettext', 'npgettext',
+ 'dnpgettext'
+ ]
+
+_default_localedir = os.path.join(sys.base_prefix, 'share', 'locale')
+
+# Expression parsing for plural form selection.
+#
+# The gettext library supports a small subset of C syntax. The only
+# incompatible difference is that integer literals starting with zero are
+# decimal.
+#
+# https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms
+# http://git.savannah.gnu.org/cgit/gettext.git/tree/gettext-runtime/intl/plural.y
+
+_token_pattern = None
+
+def _tokenize(plural):
+ global _token_pattern
+ if _token_pattern is None:
+ import re
+ _token_pattern = re.compile(r"""
+ (?P[ \t]+) | # spaces and horizontal tabs
+ (?P[0-9]+\b) | # decimal integer
+ (?Pn\b) | # only n is allowed
+ (?P[()]) |
+ (?P[-*/%+?:]|[>,
+ # <=, >=, ==, !=, &&, ||,
+ # ? :
+ # unary and bitwise ops
+ # not allowed
+ (?P\w+|.) # invalid token
+ """, re.VERBOSE|re.DOTALL)
+
+ for mo in _token_pattern.finditer(plural):
+ kind = mo.lastgroup
+ if kind == 'WHITESPACES':
+ continue
+ value = mo.group(kind)
+ if kind == 'INVALID':
+ raise ValueError('invalid token in plural form: %s' % value)
+ yield value
+ yield ''
+
+
+def _error(value):
+ if value:
+ return ValueError('unexpected token in plural form: %s' % value)
+ else:
+ return ValueError('unexpected end of plural form')
+
+
+_binary_ops = (
+ ('||',),
+ ('&&',),
+ ('==', '!='),
+ ('<', '>', '<=', '>='),
+ ('+', '-'),
+ ('*', '/', '%'),
+)
+_binary_ops = {op: i for i, ops in enumerate(_binary_ops, 1) for op in ops}
+_c2py_ops = {'||': 'or', '&&': 'and', '/': '//'}
+
+
+def _parse(tokens, priority=-1):
+ result = ''
+ nexttok = next(tokens)
+ while nexttok == '!':
+ result += 'not '
+ nexttok = next(tokens)
+
+ if nexttok == '(':
+ sub, nexttok = _parse(tokens)
+ result = '%s(%s)' % (result, sub)
+ if nexttok != ')':
+ raise ValueError('unbalanced parenthesis in plural form')
+ elif nexttok == 'n':
+ result = '%s%s' % (result, nexttok)
+ else:
+ try:
+ value = int(nexttok, 10)
+ except ValueError:
+ raise _error(nexttok) from None
+ result = '%s%d' % (result, value)
+ nexttok = next(tokens)
+
+ j = 100
+ while nexttok in _binary_ops:
+ i = _binary_ops[nexttok]
+ if i < priority:
+ break
+ # Break chained comparisons
+ if i in (3, 4) and j in (3, 4): # '==', '!=', '<', '>', '<=', '>='
+ result = '(%s)' % result
+ # Replace some C operators by their Python equivalents
+ op = _c2py_ops.get(nexttok, nexttok)
+ right, nexttok = _parse(tokens, i + 1)
+ result = '%s %s %s' % (result, op, right)
+ j = i
+ if j == priority == 4: # '<', '>', '<=', '>='
+ result = '(%s)' % result
+
+ if nexttok == '?' and priority <= 0:
+ if_true, nexttok = _parse(tokens, 0)
+ if nexttok != ':':
+ raise _error(nexttok)
+ if_false, nexttok = _parse(tokens)
+ result = '%s if %s else %s' % (if_true, result, if_false)
+ if priority == 0:
+ result = '(%s)' % result
+
+ return result, nexttok
+
+
+def _as_int(n):
+ try:
+ round(n)
+ except TypeError:
+ raise TypeError('Plural value must be an integer, got %s' %
+ (n.__class__.__name__,)) from None
+ return _as_int2(n)
+
+def _as_int2(n):
+ try:
+ return operator.index(n)
+ except TypeError:
+ pass
+
+ import warnings
+ frame = sys._getframe(1)
+ stacklevel = 2
+ while frame.f_back is not None and frame.f_globals.get('__name__') == __name__:
+ stacklevel += 1
+ frame = frame.f_back
+ warnings.warn('Plural value must be an integer, got %s' %
+ (n.__class__.__name__,),
+ DeprecationWarning,
+ stacklevel)
+ return n
+
+
+def c2py(plural):
+ """Gets a C expression as used in PO files for plural forms and returns a
+ Python function that implements an equivalent expression.
+ """
+
+ if len(plural) > 1000:
+ raise ValueError('plural form expression is too long')
+ try:
+ result, nexttok = _parse(_tokenize(plural))
+ if nexttok:
+ raise _error(nexttok)
+
+ depth = 0
+ for c in result:
+ if c == '(':
+ depth += 1
+ if depth > 20:
+ # Python compiler limit is about 90.
+ # The most complex example has 2.
+ raise ValueError('plural form expression is too complex')
+ elif c == ')':
+ depth -= 1
+
+ ns = {'_as_int': _as_int, '__name__': __name__}
+ exec('''if True:
+ def func(n):
+ if not isinstance(n, int):
+ n = _as_int(n)
+ return int(%s)
+ ''' % result, ns)
+ return ns['func']
+ except RecursionError:
+ # Recursion error can be raised in _parse() or exec().
+ raise ValueError('plural form expression is too complex')
+
+
+def _expand_lang(loc):
+ import locale
+ loc = locale.normalize(loc)
+ COMPONENT_CODESET = 1 << 0
+ COMPONENT_TERRITORY = 1 << 1
+ COMPONENT_MODIFIER = 1 << 2
+ # split up the locale into its base components
+ mask = 0
+ pos = loc.find('@')
+ if pos >= 0:
+ modifier = loc[pos:]
+ loc = loc[:pos]
+ mask |= COMPONENT_MODIFIER
+ else:
+ modifier = ''
+ pos = loc.find('.')
+ if pos >= 0:
+ codeset = loc[pos:]
+ loc = loc[:pos]
+ mask |= COMPONENT_CODESET
+ else:
+ codeset = ''
+ pos = loc.find('_')
+ if pos >= 0:
+ territory = loc[pos:]
+ loc = loc[:pos]
+ mask |= COMPONENT_TERRITORY
+ else:
+ territory = ''
+ language = loc
+ ret = []
+ for i in range(mask+1):
+ if not (i & ~mask): # if all components for this combo exist ...
+ val = language
+ if i & COMPONENT_TERRITORY: val += territory
+ if i & COMPONENT_CODESET: val += codeset
+ if i & COMPONENT_MODIFIER: val += modifier
+ ret.append(val)
+ ret.reverse()
+ return ret
+
+
+class NullTranslations:
+ def __init__(self, fp=None):
+ self._info = {}
+ self._charset = None
+ self._fallback = None
+ if fp is not None:
+ self._parse(fp)
+
+ def _parse(self, fp):
+ pass
+
+ def add_fallback(self, fallback):
+ if self._fallback:
+ self._fallback.add_fallback(fallback)
+ else:
+ self._fallback = fallback
+
+ def gettext(self, message):
+ if self._fallback:
+ return self._fallback.gettext(message)
+ return message
+
+ def ngettext(self, msgid1, msgid2, n):
+ if self._fallback:
+ return self._fallback.ngettext(msgid1, msgid2, n)
+ n = _as_int2(n)
+ if n == 1:
+ return msgid1
+ else:
+ return msgid2
+
+ def pgettext(self, context, message):
+ if self._fallback:
+ return self._fallback.pgettext(context, message)
+ return message
+
+ def npgettext(self, context, msgid1, msgid2, n):
+ if self._fallback:
+ return self._fallback.npgettext(context, msgid1, msgid2, n)
+ n = _as_int2(n)
+ if n == 1:
+ return msgid1
+ else:
+ return msgid2
+
+ def info(self):
+ return self._info
+
+ def charset(self):
+ return self._charset
+
+ def install(self, names=None):
+ import builtins
+ builtins.__dict__['_'] = self.gettext
+ if names is not None:
+ allowed = {'gettext', 'ngettext', 'npgettext', 'pgettext'}
+ for name in allowed & set(names):
+ builtins.__dict__[name] = getattr(self, name)
+
+
+class GNUTranslations(NullTranslations):
+ # Magic number of .mo files
+ LE_MAGIC = 0x950412de
+ BE_MAGIC = 0xde120495
+
+ # The encoding of a msgctxt and a msgid in a .mo file is
+ # msgctxt + "\x04" + msgid (gettext version >= 0.15)
+ CONTEXT = "%s\x04%s"
+
+ # Acceptable .mo versions
+ VERSIONS = (0, 1)
+
+ def _get_versions(self, version):
+ """Returns a tuple of major version, minor version"""
+ return (version >> 16, version & 0xffff)
+
+ def _parse(self, fp):
+ """Override this method to support alternative .mo formats."""
+ # Delay struct import for speeding up gettext import when .mo files
+ # are not used.
+ from struct import unpack
+ filename = getattr(fp, 'name', '')
+ # Parse the .mo file header, which consists of 5 little endian 32
+ # bit words.
+ self._catalog = catalog = {}
+ self.plural = lambda n: int(n != 1) # germanic plural by default
+ buf = fp.read()
+ buflen = len(buf)
+ # Are we big endian or little endian?
+ magic = unpack('4I', buf[4:20])
+ ii = '>II'
+ else:
+ raise OSError(0, 'Bad magic number', filename)
+
+ major_version, minor_version = self._get_versions(version)
+
+ if major_version not in self.VERSIONS:
+ raise OSError(0, 'Bad version number ' + str(major_version), filename)
+
+ # Now put all messages from the .mo file buffer into the catalog
+ # dictionary.
+ for i in range(0, msgcount):
+ mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
+ mend = moff + mlen
+ tlen, toff = unpack(ii, buf[transidx:transidx+8])
+ tend = toff + tlen
+ if mend < buflen and tend < buflen:
+ msg = buf[moff:mend]
+ tmsg = buf[toff:tend]
+ else:
+ raise OSError(0, 'File is corrupt', filename)
+ # See if we're looking at GNU .mo conventions for metadata
+ if mlen == 0:
+ # Catalog description
+ lastk = None
+ for b_item in tmsg.split(b'\n'):
+ item = b_item.decode().strip()
+ if not item:
+ continue
+ # Skip over comment lines:
+ if item.startswith('#-#-#-#-#') and item.endswith('#-#-#-#-#'):
+ continue
+ k = v = None
+ if ':' in item:
+ k, v = item.split(':', 1)
+ k = k.strip().lower()
+ v = v.strip()
+ self._info[k] = v
+ lastk = k
+ elif lastk:
+ self._info[lastk] += '\n' + item
+ if k == 'content-type':
+ self._charset = v.split('charset=')[1]
+ elif k == 'plural-forms':
+ v = v.split(';')
+ plural = v[1].split('plural=')[1]
+ self.plural = c2py(plural)
+ # Note: we unconditionally convert both msgids and msgstrs to
+ # Unicode using the character encoding specified in the charset
+ # parameter of the Content-Type header. The gettext documentation
+ # strongly encourages msgids to be us-ascii, but some applications
+ # require alternative encodings (e.g. Zope's ZCML and ZPT). For
+ # traditional gettext applications, the msgid conversion will
+ # cause no problems since us-ascii should always be a subset of
+ # the charset encoding. We may want to fall back to 8-bit msgids
+ # if the Unicode conversion fails.
+ charset = self._charset or 'ascii'
+ if b'\x00' in msg:
+ # Plural forms
+ msgid1, msgid2 = msg.split(b'\x00')
+ tmsg = tmsg.split(b'\x00')
+ msgid1 = str(msgid1, charset)
+ for i, x in enumerate(tmsg):
+ catalog[(msgid1, i)] = str(x, charset)
+ else:
+ catalog[str(msg, charset)] = str(tmsg, charset)
+ # advance to next entry in the seek tables
+ masteridx += 8
+ transidx += 8
+
+ def gettext(self, message):
+ missing = object()
+ tmsg = self._catalog.get(message, missing)
+ if tmsg is missing:
+ tmsg = self._catalog.get((message, self.plural(1)), missing)
+ if tmsg is not missing:
+ return tmsg
+ if self._fallback:
+ return self._fallback.gettext(message)
+ return message
+
+ def ngettext(self, msgid1, msgid2, n):
+ try:
+ tmsg = self._catalog[(msgid1, self.plural(n))]
+ except KeyError:
+ if self._fallback:
+ return self._fallback.ngettext(msgid1, msgid2, n)
+ if n == 1:
+ tmsg = msgid1
+ else:
+ tmsg = msgid2
+ return tmsg
+
+ def pgettext(self, context, message):
+ ctxt_msg_id = self.CONTEXT % (context, message)
+ missing = object()
+ tmsg = self._catalog.get(ctxt_msg_id, missing)
+ if tmsg is missing:
+ tmsg = self._catalog.get((ctxt_msg_id, self.plural(1)), missing)
+ if tmsg is not missing:
+ return tmsg
+ if self._fallback:
+ return self._fallback.pgettext(context, message)
+ return message
+
+ def npgettext(self, context, msgid1, msgid2, n):
+ ctxt_msg_id = self.CONTEXT % (context, msgid1)
+ try:
+ tmsg = self._catalog[ctxt_msg_id, self.plural(n)]
+ except KeyError:
+ if self._fallback:
+ return self._fallback.npgettext(context, msgid1, msgid2, n)
+ if n == 1:
+ tmsg = msgid1
+ else:
+ tmsg = msgid2
+ return tmsg
+
+
+# Locate a .mo file using the gettext strategy
+def find(domain, localedir=None, languages=None, all=False):
+ # Get some reasonable defaults for arguments that were not supplied
+ if localedir is None:
+ localedir = _default_localedir
+ if languages is None:
+ languages = []
+ for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
+ val = os.environ.get(envar)
+ if val:
+ languages = val.split(':')
+ break
+ if 'C' not in languages:
+ languages.append('C')
+ # now normalize and expand the languages
+ nelangs = []
+ for lang in languages:
+ for nelang in _expand_lang(lang):
+ if nelang not in nelangs:
+ nelangs.append(nelang)
+ # select a language
+ if all:
+ result = []
+ else:
+ result = None
+ for lang in nelangs:
+ if lang == 'C':
+ break
+ mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
+ if os.path.exists(mofile):
+ if all:
+ result.append(mofile)
+ else:
+ return mofile
+ return result
+
+
+# a mapping between absolute .mo file path and Translation object
+_translations = {}
+
+
+def translation(domain, localedir=None, languages=None,
+ class_=None, fallback=False):
+ if class_ is None:
+ class_ = GNUTranslations
+ mofiles = find(domain, localedir, languages, all=True)
+ if not mofiles:
+ if fallback:
+ return NullTranslations()
+ from errno import ENOENT
+ raise FileNotFoundError(ENOENT,
+ 'No translation file found for domain', domain)
+ # Avoid opening, reading, and parsing the .mo file after it's been done
+ # once.
+ result = None
+ for mofile in mofiles:
+ key = (class_, os.path.abspath(mofile))
+ t = _translations.get(key)
+ if t is None:
+ with open(mofile, 'rb') as fp:
+ t = _translations.setdefault(key, class_(fp))
+ # Copy the translation object to allow setting fallbacks and
+ # output charset. All other instance data is shared with the
+ # cached object.
+ # Delay copy import for speeding up gettext import when .mo files
+ # are not used.
+ import copy
+ t = copy.copy(t)
+ if result is None:
+ result = t
+ else:
+ result.add_fallback(t)
+ return result
+
+
+def install(domain, localedir=None, *, names=None):
+ t = translation(domain, localedir, fallback=True)
+ t.install(names)
+
+
+# a mapping b/w domains and locale directories
+_localedirs = {}
+# current global domain, `messages' used for compatibility w/ GNU gettext
+_current_domain = 'messages'
+
+
+def textdomain(domain=None):
+ global _current_domain
+ if domain is not None:
+ _current_domain = domain
+ return _current_domain
+
+
+def bindtextdomain(domain, localedir=None):
+ global _localedirs
+ if localedir is not None:
+ _localedirs[domain] = localedir
+ return _localedirs.get(domain, _default_localedir)
+
+
+def dgettext(domain, message):
+ try:
+ t = translation(domain, _localedirs.get(domain, None))
+ except OSError:
+ return message
+ return t.gettext(message)
+
+
+def dngettext(domain, msgid1, msgid2, n):
+ try:
+ t = translation(domain, _localedirs.get(domain, None))
+ except OSError:
+ n = _as_int2(n)
+ if n == 1:
+ return msgid1
+ else:
+ return msgid2
+ return t.ngettext(msgid1, msgid2, n)
+
+
+def dpgettext(domain, context, message):
+ try:
+ t = translation(domain, _localedirs.get(domain, None))
+ except OSError:
+ return message
+ return t.pgettext(context, message)
+
+
+def dnpgettext(domain, context, msgid1, msgid2, n):
+ try:
+ t = translation(domain, _localedirs.get(domain, None))
+ except OSError:
+ n = _as_int2(n)
+ if n == 1:
+ return msgid1
+ else:
+ return msgid2
+ return t.npgettext(context, msgid1, msgid2, n)
+
+
+def gettext(message):
+ return dgettext(_current_domain, message)
+
+
+def ngettext(msgid1, msgid2, n):
+ return dngettext(_current_domain, msgid1, msgid2, n)
+
+
+def pgettext(context, message):
+ return dpgettext(_current_domain, context, message)
+
+
+def npgettext(context, msgid1, msgid2, n):
+ return dnpgettext(_current_domain, context, msgid1, msgid2, n)
+
+
+# dcgettext() has been deemed unnecessary and is not implemented.
+
+# James Henstridge's Catalog constructor from GNOME gettext. Documented usage
+# was:
+#
+# import gettext
+# cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
+# _ = cat.gettext
+# print(_('Hello World'))
+
+# The resulting catalog object currently don't support access through a
+# dictionary API, which was supported (but apparently unused) in GNOME
+# gettext.
+
+Catalog = translation
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/glob.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/glob.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ce3998c27ce337945d43c36e725fcf0609e05e8
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/glob.py
@@ -0,0 +1,574 @@
+"""Filename globbing utility."""
+
+import contextlib
+import os
+import re
+import fnmatch
+import functools
+import itertools
+import operator
+import stat
+import sys
+
+
+__all__ = ["glob", "iglob", "escape", "translate"]
+
+def glob(pathname, *, root_dir=None, dir_fd=None, recursive=False,
+ include_hidden=False):
+ """Return a list of paths matching a `pathname` pattern.
+
+ The pattern may contain simple shell-style wildcards a la
+ fnmatch. Unlike fnmatch, filenames starting with a
+ dot are special cases that are not matched by '*' and '?'
+ patterns by default.
+
+ The order of the returned list is undefined. Sort it if you need a
+ particular order.
+
+ If `root_dir` is not None, it should be a path-like object specifying the
+ root directory for searching. It has the same effect as changing the
+ current directory before calling it (without actually
+ changing it). If pathname is relative, the result will contain
+ paths relative to `root_dir`.
+
+ If `dir_fd` is not None, it should be a file descriptor referring to a
+ directory, and paths will then be relative to that directory.
+
+ If `include_hidden` is true, the patterns '*', '?', '**' will match hidden
+ directories.
+
+ If `recursive` is true, the pattern '**' will match any files and
+ zero or more directories and subdirectories.
+ """
+ return list(iglob(pathname, root_dir=root_dir, dir_fd=dir_fd, recursive=recursive,
+ include_hidden=include_hidden))
+
+def iglob(pathname, *, root_dir=None, dir_fd=None, recursive=False,
+ include_hidden=False):
+ """Return an iterator which yields the paths matching a `pathname` pattern.
+
+ The pattern may contain simple shell-style wildcards a la
+ fnmatch. However, unlike fnmatch, filenames starting with a
+ dot are special cases that are not matched by '*' and '?'
+ patterns.
+
+ The order of the returned paths is undefined. Sort them if you need a
+ particular order.
+
+ If `root_dir` is not None, it should be a path-like object specifying
+ the root directory for searching. It has the same effect as changing
+ the current directory before calling it (without actually
+ changing it). If pathname is relative, the result will contain
+ paths relative to `root_dir`.
+
+ If `dir_fd` is not None, it should be a file descriptor referring to a
+ directory, and paths will then be relative to that directory.
+
+ If `include_hidden` is true, the patterns '*', '?', '**' will match hidden
+ directories.
+
+ If `recursive` is true, the pattern '**' will match any files and
+ zero or more directories and subdirectories.
+ """
+ sys.audit("glob.glob", pathname, recursive)
+ sys.audit("glob.glob/2", pathname, recursive, root_dir, dir_fd)
+ if root_dir is not None:
+ root_dir = os.fspath(root_dir)
+ else:
+ root_dir = pathname[:0]
+ it = _iglob(pathname, root_dir, dir_fd, recursive, False,
+ include_hidden=include_hidden)
+ if not pathname or recursive and _isrecursive(pathname[:2]):
+ try:
+ s = next(it) # skip empty string
+ if s:
+ it = itertools.chain((s,), it)
+ except StopIteration:
+ pass
+ return it
+
+def _iglob(pathname, root_dir, dir_fd, recursive, dironly,
+ include_hidden=False):
+ dirname, basename = os.path.split(pathname)
+ if not has_magic(pathname):
+ assert not dironly
+ if basename:
+ if _lexists(_join(root_dir, pathname), dir_fd):
+ yield pathname
+ else:
+ # Patterns ending with a slash should match only directories
+ if _isdir(_join(root_dir, dirname), dir_fd):
+ yield pathname
+ return
+ if not dirname:
+ if recursive and _isrecursive(basename):
+ yield from _glob2(root_dir, basename, dir_fd, dironly,
+ include_hidden=include_hidden)
+ else:
+ yield from _glob1(root_dir, basename, dir_fd, dironly,
+ include_hidden=include_hidden)
+ return
+ # `os.path.split()` returns the argument itself as a dirname if it is a
+ # drive or UNC path. Prevent an infinite recursion if a drive or UNC path
+ # contains magic characters (i.e. r'\\?\C:').
+ if dirname != pathname and has_magic(dirname):
+ dirs = _iglob(dirname, root_dir, dir_fd, recursive, True,
+ include_hidden=include_hidden)
+ else:
+ dirs = [dirname]
+ if has_magic(basename):
+ if recursive and _isrecursive(basename):
+ glob_in_dir = _glob2
+ else:
+ glob_in_dir = _glob1
+ else:
+ glob_in_dir = _glob0
+ for dirname in dirs:
+ for name in glob_in_dir(_join(root_dir, dirname), basename, dir_fd, dironly,
+ include_hidden=include_hidden):
+ yield os.path.join(dirname, name)
+
+# These 2 helper functions non-recursively glob inside a literal directory.
+# They return a list of basenames. _glob1 accepts a pattern while _glob0
+# takes a literal basename (so it only has to check for its existence).
+
+def _glob1(dirname, pattern, dir_fd, dironly, include_hidden=False):
+ names = _listdir(dirname, dir_fd, dironly)
+ if not (include_hidden or _ishidden(pattern)):
+ names = (x for x in names if not _ishidden(x))
+ return fnmatch.filter(names, pattern)
+
+def _glob0(dirname, basename, dir_fd, dironly, include_hidden=False):
+ if basename:
+ if _lexists(_join(dirname, basename), dir_fd):
+ return [basename]
+ else:
+ # `os.path.split()` returns an empty basename for paths ending with a
+ # directory separator. 'q*x/' should match only directories.
+ if _isdir(dirname, dir_fd):
+ return [basename]
+ return []
+
+_deprecated_function_message = (
+ "{name} is deprecated and will be removed in Python {remove}. Use "
+ "glob.glob and pass a directory to its root_dir argument instead."
+)
+
+def glob0(dirname, pattern):
+ import warnings
+ warnings._deprecated("glob.glob0", _deprecated_function_message, remove=(3, 15))
+ return _glob0(dirname, pattern, None, False)
+
+def glob1(dirname, pattern):
+ import warnings
+ warnings._deprecated("glob.glob1", _deprecated_function_message, remove=(3, 15))
+ return _glob1(dirname, pattern, None, False)
+
+# This helper function recursively yields relative pathnames inside a literal
+# directory.
+
+def _glob2(dirname, pattern, dir_fd, dironly, include_hidden=False):
+ assert _isrecursive(pattern)
+ if not dirname or _isdir(dirname, dir_fd):
+ yield pattern[:0]
+ yield from _rlistdir(dirname, dir_fd, dironly,
+ include_hidden=include_hidden)
+
+# If dironly is false, yields all file names inside a directory.
+# If dironly is true, yields only directory names.
+def _iterdir(dirname, dir_fd, dironly):
+ try:
+ fd = None
+ fsencode = None
+ if dir_fd is not None:
+ if dirname:
+ fd = arg = os.open(dirname, _dir_open_flags, dir_fd=dir_fd)
+ else:
+ arg = dir_fd
+ if isinstance(dirname, bytes):
+ fsencode = os.fsencode
+ elif dirname:
+ arg = dirname
+ elif isinstance(dirname, bytes):
+ arg = bytes(os.curdir, 'ASCII')
+ else:
+ arg = os.curdir
+ try:
+ with os.scandir(arg) as it:
+ for entry in it:
+ try:
+ if not dironly or entry.is_dir():
+ if fsencode is not None:
+ yield fsencode(entry.name)
+ else:
+ yield entry.name
+ except OSError:
+ pass
+ finally:
+ if fd is not None:
+ os.close(fd)
+ except OSError:
+ return
+
+def _listdir(dirname, dir_fd, dironly):
+ with contextlib.closing(_iterdir(dirname, dir_fd, dironly)) as it:
+ return list(it)
+
+# Recursively yields relative pathnames inside a literal directory.
+def _rlistdir(dirname, dir_fd, dironly, include_hidden=False):
+ names = _listdir(dirname, dir_fd, dironly)
+ for x in names:
+ if include_hidden or not _ishidden(x):
+ yield x
+ path = _join(dirname, x) if dirname else x
+ for y in _rlistdir(path, dir_fd, dironly,
+ include_hidden=include_hidden):
+ yield _join(x, y)
+
+
+def _lexists(pathname, dir_fd):
+ # Same as os.path.lexists(), but with dir_fd
+ if dir_fd is None:
+ return os.path.lexists(pathname)
+ try:
+ os.lstat(pathname, dir_fd=dir_fd)
+ except (OSError, ValueError):
+ return False
+ else:
+ return True
+
+def _isdir(pathname, dir_fd):
+ # Same as os.path.isdir(), but with dir_fd
+ if dir_fd is None:
+ return os.path.isdir(pathname)
+ try:
+ st = os.stat(pathname, dir_fd=dir_fd)
+ except (OSError, ValueError):
+ return False
+ else:
+ return stat.S_ISDIR(st.st_mode)
+
+def _join(dirname, basename):
+ # It is common if dirname or basename is empty
+ if not dirname or not basename:
+ return dirname or basename
+ return os.path.join(dirname, basename)
+
+magic_check = re.compile('([*?[])')
+magic_check_bytes = re.compile(b'([*?[])')
+
+def has_magic(s):
+ if isinstance(s, bytes):
+ match = magic_check_bytes.search(s)
+ else:
+ match = magic_check.search(s)
+ return match is not None
+
+def _ishidden(path):
+ return path[0] in ('.', b'.'[0])
+
+def _isrecursive(pattern):
+ if isinstance(pattern, bytes):
+ return pattern == b'**'
+ else:
+ return pattern == '**'
+
+def escape(pathname):
+ """Escape all special characters.
+ """
+ # Escaping is done by wrapping any of "*?[" between square brackets.
+ # Metacharacters do not work in the drive part and shouldn't be escaped.
+ drive, pathname = os.path.splitdrive(pathname)
+ if isinstance(pathname, bytes):
+ pathname = magic_check_bytes.sub(br'[\1]', pathname)
+ else:
+ pathname = magic_check.sub(r'[\1]', pathname)
+ return drive + pathname
+
+
+_special_parts = ('', '.', '..')
+_dir_open_flags = os.O_RDONLY | getattr(os, 'O_DIRECTORY', 0)
+_no_recurse_symlinks = object()
+
+
+def translate(pat, *, recursive=False, include_hidden=False, seps=None):
+ """Translate a pathname with shell wildcards to a regular expression.
+
+ If `recursive` is true, the pattern segment '**' will match any number of
+ path segments.
+
+ If `include_hidden` is true, wildcards can match path segments beginning
+ with a dot ('.').
+
+ If a sequence of separator characters is given to `seps`, they will be
+ used to split the pattern into segments and match path separators. If not
+ given, os.path.sep and os.path.altsep (where available) are used.
+ """
+ if not seps:
+ if os.path.altsep:
+ seps = (os.path.sep, os.path.altsep)
+ else:
+ seps = os.path.sep
+ escaped_seps = ''.join(map(re.escape, seps))
+ any_sep = f'[{escaped_seps}]' if len(seps) > 1 else escaped_seps
+ not_sep = f'[^{escaped_seps}]'
+ if include_hidden:
+ one_last_segment = f'{not_sep}+'
+ one_segment = f'{one_last_segment}{any_sep}'
+ any_segments = f'(?:.+{any_sep})?'
+ any_last_segments = '.*'
+ else:
+ one_last_segment = f'[^{escaped_seps}.]{not_sep}*'
+ one_segment = f'{one_last_segment}{any_sep}'
+ any_segments = f'(?:{one_segment})*'
+ any_last_segments = f'{any_segments}(?:{one_last_segment})?'
+
+ results = []
+ parts = re.split(any_sep, pat)
+ last_part_idx = len(parts) - 1
+ for idx, part in enumerate(parts):
+ if part == '*':
+ results.append(one_segment if idx < last_part_idx else one_last_segment)
+ elif recursive and part == '**':
+ if idx < last_part_idx:
+ if parts[idx + 1] != '**':
+ results.append(any_segments)
+ else:
+ results.append(any_last_segments)
+ else:
+ if part:
+ if not include_hidden and part[0] in '*?':
+ results.append(r'(?!\.)')
+ results.extend(fnmatch._translate(part, f'{not_sep}*', not_sep)[0])
+ if idx < last_part_idx:
+ results.append(any_sep)
+ res = ''.join(results)
+ return fr'(?s:{res})\z'
+
+
+@functools.lru_cache(maxsize=512)
+def _compile_pattern(pat, seps, case_sensitive, recursive=True):
+ """Compile given glob pattern to a re.Pattern object (observing case
+ sensitivity)."""
+ flags = re.NOFLAG if case_sensitive else re.IGNORECASE
+ regex = translate(pat, recursive=recursive, include_hidden=True, seps=seps)
+ return re.compile(regex, flags=flags).match
+
+
+class _GlobberBase:
+ """Abstract class providing shell-style pattern matching and globbing.
+ """
+
+ def __init__(self, sep, case_sensitive, case_pedantic=False, recursive=False):
+ self.sep = sep
+ self.case_sensitive = case_sensitive
+ self.case_pedantic = case_pedantic
+ self.recursive = recursive
+
+ # Abstract methods
+
+ @staticmethod
+ def lexists(path):
+ """Implements os.path.lexists().
+ """
+ raise NotImplementedError
+
+ @staticmethod
+ def scandir(path):
+ """Like os.scandir(), but generates (entry, name, path) tuples.
+ """
+ raise NotImplementedError
+
+ @staticmethod
+ def concat_path(path, text):
+ """Implements path concatenation.
+ """
+ raise NotImplementedError
+
+ # High-level methods
+
+ def compile(self, pat, altsep=None):
+ seps = (self.sep, altsep) if altsep else self.sep
+ return _compile_pattern(pat, seps, self.case_sensitive, self.recursive)
+
+ def selector(self, parts):
+ """Returns a function that selects from a given path, walking and
+ filtering according to the glob-style pattern parts in *parts*.
+ """
+ if not parts:
+ return self.select_exists
+ part = parts.pop()
+ if self.recursive and part == '**':
+ selector = self.recursive_selector
+ elif part in _special_parts:
+ selector = self.special_selector
+ elif not self.case_pedantic and magic_check.search(part) is None:
+ selector = self.literal_selector
+ else:
+ selector = self.wildcard_selector
+ return selector(part, parts)
+
+ def special_selector(self, part, parts):
+ """Returns a function that selects special children of the given path.
+ """
+ if parts:
+ part += self.sep
+ select_next = self.selector(parts)
+
+ def select_special(path, exists=False):
+ path = self.concat_path(path, part)
+ return select_next(path, exists)
+ return select_special
+
+ def literal_selector(self, part, parts):
+ """Returns a function that selects a literal descendant of a path.
+ """
+
+ # Optimization: consume and join any subsequent literal parts here,
+ # rather than leaving them for the next selector. This reduces the
+ # number of string concatenation operations.
+ while parts and magic_check.search(parts[-1]) is None:
+ part += self.sep + parts.pop()
+ if parts:
+ part += self.sep
+
+ select_next = self.selector(parts)
+
+ def select_literal(path, exists=False):
+ path = self.concat_path(path, part)
+ return select_next(path, exists=False)
+ return select_literal
+
+ def wildcard_selector(self, part, parts):
+ """Returns a function that selects direct children of a given path,
+ filtering by pattern.
+ """
+
+ match = None if part == '*' else self.compile(part)
+ dir_only = bool(parts)
+ if dir_only:
+ select_next = self.selector(parts)
+
+ def select_wildcard(path, exists=False):
+ try:
+ entries = self.scandir(path)
+ except OSError:
+ pass
+ else:
+ for entry, entry_name, entry_path in entries:
+ if match is None or match(entry_name):
+ if dir_only:
+ try:
+ if not entry.is_dir():
+ continue
+ except OSError:
+ continue
+ entry_path = self.concat_path(entry_path, self.sep)
+ yield from select_next(entry_path, exists=True)
+ else:
+ yield entry_path
+ return select_wildcard
+
+ def recursive_selector(self, part, parts):
+ """Returns a function that selects a given path and all its children,
+ recursively, filtering by pattern.
+ """
+ # Optimization: consume following '**' parts, which have no effect.
+ while parts and parts[-1] == '**':
+ parts.pop()
+
+ # Optimization: consume and join any following non-special parts here,
+ # rather than leaving them for the next selector. They're used to
+ # build a regular expression, which we use to filter the results of
+ # the recursive walk. As a result, non-special pattern segments
+ # following a '**' wildcard don't require additional filesystem access
+ # to expand.
+ follow_symlinks = self.recursive is not _no_recurse_symlinks
+ if follow_symlinks:
+ while parts and parts[-1] not in _special_parts:
+ part += self.sep + parts.pop()
+
+ match = None if part == '**' else self.compile(part)
+ dir_only = bool(parts)
+ select_next = self.selector(parts)
+
+ def select_recursive(path, exists=False):
+ match_pos = len(str(path))
+ if match is None or match(str(path), match_pos):
+ yield from select_next(path, exists)
+ stack = [path]
+ while stack:
+ yield from select_recursive_step(stack, match_pos)
+
+ def select_recursive_step(stack, match_pos):
+ path = stack.pop()
+ try:
+ entries = self.scandir(path)
+ except OSError:
+ pass
+ else:
+ for entry, _entry_name, entry_path in entries:
+ is_dir = False
+ try:
+ if entry.is_dir(follow_symlinks=follow_symlinks):
+ is_dir = True
+ except OSError:
+ pass
+
+ if is_dir or not dir_only:
+ entry_path_str = str(entry_path)
+ if dir_only:
+ entry_path = self.concat_path(entry_path, self.sep)
+ if match is None or match(entry_path_str, match_pos):
+ if dir_only:
+ yield from select_next(entry_path, exists=True)
+ else:
+ # Optimization: directly yield the path if this is
+ # last pattern part.
+ yield entry_path
+ if is_dir:
+ stack.append(entry_path)
+
+ return select_recursive
+
+ def select_exists(self, path, exists=False):
+ """Yields the given path, if it exists.
+ """
+ if exists:
+ # Optimization: this path is already known to exist, e.g. because
+ # it was returned from os.scandir(), so we skip calling lstat().
+ yield path
+ elif self.lexists(path):
+ yield path
+
+
+class _StringGlobber(_GlobberBase):
+ """Provides shell-style pattern matching and globbing for string paths.
+ """
+ lexists = staticmethod(os.path.lexists)
+ concat_path = operator.add
+
+ @staticmethod
+ def scandir(path):
+ # We must close the scandir() object before proceeding to
+ # avoid exhausting file descriptors when globbing deep trees.
+ with os.scandir(path) as scandir_it:
+ entries = list(scandir_it)
+ return ((entry, entry.name, entry.path) for entry in entries)
+
+
+class _PathGlobber(_GlobberBase):
+ """Provides shell-style pattern matching and globbing for pathlib paths.
+ """
+
+ @staticmethod
+ def lexists(path):
+ return path.info.exists(follow_symlinks=False)
+
+ @staticmethod
+ def scandir(path):
+ return ((child.info, child.name, child) for child in path.iterdir())
+
+ @staticmethod
+ def concat_path(path, text):
+ return path.with_segments(str(path) + text)
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/graphlib.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/graphlib.py
new file mode 100644
index 0000000000000000000000000000000000000000..7961c9c5cac2d66d04082bbf34e98b5438100ccc
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/graphlib.py
@@ -0,0 +1,254 @@
+from types import GenericAlias
+
+__all__ = ["TopologicalSorter", "CycleError"]
+
+_NODE_OUT = -1
+_NODE_DONE = -2
+
+
+class _NodeInfo:
+ __slots__ = "node", "npredecessors", "successors"
+
+ def __init__(self, node):
+ # The node this class is augmenting.
+ self.node = node
+
+ # Number of predecessors, generally >= 0. When this value falls to 0,
+ # and is returned by get_ready(), this is set to _NODE_OUT and when the
+ # node is marked done by a call to done(), set to _NODE_DONE.
+ self.npredecessors = 0
+
+ # List of successor nodes. The list can contain duplicated elements as
+ # long as they're all reflected in the successor's npredecessors attribute.
+ self.successors = []
+
+
+class CycleError(ValueError):
+ """Subclass of ValueError raised by TopologicalSorter.prepare if cycles
+ exist in the working graph.
+
+ If multiple cycles exist, only one undefined choice among them will be reported
+ and included in the exception. The detected cycle can be accessed via the second
+ element in the *args* attribute of the exception instance and consists in a list
+ of nodes, such that each node is, in the graph, an immediate predecessor of the
+ next node in the list. In the reported list, the first and the last node will be
+ the same, to make it clear that it is cyclic.
+ """
+
+ pass
+
+
+class TopologicalSorter:
+ """Provides functionality to topologically sort a graph of hashable nodes"""
+
+ def __init__(self, graph=None):
+ self._node2info = {}
+ self._ready_nodes = None
+ self._npassedout = 0
+ self._nfinished = 0
+
+ if graph is not None:
+ for node, predecessors in graph.items():
+ self.add(node, *predecessors)
+
+ def _get_nodeinfo(self, node):
+ if (result := self._node2info.get(node)) is None:
+ self._node2info[node] = result = _NodeInfo(node)
+ return result
+
+ def add(self, node, *predecessors):
+ """Add a new node and its predecessors to the graph.
+
+ Both the *node* and all elements in *predecessors* must be hashable.
+
+ If called multiple times with the same node argument, the set of dependencies
+ will be the union of all dependencies passed in.
+
+ It is possible to add a node with no dependencies (*predecessors* is not provided)
+ as well as provide a dependency twice. If a node that has not been provided before
+ is included among *predecessors* it will be automatically added to the graph with
+ no predecessors of its own.
+
+ Raises ValueError if called after "prepare".
+ """
+ if self._ready_nodes is not None:
+ raise ValueError("Nodes cannot be added after a call to prepare()")
+
+ # Create the node -> predecessor edges
+ nodeinfo = self._get_nodeinfo(node)
+ nodeinfo.npredecessors += len(predecessors)
+
+ # Create the predecessor -> node edges
+ for pred in predecessors:
+ pred_info = self._get_nodeinfo(pred)
+ pred_info.successors.append(node)
+
+ def prepare(self):
+ """Mark the graph as finished and check for cycles in the graph.
+
+ If any cycle is detected, "CycleError" will be raised, but "get_ready" can
+ still be used to obtain as many nodes as possible until cycles block more
+ progress. After a call to this function, the graph cannot be modified and
+ therefore no more nodes can be added using "add".
+
+ Raise ValueError if nodes have already been passed out of the sorter.
+
+ """
+ if self._npassedout > 0:
+ raise ValueError("cannot prepare() after starting sort")
+
+ if self._ready_nodes is None:
+ self._ready_nodes = [
+ i.node for i in self._node2info.values() if i.npredecessors == 0
+ ]
+ # ready_nodes is set before we look for cycles on purpose:
+ # if the user wants to catch the CycleError, that's fine,
+ # they can continue using the instance to grab as many
+ # nodes as possible before cycles block more progress
+ cycle = self._find_cycle()
+ if cycle:
+ raise CycleError("nodes are in a cycle", cycle)
+
+ def get_ready(self):
+ """Return a tuple of all the nodes that are ready.
+
+ Initially it returns all nodes with no predecessors; once those are marked
+ as processed by calling "done", further calls will return all new nodes that
+ have all their predecessors already processed. Once no more progress can be made,
+ empty tuples are returned.
+
+ Raises ValueError if called without calling "prepare" previously.
+ """
+ if self._ready_nodes is None:
+ raise ValueError("prepare() must be called first")
+
+ # Get the nodes that are ready and mark them
+ result = tuple(self._ready_nodes)
+ n2i = self._node2info
+ for node in result:
+ n2i[node].npredecessors = _NODE_OUT
+
+ # Clean the list of nodes that are ready and update
+ # the counter of nodes that we have returned.
+ self._ready_nodes.clear()
+ self._npassedout += len(result)
+
+ return result
+
+ def is_active(self):
+ """Return ``True`` if more progress can be made and ``False`` otherwise.
+
+ Progress can be made if cycles do not block the resolution and either there
+ are still nodes ready that haven't yet been returned by "get_ready" or the
+ number of nodes marked "done" is less than the number that have been returned
+ by "get_ready".
+
+ Raises ValueError if called without calling "prepare" previously.
+ """
+ if self._ready_nodes is None:
+ raise ValueError("prepare() must be called first")
+ return self._nfinished < self._npassedout or bool(self._ready_nodes)
+
+ def __bool__(self):
+ return self.is_active()
+
+ def done(self, *nodes):
+ """Marks a set of nodes returned by "get_ready" as processed.
+
+ This method unblocks any successor of each node in *nodes* for being returned
+ in the future by a call to "get_ready".
+
+ Raises ValueError if any node in *nodes* has already been marked as
+ processed by a previous call to this method, if a node was not added to the
+ graph by using "add" or if called without calling "prepare" previously or if
+ node has not yet been returned by "get_ready".
+ """
+
+ if self._ready_nodes is None:
+ raise ValueError("prepare() must be called first")
+
+ n2i = self._node2info
+
+ for node in nodes:
+
+ # Check if we know about this node (it was added previously using add()
+ if (nodeinfo := n2i.get(node)) is None:
+ raise ValueError(f"node {node!r} was not added using add()")
+
+ # If the node has not being returned (marked as ready) previously, inform the user.
+ stat = nodeinfo.npredecessors
+ if stat != _NODE_OUT:
+ if stat >= 0:
+ raise ValueError(
+ f"node {node!r} was not passed out (still not ready)"
+ )
+ elif stat == _NODE_DONE:
+ raise ValueError(f"node {node!r} was already marked done")
+ else:
+ assert False, f"node {node!r}: unknown status {stat}"
+
+ # Mark the node as processed
+ nodeinfo.npredecessors = _NODE_DONE
+
+ # Go to all the successors and reduce the number of predecessors, collecting all the ones
+ # that are ready to be returned in the next get_ready() call.
+ for successor in nodeinfo.successors:
+ successor_info = n2i[successor]
+ successor_info.npredecessors -= 1
+ if successor_info.npredecessors == 0:
+ self._ready_nodes.append(successor)
+ self._nfinished += 1
+
+ def _find_cycle(self):
+ n2i = self._node2info
+ stack = []
+ itstack = []
+ seen = set()
+ node2stacki = {}
+
+ for node in n2i:
+ if node in seen:
+ continue
+
+ while True:
+ if node in seen:
+ # If we have seen already the node and is in the
+ # current stack we have found a cycle.
+ if node in node2stacki:
+ return stack[node2stacki[node] :] + [node]
+ # else go on to get next successor
+ else:
+ seen.add(node)
+ itstack.append(iter(n2i[node].successors).__next__)
+ node2stacki[node] = len(stack)
+ stack.append(node)
+
+ # Backtrack to the topmost stack entry with
+ # at least another successor.
+ while stack:
+ try:
+ node = itstack[-1]()
+ break
+ except StopIteration:
+ del node2stacki[stack.pop()]
+ itstack.pop()
+ else:
+ break
+ return None
+
+ def static_order(self):
+ """Returns an iterable of nodes in a topological order.
+
+ The particular order that is returned may depend on the specific
+ order in which the items were inserted in the graph.
+
+ Using this method does not require to call "prepare" or "done". If any
+ cycle is detected, :exc:`CycleError` will be raised.
+ """
+ self.prepare()
+ while self.is_active():
+ node_group = self.get_ready()
+ yield from node_group
+ self.done(*node_group)
+
+ __class_getitem__ = classmethod(GenericAlias)
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/gzip.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/gzip.py
new file mode 100644
index 0000000000000000000000000000000000000000..c00f51858de0f0d5f04d6b54641cc4147e81a165
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/gzip.py
@@ -0,0 +1,717 @@
+"""Functions that read and write gzipped files.
+
+The user of the file doesn't have to worry about the compression,
+but random access is not allowed."""
+
+# based on Andrew Kuchling's minigzip.py distributed with the zlib module
+
+import builtins
+import io
+import os
+import struct
+import sys
+import time
+import weakref
+import zlib
+from compression._common import _streams
+
+__all__ = ["BadGzipFile", "GzipFile", "open", "compress", "decompress"]
+
+FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16
+
+READ = 'rb'
+WRITE = 'wb'
+
+_COMPRESS_LEVEL_FAST = 1
+_COMPRESS_LEVEL_TRADEOFF = 6
+_COMPRESS_LEVEL_BEST = 9
+
+READ_BUFFER_SIZE = 128 * 1024
+_WRITE_BUFFER_SIZE = 4 * io.DEFAULT_BUFFER_SIZE
+
+
+def open(filename, mode="rb", compresslevel=_COMPRESS_LEVEL_BEST,
+ encoding=None, errors=None, newline=None):
+ """Open a gzip-compressed file in binary or text mode.
+
+ The filename argument can be an actual filename (a str or bytes object), or
+ an existing file object to read from or write to.
+
+ The mode argument can be "r", "rb", "w", "wb", "x", "xb", "a" or "ab" for
+ binary mode, or "rt", "wt", "xt" or "at" for text mode. The default mode is
+ "rb", and the default compresslevel is 9.
+
+ For binary mode, this function is equivalent to the GzipFile constructor:
+ GzipFile(filename, mode, compresslevel). In this case, the encoding, errors
+ and newline arguments must not be provided.
+
+ For text mode, a GzipFile object is created, and wrapped in an
+ io.TextIOWrapper instance with the specified encoding, error handling
+ behavior, and line ending(s).
+
+ """
+ if "t" in mode:
+ if "b" in mode:
+ raise ValueError("Invalid mode: %r" % (mode,))
+ else:
+ if encoding is not None:
+ raise ValueError("Argument 'encoding' not supported in binary mode")
+ if errors is not None:
+ raise ValueError("Argument 'errors' not supported in binary mode")
+ if newline is not None:
+ raise ValueError("Argument 'newline' not supported in binary mode")
+
+ gz_mode = mode.replace("t", "")
+ if isinstance(filename, (str, bytes, os.PathLike)):
+ binary_file = GzipFile(filename, gz_mode, compresslevel)
+ elif hasattr(filename, "read") or hasattr(filename, "write"):
+ binary_file = GzipFile(None, gz_mode, compresslevel, filename)
+ else:
+ raise TypeError("filename must be a str or bytes object, or a file")
+
+ if "t" in mode:
+ encoding = io.text_encoding(encoding)
+ return io.TextIOWrapper(binary_file, encoding, errors, newline)
+ else:
+ return binary_file
+
+def write32u(output, value):
+ # The L format writes the bit pattern correctly whether signed
+ # or unsigned.
+ output.write(struct.pack("'
+
+ def _init_write(self, filename):
+ self.name = filename
+ self.crc = zlib.crc32(b"")
+ self.size = 0
+ self.writebuf = []
+ self.bufsize = 0
+ self.offset = 0 # Current file offset for seek(), tell(), etc
+
+ def tell(self):
+ self._check_not_closed()
+ self._buffer.flush()
+ return super().tell()
+
+ def _write_gzip_header(self, compresslevel):
+ self.fileobj.write(b'\037\213') # magic header
+ self.fileobj.write(b'\010') # compression method
+ try:
+ # RFC 1952 requires the FNAME field to be Latin-1. Do not
+ # include filenames that cannot be represented that way.
+ fname = os.path.basename(self.name)
+ if not isinstance(fname, bytes):
+ fname = fname.encode('latin-1')
+ if fname.endswith(b'.gz'):
+ fname = fname[:-3]
+ except UnicodeEncodeError:
+ fname = b''
+ flags = 0
+ if fname:
+ flags = FNAME
+ self.fileobj.write(chr(flags).encode('latin-1'))
+ mtime = self._write_mtime
+ if mtime is None:
+ mtime = time.time()
+ write32u(self.fileobj, int(mtime))
+ if compresslevel == _COMPRESS_LEVEL_BEST:
+ xfl = b'\002'
+ elif compresslevel == _COMPRESS_LEVEL_FAST:
+ xfl = b'\004'
+ else:
+ xfl = b'\000'
+ self.fileobj.write(xfl)
+ self.fileobj.write(b'\377')
+ if fname:
+ self.fileobj.write(fname + b'\000')
+
+ def write(self,data):
+ self._check_not_closed()
+ if self.mode != WRITE:
+ import errno
+ raise OSError(errno.EBADF, "write() on read-only GzipFile object")
+
+ if self.fileobj is None:
+ raise ValueError("write() on closed GzipFile object")
+
+ return self._buffer.write(data)
+
+ def _write_raw(self, data):
+ # Called by our self._buffer underlying WriteBufferStream.
+ if isinstance(data, (bytes, bytearray)):
+ length = len(data)
+ else:
+ # accept any data that supports the buffer protocol
+ data = memoryview(data)
+ length = data.nbytes
+
+ if length > 0:
+ self.fileobj.write(self.compress.compress(data))
+ self.size += length
+ self.crc = zlib.crc32(data, self.crc)
+ self.offset += length
+
+ return length
+
+ def _check_read(self, caller):
+ if self.mode != READ:
+ import errno
+ msg = f"{caller}() on write-only GzipFile object"
+ raise OSError(errno.EBADF, msg)
+
+ def read(self, size=-1):
+ self._check_not_closed()
+ self._check_read("read")
+ return self._buffer.read(size)
+
+ def read1(self, size=-1):
+ """Implements BufferedIOBase.read1()
+
+ Reads up to a buffer's worth of data if size is negative."""
+ self._check_not_closed()
+ self._check_read("read1")
+
+ if size < 0:
+ size = io.DEFAULT_BUFFER_SIZE
+ return self._buffer.read1(size)
+
+ def readinto(self, b):
+ self._check_not_closed()
+ self._check_read("readinto")
+ return self._buffer.readinto(b)
+
+ def readinto1(self, b):
+ self._check_not_closed()
+ self._check_read("readinto1")
+ return self._buffer.readinto1(b)
+
+ def peek(self, n):
+ self._check_not_closed()
+ self._check_read("peek")
+ return self._buffer.peek(n)
+
+ @property
+ def closed(self):
+ return self.fileobj is None
+
+ def close(self):
+ fileobj = self.fileobj
+ if fileobj is None:
+ return
+ if self._buffer is None or self._buffer.closed:
+ return
+ try:
+ if self.mode == WRITE:
+ self._buffer.flush()
+ fileobj.write(self.compress.flush())
+ write32u(fileobj, self.crc)
+ # self.size may exceed 2 GiB, or even 4 GiB
+ write32u(fileobj, self.size & 0xffffffff)
+ elif self.mode == READ:
+ self._buffer.close()
+ finally:
+ self._close()
+
+ def _close(self):
+ self.fileobj = None
+ myfileobj = self.myfileobj
+ if myfileobj is not None:
+ self.myfileobj = None
+ myfileobj.close()
+
+ def flush(self,zlib_mode=zlib.Z_SYNC_FLUSH):
+ self._check_not_closed()
+ if self.mode == WRITE:
+ self._buffer.flush()
+ # Ensure the compressor's buffer is flushed
+ self.fileobj.write(self.compress.flush(zlib_mode))
+ self.fileobj.flush()
+
+ def fileno(self):
+ """Invoke the underlying file object's fileno() method.
+
+ This will raise AttributeError if the underlying file object
+ doesn't support fileno().
+ """
+ return self.fileobj.fileno()
+
+ def rewind(self):
+ '''Return the uncompressed stream file position indicator to the
+ beginning of the file'''
+ if self.mode != READ:
+ raise OSError("Can't rewind in write mode")
+ self._buffer.seek(0)
+
+ def readable(self):
+ return self.mode == READ
+
+ def writable(self):
+ return self.mode == WRITE
+
+ def seekable(self):
+ return True
+
+ def seek(self, offset, whence=io.SEEK_SET):
+ if self.mode == WRITE:
+ self._check_not_closed()
+ # Flush buffer to ensure validity of self.offset
+ self._buffer.flush()
+ if whence != io.SEEK_SET:
+ if whence == io.SEEK_CUR:
+ offset = self.offset + offset
+ else:
+ raise ValueError('Seek from end not supported')
+ if offset < self.offset:
+ raise OSError('Negative seek in write mode')
+ count = offset - self.offset
+ chunk = b'\0' * self._buffer_size
+ for i in range(count // self._buffer_size):
+ self.write(chunk)
+ self.write(b'\0' * (count % self._buffer_size))
+ elif self.mode == READ:
+ self._check_not_closed()
+ return self._buffer.seek(offset, whence)
+
+ return self.offset
+
+ def readline(self, size=-1):
+ self._check_not_closed()
+ return self._buffer.readline(size)
+
+ def __del__(self):
+ if self.mode == WRITE and not self.closed:
+ import warnings
+ warnings.warn("unclosed GzipFile",
+ ResourceWarning, source=self, stacklevel=2)
+
+ super().__del__()
+
+def _read_exact(fp, n):
+ '''Read exactly *n* bytes from `fp`
+
+ This method is required because fp may be unbuffered,
+ i.e. return short reads.
+ '''
+ data = fp.read(n)
+ while len(data) < n:
+ b = fp.read(n - len(data))
+ if not b:
+ raise EOFError("Compressed file ended before the "
+ "end-of-stream marker was reached")
+ data += b
+ return data
+
+
+def _read_gzip_header(fp):
+ '''Read a gzip header from `fp` and progress to the end of the header.
+
+ Returns last mtime if header was present or None otherwise.
+ '''
+ magic = fp.read(2)
+ if magic == b'':
+ return None
+
+ if magic != b'\037\213':
+ raise BadGzipFile('Not a gzipped file (%r)' % magic)
+
+ (method, flag, last_mtime) = struct.unpack(">> import hashlib
+ >>> m = hashlib.md5()
+ >>> m.update(b"Nobody inspects")
+ >>> m.update(b" the spammish repetition")
+ >>> m.digest()
+ b'\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'
+
+More condensed:
+
+ >>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest()
+ 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'
+
+"""
+
+# This tuple and __get_builtin_constructor() must be modified if a new
+# always available algorithm is added.
+__always_supported = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',
+ 'blake2b', 'blake2s',
+ 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512',
+ 'shake_128', 'shake_256')
+
+
+algorithms_guaranteed = set(__always_supported)
+algorithms_available = set(__always_supported)
+
+__all__ = __always_supported + ('new', 'algorithms_guaranteed',
+ 'algorithms_available', 'file_digest')
+
+
+__builtin_constructor_cache = {}
+
+# Prefer our blake2 implementation
+# OpenSSL 1.1.0 comes with a limited implementation of blake2b/s. The OpenSSL
+# implementations neither support keyed blake2 (blake2 MAC) nor advanced
+# features like salt, personalization, or tree hashing. OpenSSL hash-only
+# variants are available as 'blake2b512' and 'blake2s256', though.
+__block_openssl_constructor = {
+ 'blake2b', 'blake2s',
+}
+
+def __get_builtin_constructor(name):
+ cache = __builtin_constructor_cache
+ constructor = cache.get(name)
+ if constructor is not None:
+ return constructor
+ try:
+ if name in {'SHA1', 'sha1'}:
+ import _sha1
+ cache['SHA1'] = cache['sha1'] = _sha1.sha1
+ elif name in {'MD5', 'md5'}:
+ import _md5
+ cache['MD5'] = cache['md5'] = _md5.md5
+ elif name in {'SHA256', 'sha256', 'SHA224', 'sha224'}:
+ import _sha2
+ cache['SHA224'] = cache['sha224'] = _sha2.sha224
+ cache['SHA256'] = cache['sha256'] = _sha2.sha256
+ elif name in {'SHA512', 'sha512', 'SHA384', 'sha384'}:
+ import _sha2
+ cache['SHA384'] = cache['sha384'] = _sha2.sha384
+ cache['SHA512'] = cache['sha512'] = _sha2.sha512
+ elif name in {'blake2b', 'blake2s'}:
+ import _blake2
+ cache['blake2b'] = _blake2.blake2b
+ cache['blake2s'] = _blake2.blake2s
+ elif name in {'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512'}:
+ import _sha3
+ cache['sha3_224'] = _sha3.sha3_224
+ cache['sha3_256'] = _sha3.sha3_256
+ cache['sha3_384'] = _sha3.sha3_384
+ cache['sha3_512'] = _sha3.sha3_512
+ elif name in {'shake_128', 'shake_256'}:
+ import _sha3
+ cache['shake_128'] = _sha3.shake_128
+ cache['shake_256'] = _sha3.shake_256
+ except ImportError:
+ pass # no extension module, this hash is unsupported.
+
+ constructor = cache.get(name)
+ if constructor is not None:
+ return constructor
+
+ raise ValueError('unsupported hash type ' + name)
+
+
+def __get_openssl_constructor(name):
+ if name in __block_openssl_constructor:
+ # Prefer our builtin blake2 implementation.
+ return __get_builtin_constructor(name)
+ try:
+ # MD5, SHA1, and SHA2 are in all supported OpenSSL versions
+ # SHA3/shake are available in OpenSSL 1.1.1+
+ f = getattr(_hashlib, 'openssl_' + name)
+ # Allow the C module to raise ValueError. The function will be
+ # defined but the hash not actually available. Don't fall back to
+ # builtin if the current security policy blocks a digest, bpo#40695.
+ f(usedforsecurity=False)
+ # Use the C function directly (very fast)
+ return f
+ except (AttributeError, ValueError):
+ return __get_builtin_constructor(name)
+
+
+def __py_new(name, *args, **kwargs):
+ """new(name, data=b'', **kwargs) - Return a new hashing object using the
+ named algorithm; optionally initialized with data (which must be
+ a bytes-like object).
+ """
+ return __get_builtin_constructor(name)(*args, **kwargs)
+
+
+def __hash_new(name, *args, **kwargs):
+ """new(name, data=b'') - Return a new hashing object using the named algorithm;
+ optionally initialized with data (which must be a bytes-like object).
+ """
+ if name in __block_openssl_constructor:
+ # Prefer our builtin blake2 implementation.
+ return __get_builtin_constructor(name)(*args, **kwargs)
+ try:
+ return _hashlib.new(name, *args, **kwargs)
+ except ValueError:
+ # If the _hashlib module (OpenSSL) doesn't support the named
+ # hash, try using our builtin implementations.
+ # This allows for SHA224/256 and SHA384/512 support even though
+ # the OpenSSL library prior to 0.9.8 doesn't provide them.
+ return __get_builtin_constructor(name)(*args, **kwargs)
+
+
+try:
+ import _hashlib
+ new = __hash_new
+ __get_hash = __get_openssl_constructor
+ algorithms_available = algorithms_available.union(
+ _hashlib.openssl_md_meth_names)
+except ImportError:
+ _hashlib = None
+ new = __py_new
+ __get_hash = __get_builtin_constructor
+
+try:
+ # OpenSSL's PKCS5_PBKDF2_HMAC requires OpenSSL 1.0+ with HMAC and SHA
+ from _hashlib import pbkdf2_hmac
+ __all__ += ('pbkdf2_hmac',)
+except ImportError:
+ pass
+
+
+try:
+ # OpenSSL's scrypt requires OpenSSL 1.1+
+ from _hashlib import scrypt # noqa: F401
+except ImportError:
+ pass
+
+
+def file_digest(fileobj, digest, /, *, _bufsize=2**18):
+ """Hash the contents of a file-like object. Returns a digest object.
+
+ *fileobj* must be a file-like object opened for reading in binary mode.
+ It accepts file objects from open(), io.BytesIO(), and SocketIO objects.
+ The function may bypass Python's I/O and use the file descriptor *fileno*
+ directly.
+
+ *digest* must either be a hash algorithm name as a *str*, a hash
+ constructor, or a callable that returns a hash object.
+ """
+ # On Linux we could use AF_ALG sockets and sendfile() to archive zero-copy
+ # hashing with hardware acceleration.
+ if isinstance(digest, str):
+ digestobj = new(digest)
+ else:
+ digestobj = digest()
+
+ if hasattr(fileobj, "getbuffer"):
+ # io.BytesIO object, use zero-copy buffer
+ digestobj.update(fileobj.getbuffer())
+ return digestobj
+
+ # Only binary files implement readinto().
+ if not (
+ hasattr(fileobj, "readinto")
+ and hasattr(fileobj, "readable")
+ and fileobj.readable()
+ ):
+ raise ValueError(
+ f"'{fileobj!r}' is not a file-like object in binary reading mode."
+ )
+
+ # binary file, socket.SocketIO object
+ # Note: socket I/O uses different syscalls than file I/O.
+ buf = bytearray(_bufsize) # Reusable buffer to reduce allocations.
+ view = memoryview(buf)
+ while True:
+ size = fileobj.readinto(buf)
+ if size is None:
+ raise BlockingIOError("I/O operation would block.")
+ if size == 0:
+ break # EOF
+ digestobj.update(view[:size])
+
+ return digestobj
+
+
+for __func_name in __always_supported:
+ # try them all, some may not work due to the OpenSSL
+ # version not supporting that algorithm.
+ try:
+ globals()[__func_name] = __get_hash(__func_name)
+ except ValueError:
+ import logging
+ logging.exception('code for hash %s was not found.', __func_name)
+
+
+# Cleanup locals()
+del __always_supported, __func_name, __get_hash
+del __py_new, __hash_new, __get_openssl_constructor
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/heapq.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/heapq.py
new file mode 100644
index 0000000000000000000000000000000000000000..17f62dd2d5839b9c7f4f1d3583ae01f215d57f0f
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/heapq.py
@@ -0,0 +1,611 @@
+"""Heap queue algorithm (a.k.a. priority queue).
+
+Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
+all k, counting elements from 0. For the sake of comparison,
+non-existing elements are considered to be infinite. The interesting
+property of a heap is that a[0] is always its smallest element.
+
+Usage:
+
+heap = [] # creates an empty heap
+heappush(heap, item) # pushes a new item on the heap
+item = heappop(heap) # pops the smallest item from the heap
+item = heap[0] # smallest item on the heap without popping it
+heapify(x) # transforms list into a heap, in-place, in linear time
+item = heappushpop(heap, item) # pushes a new item and then returns
+ # the smallest item; the heap size is unchanged
+item = heapreplace(heap, item) # pops and returns smallest item, and adds
+ # new item; the heap size is unchanged
+
+Our API differs from textbook heap algorithms as follows:
+
+- We use 0-based indexing. This makes the relationship between the
+ index for a node and the indexes for its children slightly less
+ obvious, but is more suitable since Python uses 0-based indexing.
+
+- Our heappop() method returns the smallest item, not the largest.
+
+These two make it possible to view the heap as a regular Python list
+without surprises: heap[0] is the smallest item, and heap.sort()
+maintains the heap invariant!
+"""
+
+# Original code by Kevin O'Connor, augmented by Tim Peters and Raymond Hettinger
+
+__about__ = """Heap queues
+
+[explanation by François Pinard]
+
+Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
+all k, counting elements from 0. For the sake of comparison,
+non-existing elements are considered to be infinite. The interesting
+property of a heap is that a[0] is always its smallest element.
+
+The strange invariant above is meant to be an efficient memory
+representation for a tournament. The numbers below are 'k', not a[k]:
+
+ 0
+
+ 1 2
+
+ 3 4 5 6
+
+ 7 8 9 10 11 12 13 14
+
+ 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
+
+
+In the tree above, each cell 'k' is topping '2*k+1' and '2*k+2'. In
+a usual binary tournament we see in sports, each cell is the winner
+over the two cells it tops, and we can trace the winner down the tree
+to see all opponents s/he had. However, in many computer applications
+of such tournaments, we do not need to trace the history of a winner.
+To be more memory efficient, when a winner is promoted, we try to
+replace it by something else at a lower level, and the rule becomes
+that a cell and the two cells it tops contain three different items,
+but the top cell "wins" over the two topped cells.
+
+If this heap invariant is protected at all time, index 0 is clearly
+the overall winner. The simplest algorithmic way to remove it and
+find the "next" winner is to move some loser (let's say cell 30 in the
+diagram above) into the 0 position, and then percolate this new 0 down
+the tree, exchanging values, until the invariant is re-established.
+This is clearly logarithmic on the total number of items in the tree.
+By iterating over all items, you get an O(n ln n) sort.
+
+A nice feature of this sort is that you can efficiently insert new
+items while the sort is going on, provided that the inserted items are
+not "better" than the last 0'th element you extracted. This is
+especially useful in simulation contexts, where the tree holds all
+incoming events, and the "win" condition means the smallest scheduled
+time. When an event schedules other events for execution, they are
+scheduled into the future, so they can easily go into the heap. So, a
+heap is a good structure for implementing schedulers (this is what I
+used for my MIDI sequencer :-).
+
+Various structures for implementing schedulers have been extensively
+studied, and heaps are good for this, as they are reasonably speedy,
+the speed is almost constant, and the worst case is not much different
+than the average case. However, there are other representations which
+are more efficient overall, yet the worst cases might be terrible.
+
+Heaps are also very useful in big disk sorts. You most probably all
+know that a big sort implies producing "runs" (which are pre-sorted
+sequences, whose size is usually related to the amount of CPU memory),
+followed by a merging passes for these runs, which merging is often
+very cleverly organised[1]. It is very important that the initial
+sort produces the longest runs possible. Tournaments are a good way
+to achieve that. If, using all the memory available to hold a
+tournament, you replace and percolate items that happen to fit the
+current run, you'll produce runs which are twice the size of the
+memory for random input, and much better for input fuzzily ordered.
+
+Moreover, if you output the 0'th item on disk and get an input which
+may not fit in the current tournament (because the value "wins" over
+the last output value), it cannot fit in the heap, so the size of the
+heap decreases. The freed memory could be cleverly reused immediately
+for progressively building a second heap, which grows at exactly the
+same rate the first heap is melting. When the first heap completely
+vanishes, you switch heaps and start a new run. Clever and quite
+effective!
+
+In a word, heaps are useful memory structures to know. I use them in
+a few applications, and I think it is good to keep a 'heap' module
+around. :-)
+
+--------------------
+[1] The disk balancing algorithms which are current, nowadays, are
+more annoying than clever, and this is a consequence of the seeking
+capabilities of the disks. On devices which cannot seek, like big
+tape drives, the story was quite different, and one had to be very
+clever to ensure (far in advance) that each tape movement will be the
+most effective possible (that is, will best participate at
+"progressing" the merge). Some tapes were even able to read
+backwards, and this was also used to avoid the rewinding time.
+Believe me, real good tape sorts were quite spectacular to watch!
+From all times, sorting has always been a Great Art! :-)
+"""
+
+__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'heappushpop',
+ 'heappush_max', 'heappop_max', 'heapify_max', 'heapreplace_max',
+ 'heappushpop_max', 'nlargest', 'nsmallest', 'merge']
+
+def heappush(heap, item):
+ """Push item onto heap, maintaining the heap invariant."""
+ heap.append(item)
+ _siftdown(heap, 0, len(heap)-1)
+
+def heappop(heap):
+ """Pop the smallest item off the heap, maintaining the heap invariant."""
+ lastelt = heap.pop() # raises appropriate IndexError if heap is empty
+ if heap:
+ returnitem = heap[0]
+ heap[0] = lastelt
+ _siftup(heap, 0)
+ return returnitem
+ return lastelt
+
+def heapreplace(heap, item):
+ """Pop and return the current smallest value, and add the new item.
+
+ This is more efficient than heappop() followed by heappush(), and can be
+ more appropriate when using a fixed-size heap. Note that the value
+ returned may be larger than item! That constrains reasonable uses of
+ this routine unless written as part of a conditional replacement:
+
+ if item > heap[0]:
+ item = heapreplace(heap, item)
+ """
+ returnitem = heap[0] # raises appropriate IndexError if heap is empty
+ heap[0] = item
+ _siftup(heap, 0)
+ return returnitem
+
+def heappushpop(heap, item):
+ """Fast version of a heappush followed by a heappop."""
+ if heap and heap[0] < item:
+ item, heap[0] = heap[0], item
+ _siftup(heap, 0)
+ return item
+
+def heapify(x):
+ """Transform list into a heap, in-place, in O(len(x)) time."""
+ n = len(x)
+ # Transform bottom-up. The largest index there's any point to looking at
+ # is the largest with a child index in-range, so must have 2*i + 1 < n,
+ # or i < (n-1)/2. If n is even = 2*j, this is (2*j-1)/2 = j-1/2 so
+ # j-1 is the largest, which is n//2 - 1. If n is odd = 2*j+1, this is
+ # (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1.
+ for i in reversed(range(n//2)):
+ _siftup(x, i)
+
+def heappop_max(heap):
+ """Maxheap version of a heappop."""
+ lastelt = heap.pop() # raises appropriate IndexError if heap is empty
+ if heap:
+ returnitem = heap[0]
+ heap[0] = lastelt
+ _siftup_max(heap, 0)
+ return returnitem
+ return lastelt
+
+def heapreplace_max(heap, item):
+ """Maxheap version of a heappop followed by a heappush."""
+ returnitem = heap[0] # raises appropriate IndexError if heap is empty
+ heap[0] = item
+ _siftup_max(heap, 0)
+ return returnitem
+
+def heappush_max(heap, item):
+ """Maxheap version of a heappush."""
+ heap.append(item)
+ _siftdown_max(heap, 0, len(heap)-1)
+
+def heappushpop_max(heap, item):
+ """Maxheap fast version of a heappush followed by a heappop."""
+ if heap and item < heap[0]:
+ item, heap[0] = heap[0], item
+ _siftup_max(heap, 0)
+ return item
+
+def heapify_max(x):
+ """Transform list into a maxheap, in-place, in O(len(x)) time."""
+ n = len(x)
+ for i in reversed(range(n//2)):
+ _siftup_max(x, i)
+
+
+# 'heap' is a heap at all indices >= startpos, except possibly for pos. pos
+# is the index of a leaf with a possibly out-of-order value. Restore the
+# heap invariant.
+def _siftdown(heap, startpos, pos):
+ newitem = heap[pos]
+ # Follow the path to the root, moving parents down until finding a place
+ # newitem fits.
+ while pos > startpos:
+ parentpos = (pos - 1) >> 1
+ parent = heap[parentpos]
+ if newitem < parent:
+ heap[pos] = parent
+ pos = parentpos
+ continue
+ break
+ heap[pos] = newitem
+
+# The child indices of heap index pos are already heaps, and we want to make
+# a heap at index pos too. We do this by bubbling the smaller child of
+# pos up (and so on with that child's children, etc) until hitting a leaf,
+# then using _siftdown to move the oddball originally at index pos into place.
+#
+# We *could* break out of the loop as soon as we find a pos where newitem <=
+# both its children, but turns out that's not a good idea, and despite that
+# many books write the algorithm that way. During a heap pop, the last array
+# element is sifted in, and that tends to be large, so that comparing it
+# against values starting from the root usually doesn't pay (= usually doesn't
+# get us out of the loop early). See Knuth, Volume 3, where this is
+# explained and quantified in an exercise.
+#
+# Cutting the # of comparisons is important, since these routines have no
+# way to extract "the priority" from an array element, so that intelligence
+# is likely to be hiding in custom comparison methods, or in array elements
+# storing (priority, record) tuples. Comparisons are thus potentially
+# expensive.
+#
+# On random arrays of length 1000, making this change cut the number of
+# comparisons made by heapify() a little, and those made by exhaustive
+# heappop() a lot, in accord with theory. Here are typical results from 3
+# runs (3 just to demonstrate how small the variance is):
+#
+# Compares needed by heapify Compares needed by 1000 heappops
+# -------------------------- --------------------------------
+# 1837 cut to 1663 14996 cut to 8680
+# 1855 cut to 1659 14966 cut to 8678
+# 1847 cut to 1660 15024 cut to 8703
+#
+# Building the heap by using heappush() 1000 times instead required
+# 2198, 2148, and 2219 compares: heapify() is more efficient, when
+# you can use it.
+#
+# The total compares needed by list.sort() on the same lists were 8627,
+# 8627, and 8632 (this should be compared to the sum of heapify() and
+# heappop() compares): list.sort() is (unsurprisingly!) more efficient
+# for sorting.
+
+def _siftup(heap, pos):
+ endpos = len(heap)
+ startpos = pos
+ newitem = heap[pos]
+ # Bubble up the smaller child until hitting a leaf.
+ childpos = 2*pos + 1 # leftmost child position
+ while childpos < endpos:
+ # Set childpos to index of smaller child.
+ rightpos = childpos + 1
+ if rightpos < endpos and not heap[childpos] < heap[rightpos]:
+ childpos = rightpos
+ # Move the smaller child up.
+ heap[pos] = heap[childpos]
+ pos = childpos
+ childpos = 2*pos + 1
+ # The leaf at pos is empty now. Put newitem there, and bubble it up
+ # to its final resting place (by sifting its parents down).
+ heap[pos] = newitem
+ _siftdown(heap, startpos, pos)
+
+def _siftdown_max(heap, startpos, pos):
+ 'Maxheap variant of _siftdown'
+ newitem = heap[pos]
+ # Follow the path to the root, moving parents down until finding a place
+ # newitem fits.
+ while pos > startpos:
+ parentpos = (pos - 1) >> 1
+ parent = heap[parentpos]
+ if parent < newitem:
+ heap[pos] = parent
+ pos = parentpos
+ continue
+ break
+ heap[pos] = newitem
+
+def _siftup_max(heap, pos):
+ 'Maxheap variant of _siftup'
+ endpos = len(heap)
+ startpos = pos
+ newitem = heap[pos]
+ # Bubble up the larger child until hitting a leaf.
+ childpos = 2*pos + 1 # leftmost child position
+ while childpos < endpos:
+ # Set childpos to index of larger child.
+ rightpos = childpos + 1
+ if rightpos < endpos and not heap[rightpos] < heap[childpos]:
+ childpos = rightpos
+ # Move the larger child up.
+ heap[pos] = heap[childpos]
+ pos = childpos
+ childpos = 2*pos + 1
+ # The leaf at pos is empty now. Put newitem there, and bubble it up
+ # to its final resting place (by sifting its parents down).
+ heap[pos] = newitem
+ _siftdown_max(heap, startpos, pos)
+
+def merge(*iterables, key=None, reverse=False):
+ '''Merge multiple sorted inputs into a single sorted output.
+
+ Similar to sorted(itertools.chain(*iterables)) but returns a generator,
+ does not pull the data into memory all at once, and assumes that each of
+ the input streams is already sorted (smallest to largest).
+
+ >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25]))
+ [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]
+
+ If *key* is not None, applies a key function to each element to determine
+ its sort order.
+
+ >>> list(merge(['dog', 'horse'], ['cat', 'fish', 'kangaroo'], key=len))
+ ['dog', 'cat', 'fish', 'horse', 'kangaroo']
+
+ '''
+
+ h = []
+ h_append = h.append
+
+ if reverse:
+ _heapify = heapify_max
+ _heappop = heappop_max
+ _heapreplace = heapreplace_max
+ direction = -1
+ else:
+ _heapify = heapify
+ _heappop = heappop
+ _heapreplace = heapreplace
+ direction = 1
+
+ if key is None:
+ for order, it in enumerate(map(iter, iterables)):
+ try:
+ next = it.__next__
+ h_append([next(), order * direction, next])
+ except StopIteration:
+ pass
+ _heapify(h)
+ while len(h) > 1:
+ try:
+ while True:
+ value, order, next = s = h[0]
+ yield value
+ s[0] = next() # raises StopIteration when exhausted
+ _heapreplace(h, s) # restore heap condition
+ except StopIteration:
+ _heappop(h) # remove empty iterator
+ if h:
+ # fast case when only a single iterator remains
+ value, order, next = h[0]
+ yield value
+ yield from next.__self__
+ return
+
+ for order, it in enumerate(map(iter, iterables)):
+ try:
+ next = it.__next__
+ value = next()
+ h_append([key(value), order * direction, value, next])
+ except StopIteration:
+ pass
+ _heapify(h)
+ while len(h) > 1:
+ try:
+ while True:
+ key_value, order, value, next = s = h[0]
+ yield value
+ value = next()
+ s[0] = key(value)
+ s[2] = value
+ _heapreplace(h, s)
+ except StopIteration:
+ _heappop(h)
+ if h:
+ key_value, order, value, next = h[0]
+ yield value
+ yield from next.__self__
+
+
+# Algorithm notes for nlargest() and nsmallest()
+# ==============================================
+#
+# Make a single pass over the data while keeping the k most extreme values
+# in a heap. Memory consumption is limited to keeping k values in a list.
+#
+# Measured performance for random inputs:
+#
+# number of comparisons
+# n inputs k-extreme values (average of 5 trials) % more than min()
+# ------------- ---------------- --------------------- -----------------
+# 1,000 100 3,317 231.7%
+# 10,000 100 14,046 40.5%
+# 100,000 100 105,749 5.7%
+# 1,000,000 100 1,007,751 0.8%
+# 10,000,000 100 10,009,401 0.1%
+#
+# Theoretical number of comparisons for k smallest of n random inputs:
+#
+# Step Comparisons Action
+# ---- -------------------------- ---------------------------
+# 1 1.66 * k heapify the first k-inputs
+# 2 n - k compare remaining elements to top of heap
+# 3 k * (1 + lg2(k)) * ln(n/k) replace the topmost value on the heap
+# 4 k * lg2(k) - (k/2) final sort of the k most extreme values
+#
+# Combining and simplifying for a rough estimate gives:
+#
+# comparisons = n + k * (log(k, 2) * log(n/k) + log(k, 2) + log(n/k))
+#
+# Computing the number of comparisons for step 3:
+# -----------------------------------------------
+# * For the i-th new value from the iterable, the probability of being in the
+# k most extreme values is k/i. For example, the probability of the 101st
+# value seen being in the 100 most extreme values is 100/101.
+# * If the value is a new extreme value, the cost of inserting it into the
+# heap is 1 + log(k, 2).
+# * The probability times the cost gives:
+# (k/i) * (1 + log(k, 2))
+# * Summing across the remaining n-k elements gives:
+# sum((k/i) * (1 + log(k, 2)) for i in range(k+1, n+1))
+# * This reduces to:
+# (H(n) - H(k)) * k * (1 + log(k, 2))
+# * Where H(n) is the n-th harmonic number estimated by:
+# gamma = 0.5772156649
+# H(n) = log(n, e) + gamma + 1 / (2 * n)
+# http://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#Rate_of_divergence
+# * Substituting the H(n) formula:
+# comparisons = k * (1 + log(k, 2)) * (log(n/k, e) + (1/n - 1/k) / 2)
+#
+# Worst-case for step 3:
+# ----------------------
+# In the worst case, the input data is reversed sorted so that every new element
+# must be inserted in the heap:
+#
+# comparisons = 1.66 * k + log(k, 2) * (n - k)
+#
+# Alternative Algorithms
+# ----------------------
+# Other algorithms were not used because they:
+# 1) Took much more auxiliary memory,
+# 2) Made multiple passes over the data.
+# 3) Made more comparisons in common cases (small k, large n, semi-random input).
+# See the more detailed comparison of approach at:
+# http://code.activestate.com/recipes/577573-compare-algorithms-for-heapqsmallest
+
+def nsmallest(n, iterable, key=None):
+ """Find the n smallest elements in a dataset.
+
+ Equivalent to: sorted(iterable, key=key)[:n]
+ """
+
+ # Short-cut for n==1 is to use min()
+ if n == 1:
+ it = iter(iterable)
+ sentinel = object()
+ result = min(it, default=sentinel, key=key)
+ return [] if result is sentinel else [result]
+
+ # When n>=size, it's faster to use sorted()
+ try:
+ size = len(iterable)
+ except (TypeError, AttributeError):
+ pass
+ else:
+ if n >= size:
+ return sorted(iterable, key=key)[:n]
+
+ # When key is none, use simpler decoration
+ if key is None:
+ it = iter(iterable)
+ # put the range(n) first so that zip() doesn't
+ # consume one too many elements from the iterator
+ result = [(elem, i) for i, elem in zip(range(n), it)]
+ if not result:
+ return result
+ heapify_max(result)
+ top = result[0][0]
+ order = n
+ _heapreplace = heapreplace_max
+ for elem in it:
+ if elem < top:
+ _heapreplace(result, (elem, order))
+ top, _order = result[0]
+ order += 1
+ result.sort()
+ return [elem for (elem, order) in result]
+
+ # General case, slowest method
+ it = iter(iterable)
+ result = [(key(elem), i, elem) for i, elem in zip(range(n), it)]
+ if not result:
+ return result
+ heapify_max(result)
+ top = result[0][0]
+ order = n
+ _heapreplace = heapreplace_max
+ for elem in it:
+ k = key(elem)
+ if k < top:
+ _heapreplace(result, (k, order, elem))
+ top, _order, _elem = result[0]
+ order += 1
+ result.sort()
+ return [elem for (k, order, elem) in result]
+
+def nlargest(n, iterable, key=None):
+ """Find the n largest elements in a dataset.
+
+ Equivalent to: sorted(iterable, key=key, reverse=True)[:n]
+ """
+
+ # Short-cut for n==1 is to use max()
+ if n == 1:
+ it = iter(iterable)
+ sentinel = object()
+ result = max(it, default=sentinel, key=key)
+ return [] if result is sentinel else [result]
+
+ # When n>=size, it's faster to use sorted()
+ try:
+ size = len(iterable)
+ except (TypeError, AttributeError):
+ pass
+ else:
+ if n >= size:
+ return sorted(iterable, key=key, reverse=True)[:n]
+
+ # When key is none, use simpler decoration
+ if key is None:
+ it = iter(iterable)
+ result = [(elem, i) for i, elem in zip(range(0, -n, -1), it)]
+ if not result:
+ return result
+ heapify(result)
+ top = result[0][0]
+ order = -n
+ _heapreplace = heapreplace
+ for elem in it:
+ if top < elem:
+ _heapreplace(result, (elem, order))
+ top, _order = result[0]
+ order -= 1
+ result.sort(reverse=True)
+ return [elem for (elem, order) in result]
+
+ # General case, slowest method
+ it = iter(iterable)
+ result = [(key(elem), i, elem) for i, elem in zip(range(0, -n, -1), it)]
+ if not result:
+ return result
+ heapify(result)
+ top = result[0][0]
+ order = -n
+ _heapreplace = heapreplace
+ for elem in it:
+ k = key(elem)
+ if top < k:
+ _heapreplace(result, (k, order, elem))
+ top, _order, _elem = result[0]
+ order -= 1
+ result.sort(reverse=True)
+ return [elem for (k, order, elem) in result]
+
+# If available, use C implementation
+try:
+ from _heapq import *
+except ImportError:
+ pass
+
+# For backwards compatibility
+_heappop_max = heappop_max
+_heapreplace_max = heapreplace_max
+_heappush_max = heappush_max
+_heappushpop_max = heappushpop_max
+_heapify_max = heapify_max
+
+if __name__ == "__main__":
+
+ import doctest # pragma: no cover
+ print(doctest.testmod()) # pragma: no cover
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/hmac.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/hmac.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d6016cda11c0e5791ef361a80795d44126acaf4
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/hmac.py
@@ -0,0 +1,269 @@
+"""HMAC (Keyed-Hashing for Message Authentication) module.
+
+Implements the HMAC algorithm as described by RFC 2104.
+"""
+
+try:
+ import _hashlib as _hashopenssl
+except ImportError:
+ _hashopenssl = None
+ _functype = None
+ from _operator import _compare_digest as compare_digest
+else:
+ compare_digest = _hashopenssl.compare_digest
+ _functype = type(_hashopenssl.openssl_sha256) # builtin type
+
+try:
+ import _hmac
+except ImportError:
+ _hmac = None
+
+trans_5C = bytes((x ^ 0x5C) for x in range(256))
+trans_36 = bytes((x ^ 0x36) for x in range(256))
+
+# The size of the digests returned by HMAC depends on the underlying
+# hashing module used. Use digest_size from the instance of HMAC instead.
+digest_size = None
+
+
+def _get_digest_constructor(digest_like):
+ if callable(digest_like):
+ return digest_like
+ if isinstance(digest_like, str):
+ def digest_wrapper(d=b''):
+ import hashlib
+ return hashlib.new(digest_like, d)
+ else:
+ def digest_wrapper(d=b''):
+ return digest_like.new(d)
+ return digest_wrapper
+
+
+class HMAC:
+ """RFC 2104 HMAC class. Also complies with RFC 4231.
+
+ This supports the API for Cryptographic Hash Functions (PEP 247).
+ """
+
+ # Note: self.blocksize is the default blocksize; self.block_size
+ # is effective block size as well as the public API attribute.
+ blocksize = 64 # 512-bit HMAC; can be changed in subclasses.
+
+ __slots__ = (
+ "_hmac", "_inner", "_outer", "block_size", "digest_size"
+ )
+
+ def __init__(self, key, msg=None, digestmod=''):
+ """Create a new HMAC object.
+
+ key: bytes or buffer, key for the keyed hash object.
+ msg: bytes or buffer, Initial input for the hash or None.
+ digestmod: A hash name suitable for hashlib.new(). *OR*
+ A hashlib constructor returning a new hash object. *OR*
+ A module supporting PEP 247.
+
+ Required as of 3.8, despite its position after the optional
+ msg argument. Passing it as a keyword argument is
+ recommended, though not required for legacy API reasons.
+ """
+
+ if not isinstance(key, (bytes, bytearray)):
+ raise TypeError(f"key: expected bytes or bytearray, "
+ f"but got {type(key).__name__!r}")
+
+ if not digestmod:
+ raise TypeError("Missing required argument 'digestmod'.")
+
+ self.__init(key, msg, digestmod)
+
+ def __init(self, key, msg, digestmod):
+ if _hashopenssl and isinstance(digestmod, (str, _functype)):
+ try:
+ self._init_openssl_hmac(key, msg, digestmod)
+ return
+ except _hashopenssl.UnsupportedDigestmodError: # pragma: no cover
+ pass
+ if _hmac and isinstance(digestmod, str):
+ try:
+ self._init_builtin_hmac(key, msg, digestmod)
+ return
+ except _hmac.UnknownHashError: # pragma: no cover
+ pass
+ self._init_old(key, msg, digestmod)
+
+ def _init_openssl_hmac(self, key, msg, digestmod):
+ self._hmac = _hashopenssl.hmac_new(key, msg, digestmod=digestmod)
+ self._inner = self._outer = None # because the slots are defined
+ self.digest_size = self._hmac.digest_size
+ self.block_size = self._hmac.block_size
+
+ _init_hmac = _init_openssl_hmac # for backward compatibility (if any)
+
+ def _init_builtin_hmac(self, key, msg, digestmod):
+ self._hmac = _hmac.new(key, msg, digestmod=digestmod)
+ self._inner = self._outer = None # because the slots are defined
+ self.digest_size = self._hmac.digest_size
+ self.block_size = self._hmac.block_size
+
+ def _init_old(self, key, msg, digestmod):
+ import warnings
+
+ digest_cons = _get_digest_constructor(digestmod)
+
+ self._hmac = None
+ self._outer = digest_cons()
+ self._inner = digest_cons()
+ self.digest_size = self._inner.digest_size
+
+ if hasattr(self._inner, 'block_size'):
+ blocksize = self._inner.block_size
+ if blocksize < 16:
+ warnings.warn(f"block_size of {blocksize} seems too small; "
+ f"using our default of {self.blocksize}.",
+ RuntimeWarning, 2)
+ blocksize = self.blocksize # pragma: no cover
+ else:
+ warnings.warn("No block_size attribute on given digest object; "
+ f"Assuming {self.blocksize}.",
+ RuntimeWarning, 2)
+ blocksize = self.blocksize # pragma: no cover
+
+ if len(key) > blocksize:
+ key = digest_cons(key).digest()
+
+ self.block_size = blocksize
+
+ key = key.ljust(blocksize, b'\0')
+ self._outer.update(key.translate(trans_5C))
+ self._inner.update(key.translate(trans_36))
+ if msg is not None:
+ self.update(msg)
+
+ @property
+ def name(self):
+ if self._hmac:
+ return self._hmac.name
+ else:
+ return f"hmac-{self._inner.name}"
+
+ def update(self, msg):
+ """Feed data from msg into this hashing object."""
+ inst = self._hmac or self._inner
+ inst.update(msg)
+
+ def copy(self):
+ """Return a separate copy of this hashing object.
+
+ An update to this copy won't affect the original object.
+ """
+ # Call __new__ directly to avoid the expensive __init__.
+ other = self.__class__.__new__(self.__class__)
+ other.digest_size = self.digest_size
+ other.block_size = self.block_size
+ if self._hmac:
+ other._hmac = self._hmac.copy()
+ other._inner = other._outer = None
+ else:
+ other._hmac = None
+ other._inner = self._inner.copy()
+ other._outer = self._outer.copy()
+ return other
+
+ def _current(self):
+ """Return a hash object for the current state.
+
+ To be used only internally with digest() and hexdigest().
+ """
+ if self._hmac:
+ return self._hmac
+ else:
+ h = self._outer.copy()
+ h.update(self._inner.digest())
+ return h
+
+ def digest(self):
+ """Return the hash value of this hashing object.
+
+ This returns the hmac value as bytes. The object is
+ not altered in any way by this function; you can continue
+ updating the object after calling this function.
+ """
+ h = self._current()
+ return h.digest()
+
+ def hexdigest(self):
+ """Like digest(), but returns a string of hexadecimal digits instead.
+ """
+ h = self._current()
+ return h.hexdigest()
+
+
+def new(key, msg=None, digestmod=''):
+ """Create a new hashing object and return it.
+
+ key: bytes or buffer, The starting key for the hash.
+ msg: bytes or buffer, Initial input for the hash, or None.
+ digestmod: A hash name suitable for hashlib.new(). *OR*
+ A hashlib constructor returning a new hash object. *OR*
+ A module supporting PEP 247.
+
+ Required as of 3.8, despite its position after the optional
+ msg argument. Passing it as a keyword argument is
+ recommended, though not required for legacy API reasons.
+
+ You can now feed arbitrary bytes into the object using its update()
+ method, and can ask for the hash value at any time by calling its digest()
+ or hexdigest() methods.
+ """
+ return HMAC(key, msg, digestmod)
+
+
+def digest(key, msg, digest):
+ """Fast inline implementation of HMAC.
+
+ key: bytes or buffer, The key for the keyed hash object.
+ msg: bytes or buffer, Input message.
+ digest: A hash name suitable for hashlib.new() for best performance. *OR*
+ A hashlib constructor returning a new hash object. *OR*
+ A module supporting PEP 247.
+ """
+ if _hashopenssl and isinstance(digest, (str, _functype)):
+ try:
+ return _hashopenssl.hmac_digest(key, msg, digest)
+ except OverflowError:
+ # OpenSSL's HMAC limits the size of the key to INT_MAX.
+ # Instead of falling back to HACL* implementation which
+ # may still not be supported due to a too large key, we
+ # directly switch to the pure Python fallback instead
+ # even if we could have used streaming HMAC for small keys
+ # but large messages.
+ return _compute_digest_fallback(key, msg, digest)
+ except _hashopenssl.UnsupportedDigestmodError:
+ pass
+
+ if _hmac and isinstance(digest, str):
+ try:
+ return _hmac.compute_digest(key, msg, digest)
+ except (OverflowError, _hmac.UnknownHashError):
+ # HACL* HMAC limits the size of the key to UINT32_MAX
+ # so we fallback to the pure Python implementation even
+ # if streaming HMAC may have been used for small keys
+ # and large messages.
+ pass
+
+ return _compute_digest_fallback(key, msg, digest)
+
+
+def _compute_digest_fallback(key, msg, digest):
+ digest_cons = _get_digest_constructor(digest)
+ inner = digest_cons()
+ outer = digest_cons()
+ blocksize = getattr(inner, 'block_size', 64)
+ if len(key) > blocksize:
+ key = digest_cons(key).digest()
+ key = key.ljust(blocksize, b'\0')
+ inner.update(key.translate(trans_36))
+ outer.update(key.translate(trans_5C))
+ inner.update(msg)
+ outer.update(inner.digest())
+ return outer.digest()
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/imaplib.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/imaplib.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbe129b3e7c2145cec06553c61f09984349ed730
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/imaplib.py
@@ -0,0 +1,1967 @@
+"""IMAP4 client.
+
+Based on RFC 2060.
+
+Public class: IMAP4
+Public variable: Debug
+Public functions: Internaldate2tuple
+ Int2AP
+ ParseFlags
+ Time2Internaldate
+"""
+
+# Author: Piers Lauder December 1997.
+#
+# Authentication code contributed by Donn Cave June 1998.
+# String method conversion by ESR, February 2001.
+# GET/SETACL contributed by Anthony Baxter April 2001.
+# IMAP4_SSL contributed by Tino Lange March 2002.
+# GET/SETQUOTA contributed by Andreas Zeidler June 2002.
+# PROXYAUTH contributed by Rick Holbert November 2002.
+# GET/SETANNOTATION contributed by Tomas Lindroos June 2005.
+# IDLE contributed by Forest August 2024.
+
+__version__ = "2.60"
+
+import binascii, errno, random, re, socket, subprocess, sys, time, calendar
+from datetime import datetime, timezone, timedelta
+from io import DEFAULT_BUFFER_SIZE
+
+try:
+ import ssl
+ HAVE_SSL = True
+except ImportError:
+ HAVE_SSL = False
+
+__all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple",
+ "Int2AP", "ParseFlags", "Time2Internaldate"]
+
+# Globals
+
+CRLF = b'\r\n'
+Debug = 0
+IMAP4_PORT = 143
+IMAP4_SSL_PORT = 993
+AllowedVersions = ('IMAP4REV1', 'IMAP4') # Most recent first
+
+# Maximal line length when calling readline(). This is to prevent
+# reading arbitrary length lines. RFC 3501 and 2060 (IMAP 4rev1)
+# don't specify a line length. RFC 2683 suggests limiting client
+# command lines to 1000 octets and that servers should be prepared
+# to accept command lines up to 8000 octets, so we used to use 10K here.
+# In the modern world (eg: gmail) the response to, for example, a
+# search command can be quite large, so we now use 1M.
+_MAXLINE = 1000000
+
+
+# Commands
+
+Commands = {
+ # name valid states
+ 'APPEND': ('AUTH', 'SELECTED'),
+ 'AUTHENTICATE': ('NONAUTH',),
+ 'CAPABILITY': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
+ 'CHECK': ('SELECTED',),
+ 'CLOSE': ('SELECTED',),
+ 'COPY': ('SELECTED',),
+ 'CREATE': ('AUTH', 'SELECTED'),
+ 'DELETE': ('AUTH', 'SELECTED'),
+ 'DELETEACL': ('AUTH', 'SELECTED'),
+ 'ENABLE': ('AUTH', ),
+ 'EXAMINE': ('AUTH', 'SELECTED'),
+ 'EXPUNGE': ('SELECTED',),
+ 'FETCH': ('SELECTED',),
+ 'GETACL': ('AUTH', 'SELECTED'),
+ 'GETANNOTATION':('AUTH', 'SELECTED'),
+ 'GETQUOTA': ('AUTH', 'SELECTED'),
+ 'GETQUOTAROOT': ('AUTH', 'SELECTED'),
+ 'IDLE': ('AUTH', 'SELECTED'),
+ 'MYRIGHTS': ('AUTH', 'SELECTED'),
+ 'LIST': ('AUTH', 'SELECTED'),
+ 'LOGIN': ('NONAUTH',),
+ 'LOGOUT': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
+ 'LSUB': ('AUTH', 'SELECTED'),
+ 'MOVE': ('SELECTED',),
+ 'NAMESPACE': ('AUTH', 'SELECTED'),
+ 'NOOP': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
+ 'PARTIAL': ('SELECTED',), # NB: obsolete
+ 'PROXYAUTH': ('AUTH',),
+ 'RENAME': ('AUTH', 'SELECTED'),
+ 'SEARCH': ('SELECTED',),
+ 'SELECT': ('AUTH', 'SELECTED'),
+ 'SETACL': ('AUTH', 'SELECTED'),
+ 'SETANNOTATION':('AUTH', 'SELECTED'),
+ 'SETQUOTA': ('AUTH', 'SELECTED'),
+ 'SORT': ('SELECTED',),
+ 'STARTTLS': ('NONAUTH',),
+ 'STATUS': ('AUTH', 'SELECTED'),
+ 'STORE': ('SELECTED',),
+ 'SUBSCRIBE': ('AUTH', 'SELECTED'),
+ 'THREAD': ('SELECTED',),
+ 'UID': ('SELECTED',),
+ 'UNSUBSCRIBE': ('AUTH', 'SELECTED'),
+ 'UNSELECT': ('SELECTED',),
+ }
+
+# Patterns to match server responses
+
+Continuation = re.compile(br'\+( (?P.*))?')
+Flags = re.compile(br'.*FLAGS \((?P[^\)]*)\)')
+InternalDate = re.compile(br'.*INTERNALDATE "'
+ br'(?P[ 0123][0-9])-(?P[A-Z][a-z][a-z])-(?P[0-9][0-9][0-9][0-9])'
+ br' (?P[0-9][0-9]):(?P[0-9][0-9]):(?P[0-9][0-9])'
+ br' (?P[-+])(?P[0-9][0-9])(?P[0-9][0-9])'
+ br'"')
+# Literal is no longer used; kept for backward compatibility.
+Literal = re.compile(br'.*{(?P\d+)}$', re.ASCII)
+MapCRLF = re.compile(br'\r\n|\r|\n')
+# We no longer exclude the ']' character from the data portion of the response
+# code, even though it violates the RFC. Popular IMAP servers such as Gmail
+# allow flags with ']', and there are programs (including imaplib!) that can
+# produce them. The problem with this is if the 'text' portion of the response
+# includes a ']' we'll parse the response wrong (which is the point of the RFC
+# restriction). However, that seems less likely to be a problem in practice
+# than being unable to correctly parse flags that include ']' chars, which
+# was reported as a real-world problem in issue #21815.
+Response_code = re.compile(br'\[(?P[A-Z-]+)( (?P.*))?\]')
+Untagged_response = re.compile(br'\* (?P[A-Z-]+)( (?P.*))?')
+# Untagged_status is no longer used; kept for backward compatibility
+Untagged_status = re.compile(
+ br'\* (?P\d+) (?P[A-Z-]+)( (?P.*))?', re.ASCII)
+# We compile these in _mode_xxx.
+_Literal = br'.*{(?P\d+)}$'
+_Untagged_status = br'\* (?P\d+) (?P[A-Z-]+)( (?P.*))?'
+
+
+
+class IMAP4:
+
+ r"""IMAP4 client class.
+
+ Instantiate with: IMAP4([host[, port[, timeout=None]]])
+
+ host - host's name (default: localhost);
+ port - port number (default: standard IMAP4 port).
+ timeout - socket timeout (default: None)
+ If timeout is not given or is None,
+ the global default socket timeout is used
+
+ All IMAP4rev1 commands are supported by methods of the same
+ name (in lowercase).
+
+ All arguments to commands are converted to strings, except for
+ AUTHENTICATE, and the last argument to APPEND which is passed as
+ an IMAP4 literal. If necessary (the string contains any
+ non-printing characters or white-space and isn't enclosed with
+ either parentheses or double quotes) each string is quoted.
+ However, the 'password' argument to the LOGIN command is always
+ quoted. If you want to avoid having an argument string quoted
+ (eg: the 'flags' argument to STORE) then enclose the string in
+ parentheses (eg: "(\Deleted)").
+
+ Each command returns a tuple: (type, [data, ...]) where 'type'
+ is usually 'OK' or 'NO', and 'data' is either the text from the
+ tagged response, or untagged results from command. Each 'data'
+ is either a string, or a tuple. If a tuple, then the first part
+ is the header of the response, and the second part contains
+ the data (ie: 'literal' value).
+
+ Errors raise the exception class .error("").
+ IMAP4 server errors raise .abort(""),
+ which is a sub-class of 'error'. Mailbox status changes
+ from READ-WRITE to READ-ONLY raise the exception class
+ .readonly(""), which is a sub-class of 'abort'.
+
+ "error" exceptions imply a program error.
+ "abort" exceptions imply the connection should be reset, and
+ the command re-tried.
+ "readonly" exceptions imply the command should be re-tried.
+
+ Note: to use this module, you must read the RFCs pertaining to the
+ IMAP4 protocol, as the semantics of the arguments to each IMAP4
+ command are left to the invoker, not to mention the results. Also,
+ most IMAP servers implement a sub-set of the commands available here.
+ """
+
+ class error(Exception): pass # Logical errors - debug required
+ class abort(error): pass # Service errors - close and retry
+ class readonly(abort): pass # Mailbox status changed to READ-ONLY
+ class _responsetimeout(TimeoutError): pass # No response during IDLE
+
+ def __init__(self, host='', port=IMAP4_PORT, timeout=None):
+ self.debug = Debug
+ self.state = 'LOGOUT'
+ self.literal = None # A literal argument to a command
+ self.tagged_commands = {} # Tagged commands awaiting response
+ self.untagged_responses = {} # {typ: [data, ...], ...}
+ self.continuation_response = '' # Last continuation response
+ self._idle_responses = [] # Response queue for idle iteration
+ self._idle_capture = False # Whether to queue responses for idle
+ self.is_readonly = False # READ-ONLY desired state
+ self.tagnum = 0
+ self._tls_established = False
+ self._mode_ascii()
+ self._readbuf = []
+
+ # Open socket to server.
+
+ self.open(host, port, timeout)
+
+ try:
+ self._connect()
+ except Exception:
+ try:
+ self.shutdown()
+ except OSError:
+ pass
+ raise
+
+ def _mode_ascii(self):
+ self.utf8_enabled = False
+ self._encoding = 'ascii'
+ self.Literal = re.compile(_Literal, re.ASCII)
+ self.Untagged_status = re.compile(_Untagged_status, re.ASCII)
+
+
+ def _mode_utf8(self):
+ self.utf8_enabled = True
+ self._encoding = 'utf-8'
+ self.Literal = re.compile(_Literal)
+ self.Untagged_status = re.compile(_Untagged_status)
+
+
+ def _connect(self):
+ # Create unique tag for this session,
+ # and compile tagged response matcher.
+
+ self.tagpre = Int2AP(random.randint(4096, 65535))
+ self.tagre = re.compile(br'(?P'
+ + self.tagpre
+ + br'\d+) (?P[A-Z]+) (?P.*)', re.ASCII)
+
+ # Get server welcome message,
+ # request and store CAPABILITY response.
+
+ if __debug__:
+ self._cmd_log_len = 10
+ self._cmd_log_idx = 0
+ self._cmd_log = {} # Last '_cmd_log_len' interactions
+ if self.debug >= 1:
+ self._mesg('imaplib version %s' % __version__)
+ self._mesg('new IMAP4 connection, tag=%s' % self.tagpre)
+
+ self.welcome = self._get_response()
+ if 'PREAUTH' in self.untagged_responses:
+ self.state = 'AUTH'
+ elif 'OK' in self.untagged_responses:
+ self.state = 'NONAUTH'
+ else:
+ raise self.error(self.welcome)
+
+ self._get_capabilities()
+ if __debug__:
+ if self.debug >= 3:
+ self._mesg('CAPABILITIES: %r' % (self.capabilities,))
+
+ for version in AllowedVersions:
+ if not version in self.capabilities:
+ continue
+ self.PROTOCOL_VERSION = version
+ return
+
+ raise self.error('server not IMAP4 compliant')
+
+
+ def __getattr__(self, attr):
+ # Allow UPPERCASE variants of IMAP4 command methods.
+ if attr in Commands:
+ return getattr(self, attr.lower())
+ raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ if self.state == "LOGOUT":
+ return
+
+ try:
+ self.logout()
+ except OSError:
+ pass
+
+
+ # Overridable methods
+
+
+ def _create_socket(self, timeout):
+ # Default value of IMAP4.host is '', but socket.getaddrinfo()
+ # (which is used by socket.create_connection()) expects None
+ # as a default value for host.
+ if timeout is not None and not timeout:
+ raise ValueError('Non-blocking socket (timeout=0) is not supported')
+ host = None if not self.host else self.host
+ sys.audit("imaplib.open", self, self.host, self.port)
+ address = (host, self.port)
+ if timeout is not None:
+ return socket.create_connection(address, timeout)
+ return socket.create_connection(address)
+
+ def open(self, host='', port=IMAP4_PORT, timeout=None):
+ """Setup connection to remote server on "host:port"
+ (default: localhost:standard IMAP4 port).
+ This connection will be used by the routines:
+ read, readline, send, shutdown.
+ """
+ self.host = host
+ self.port = port
+ self.sock = self._create_socket(timeout)
+ self._file = self.sock.makefile('rb')
+
+
+ @property
+ def file(self):
+ # The old 'file' attribute is no longer used now that we do our own
+ # read() and readline() buffering, with which it conflicts.
+ # As an undocumented interface, it should never have been accessed by
+ # external code, and therefore does not warrant deprecation.
+ # Nevertheless, we provide this property for now, to avoid suddenly
+ # breaking any code in the wild that might have been using it in a
+ # harmless way.
+ import warnings
+ warnings.warn(
+ 'IMAP4.file is unsupported, can cause errors, and may be removed.',
+ RuntimeWarning,
+ stacklevel=2)
+ return self._file
+
+
+ def read(self, size):
+ """Read 'size' bytes from remote."""
+ # We need buffered read() to continue working after socket timeouts,
+ # since we use them during IDLE. Unfortunately, the standard library's
+ # SocketIO implementation makes this impossible, by setting a permanent
+ # error condition instead of letting the caller decide how to handle a
+ # timeout. We therefore implement our own buffered read().
+ # https://github.com/python/cpython/issues/51571
+ #
+ # Reading in chunks instead of delegating to a single
+ # BufferedReader.read() call also means we avoid its preallocation
+ # of an unreasonably large memory block if a malicious server claims
+ # it will send a huge literal without actually sending one.
+ # https://github.com/python/cpython/issues/119511
+
+ parts = []
+
+ while size > 0:
+
+ if len(parts) < len(self._readbuf):
+ buf = self._readbuf[len(parts)]
+ else:
+ try:
+ buf = self.sock.recv(DEFAULT_BUFFER_SIZE)
+ except ConnectionError:
+ break
+ if not buf:
+ break
+ self._readbuf.append(buf)
+
+ if len(buf) >= size:
+ parts.append(buf[:size])
+ self._readbuf = [buf[size:]] + self._readbuf[len(parts):]
+ break
+ parts.append(buf)
+ size -= len(buf)
+
+ return b''.join(parts)
+
+
+ def readline(self):
+ """Read line from remote."""
+ # The comment in read() explains why we implement our own readline().
+
+ LF = b'\n'
+ parts = []
+ length = 0
+
+ while length < _MAXLINE:
+
+ if len(parts) < len(self._readbuf):
+ buf = self._readbuf[len(parts)]
+ else:
+ try:
+ buf = self.sock.recv(DEFAULT_BUFFER_SIZE)
+ except ConnectionError:
+ break
+ if not buf:
+ break
+ self._readbuf.append(buf)
+
+ pos = buf.find(LF)
+ if pos != -1:
+ pos += 1
+ parts.append(buf[:pos])
+ self._readbuf = [buf[pos:]] + self._readbuf[len(parts):]
+ break
+ parts.append(buf)
+ length += len(buf)
+
+ line = b''.join(parts)
+ if len(line) > _MAXLINE:
+ raise self.error("got more than %d bytes" % _MAXLINE)
+ return line
+
+
+ def send(self, data):
+ """Send data to remote."""
+ sys.audit("imaplib.send", self, data)
+ self.sock.sendall(data)
+
+
+ def shutdown(self):
+ """Close I/O established in "open"."""
+ self._file.close()
+ try:
+ self.sock.shutdown(socket.SHUT_RDWR)
+ except OSError as exc:
+ # The server might already have closed the connection.
+ # On Windows, this may result in WSAEINVAL (error 10022):
+ # An invalid operation was attempted.
+ if (exc.errno != errno.ENOTCONN
+ and getattr(exc, 'winerror', 0) != 10022):
+ raise
+ finally:
+ self.sock.close()
+
+
+ def socket(self):
+ """Return socket instance used to connect to IMAP4 server.
+
+ socket = .socket()
+ """
+ return self.sock
+
+
+
+ # Utility methods
+
+
+ def recent(self):
+ """Return most recent 'RECENT' responses if any exist,
+ else prompt server for an update using the 'NOOP' command.
+
+ (typ, [data]) = .recent()
+
+ 'data' is None if no new messages,
+ else list of RECENT responses, most recent last.
+ """
+ name = 'RECENT'
+ typ, dat = self._untagged_response('OK', [None], name)
+ if dat[-1]:
+ return typ, dat
+ typ, dat = self.noop() # Prod server for response
+ return self._untagged_response(typ, dat, name)
+
+
+ def response(self, code):
+ """Return data for response 'code' if received, or None.
+
+ Old value for response 'code' is cleared.
+
+ (code, [data]) = .response(code)
+ """
+ return self._untagged_response(code, [None], code.upper())
+
+
+
+ # IMAP4 commands
+
+
+ def append(self, mailbox, flags, date_time, message):
+ """Append message to named mailbox.
+
+ (typ, [data]) = .append(mailbox, flags, date_time, message)
+
+ All args except 'message' can be None.
+ """
+ name = 'APPEND'
+ if not mailbox:
+ mailbox = 'INBOX'
+ if flags:
+ if (flags[0],flags[-1]) != ('(',')'):
+ flags = '(%s)' % flags
+ else:
+ flags = None
+ if date_time:
+ date_time = Time2Internaldate(date_time)
+ else:
+ date_time = None
+ literal = MapCRLF.sub(CRLF, message)
+ self.literal = literal
+ return self._simple_command(name, mailbox, flags, date_time)
+
+
+ def authenticate(self, mechanism, authobject):
+ """Authenticate command - requires response processing.
+
+ 'mechanism' specifies which authentication mechanism is to
+ be used - it must appear in .capabilities in the
+ form AUTH=.
+
+ 'authobject' must be a callable object:
+
+ data = authobject(response)
+
+ It will be called to process server continuation responses; the
+ response argument it is passed will be a bytes. It should return bytes
+ data that will be base64 encoded and sent to the server. It should
+ return None if the client abort response '*' should be sent instead.
+ """
+ mech = mechanism.upper()
+ # XXX: shouldn't this code be removed, not commented out?
+ #cap = 'AUTH=%s' % mech
+ #if not cap in self.capabilities: # Let the server decide!
+ # raise self.error("Server doesn't allow %s authentication." % mech)
+ self.literal = _Authenticator(authobject).process
+ typ, dat = self._simple_command('AUTHENTICATE', mech)
+ if typ != 'OK':
+ raise self.error(dat[-1].decode('utf-8', 'replace'))
+ self.state = 'AUTH'
+ return typ, dat
+
+
+ def capability(self):
+ """(typ, [data]) = .capability()
+ Fetch capabilities list from server."""
+
+ name = 'CAPABILITY'
+ typ, dat = self._simple_command(name)
+ return self._untagged_response(typ, dat, name)
+
+
+ def check(self):
+ """Checkpoint mailbox on server.
+
+ (typ, [data]) = .check()
+ """
+ return self._simple_command('CHECK')
+
+
+ def close(self):
+ """Close currently selected mailbox.
+
+ Deleted messages are removed from writable mailbox.
+ This is the recommended command before 'LOGOUT'.
+
+ (typ, [data]) = .close()
+ """
+ try:
+ typ, dat = self._simple_command('CLOSE')
+ finally:
+ self.state = 'AUTH'
+ return typ, dat
+
+
+ def copy(self, message_set, new_mailbox):
+ """Copy 'message_set' messages onto end of 'new_mailbox'.
+
+ (typ, [data]) = .copy(message_set, new_mailbox)
+ """
+ return self._simple_command('COPY', message_set, new_mailbox)
+
+
+ def create(self, mailbox):
+ """Create new mailbox.
+
+ (typ, [data]) = .create(mailbox)
+ """
+ return self._simple_command('CREATE', mailbox)
+
+
+ def delete(self, mailbox):
+ """Delete old mailbox.
+
+ (typ, [data]) = .delete(mailbox)
+ """
+ return self._simple_command('DELETE', mailbox)
+
+ def deleteacl(self, mailbox, who):
+ """Delete the ACLs (remove any rights) set for who on mailbox.
+
+ (typ, [data]) = .deleteacl(mailbox, who)
+ """
+ return self._simple_command('DELETEACL', mailbox, who)
+
+ def enable(self, capability):
+ """Send an RFC5161 enable string to the server.
+
+ (typ, [data]) = .enable(capability)
+ """
+ if 'ENABLE' not in self.capabilities:
+ raise IMAP4.error("Server does not support ENABLE")
+ typ, data = self._simple_command('ENABLE', capability)
+ if typ == 'OK' and 'UTF8=ACCEPT' in capability.upper():
+ self._mode_utf8()
+ return typ, data
+
+ def expunge(self):
+ """Permanently remove deleted items from selected mailbox.
+
+ Generates 'EXPUNGE' response for each deleted message.
+
+ (typ, [data]) = .expunge()
+
+ 'data' is list of 'EXPUNGE'd message numbers in order received.
+ """
+ name = 'EXPUNGE'
+ typ, dat = self._simple_command(name)
+ return self._untagged_response(typ, dat, name)
+
+
+ def fetch(self, message_set, message_parts):
+ """Fetch (parts of) messages.
+
+ (typ, [data, ...]) = .fetch(message_set, message_parts)
+
+ 'message_parts' should be a string of selected parts
+ enclosed in parentheses, eg: "(UID BODY[TEXT])".
+
+ 'data' are tuples of message part envelope and data.
+ """
+ name = 'FETCH'
+ typ, dat = self._simple_command(name, message_set, message_parts)
+ return self._untagged_response(typ, dat, name)
+
+
+ def getacl(self, mailbox):
+ """Get the ACLs for a mailbox.
+
+ (typ, [data]) = .getacl(mailbox)
+ """
+ typ, dat = self._simple_command('GETACL', mailbox)
+ return self._untagged_response(typ, dat, 'ACL')
+
+
+ def getannotation(self, mailbox, entry, attribute):
+ """(typ, [data]) = .getannotation(mailbox, entry, attribute)
+ Retrieve ANNOTATIONs."""
+
+ typ, dat = self._simple_command('GETANNOTATION', mailbox, entry, attribute)
+ return self._untagged_response(typ, dat, 'ANNOTATION')
+
+
+ def getquota(self, root):
+ """Get the quota root's resource usage and limits.
+
+ Part of the IMAP4 QUOTA extension defined in rfc2087.
+
+ (typ, [data]) = .getquota(root)
+ """
+ typ, dat = self._simple_command('GETQUOTA', root)
+ return self._untagged_response(typ, dat, 'QUOTA')
+
+
+ def getquotaroot(self, mailbox):
+ """Get the list of quota roots for the named mailbox.
+
+ (typ, [[QUOTAROOT responses...], [QUOTA responses]]) = .getquotaroot(mailbox)
+ """
+ typ, dat = self._simple_command('GETQUOTAROOT', mailbox)
+ typ, quota = self._untagged_response(typ, dat, 'QUOTA')
+ typ, quotaroot = self._untagged_response(typ, dat, 'QUOTAROOT')
+ return typ, [quotaroot, quota]
+
+
+ def idle(self, duration=None):
+ """Return an iterable IDLE context manager producing untagged responses.
+ If the argument is not None, limit iteration to 'duration' seconds.
+
+ with M.idle(duration=29 * 60) as idler:
+ for typ, data in idler:
+ print(typ, data)
+
+ Note: 'duration' requires a socket connection (not IMAP4_stream).
+ """
+ return Idler(self, duration)
+
+
+ def list(self, directory='""', pattern='*'):
+ """List mailbox names in directory matching pattern.
+
+ (typ, [data]) = .list(directory='""', pattern='*')
+
+ 'data' is list of LIST responses.
+ """
+ name = 'LIST'
+ typ, dat = self._simple_command(name, directory, pattern)
+ return self._untagged_response(typ, dat, name)
+
+
+ def login(self, user, password):
+ """Identify client using plaintext password.
+
+ (typ, [data]) = .login(user, password)
+
+ NB: 'password' will be quoted.
+ """
+ typ, dat = self._simple_command('LOGIN', user, self._quote(password))
+ if typ != 'OK':
+ raise self.error(dat[-1])
+ self.state = 'AUTH'
+ return typ, dat
+
+
+ def login_cram_md5(self, user, password):
+ """ Force use of CRAM-MD5 authentication.
+
+ (typ, [data]) = .login_cram_md5(user, password)
+ """
+ self.user, self.password = user, password
+ return self.authenticate('CRAM-MD5', self._CRAM_MD5_AUTH)
+
+
+ def _CRAM_MD5_AUTH(self, challenge):
+ """ Authobject to use with CRAM-MD5 authentication. """
+ import hmac
+
+ if isinstance(self.password, str):
+ password = self.password.encode('utf-8')
+ else:
+ password = self.password
+
+ try:
+ authcode = hmac.HMAC(password, challenge, 'md5')
+ except ValueError: # HMAC-MD5 is not available
+ raise self.error("CRAM-MD5 authentication is not supported")
+ return f"{self.user} {authcode.hexdigest()}"
+
+
+ def logout(self):
+ """Shutdown connection to server.
+
+ (typ, [data]) = .logout()
+
+ Returns server 'BYE' response.
+ """
+ self.state = 'LOGOUT'
+ typ, dat = self._simple_command('LOGOUT')
+ self.shutdown()
+ return typ, dat
+
+
+ def lsub(self, directory='""', pattern='*'):
+ """List 'subscribed' mailbox names in directory matching pattern.
+
+ (typ, [data, ...]) = .lsub(directory='""', pattern='*')
+
+ 'data' are tuples of message part envelope and data.
+ """
+ name = 'LSUB'
+ typ, dat = self._simple_command(name, directory, pattern)
+ return self._untagged_response(typ, dat, name)
+
+ def myrights(self, mailbox):
+ """Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
+
+ (typ, [data]) = .myrights(mailbox)
+ """
+ typ,dat = self._simple_command('MYRIGHTS', mailbox)
+ return self._untagged_response(typ, dat, 'MYRIGHTS')
+
+ def namespace(self):
+ """ Returns IMAP namespaces ala rfc2342
+
+ (typ, [data, ...]) = .namespace()
+ """
+ name = 'NAMESPACE'
+ typ, dat = self._simple_command(name)
+ return self._untagged_response(typ, dat, name)
+
+
+ def noop(self):
+ """Send NOOP command.
+
+ (typ, [data]) = .noop()
+ """
+ if __debug__:
+ if self.debug >= 3:
+ self._dump_ur(self.untagged_responses)
+ return self._simple_command('NOOP')
+
+
+ def partial(self, message_num, message_part, start, length):
+ """Fetch truncated part of a message.
+
+ (typ, [data, ...]) = .partial(message_num, message_part, start, length)
+
+ 'data' is tuple of message part envelope and data.
+ """
+ name = 'PARTIAL'
+ typ, dat = self._simple_command(name, message_num, message_part, start, length)
+ return self._untagged_response(typ, dat, 'FETCH')
+
+
+ def proxyauth(self, user):
+ """Assume authentication as "user".
+
+ Allows an authorised administrator to proxy into any user's
+ mailbox.
+
+ (typ, [data]) = .proxyauth(user)
+ """
+
+ name = 'PROXYAUTH'
+ return self._simple_command('PROXYAUTH', user)
+
+
+ def rename(self, oldmailbox, newmailbox):
+ """Rename old mailbox name to new.
+
+ (typ, [data]) = .rename(oldmailbox, newmailbox)
+ """
+ return self._simple_command('RENAME', oldmailbox, newmailbox)
+
+
+ def search(self, charset, *criteria):
+ """Search mailbox for matching messages.
+
+ (typ, [data]) = .search(charset, criterion, ...)
+
+ 'data' is space separated list of matching message numbers.
+ If UTF8 is enabled, charset MUST be None.
+ """
+ name = 'SEARCH'
+ if charset:
+ if self.utf8_enabled:
+ raise IMAP4.error("Non-None charset not valid in UTF8 mode")
+ typ, dat = self._simple_command(name, 'CHARSET', charset, *criteria)
+ else:
+ typ, dat = self._simple_command(name, *criteria)
+ return self._untagged_response(typ, dat, name)
+
+
+ def select(self, mailbox='INBOX', readonly=False):
+ """Select a mailbox.
+
+ Flush all untagged responses.
+
+ (typ, [data]) = .select(mailbox='INBOX', readonly=False)
+
+ 'data' is count of messages in mailbox ('EXISTS' response).
+
+ Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so
+ other responses should be obtained via .response('FLAGS') etc.
+ """
+ self.untagged_responses = {} # Flush old responses.
+ self.is_readonly = readonly
+ if readonly:
+ name = 'EXAMINE'
+ else:
+ name = 'SELECT'
+ typ, dat = self._simple_command(name, mailbox)
+ if typ != 'OK':
+ self.state = 'AUTH' # Might have been 'SELECTED'
+ return typ, dat
+ self.state = 'SELECTED'
+ if 'READ-ONLY' in self.untagged_responses \
+ and not readonly:
+ if __debug__:
+ if self.debug >= 1:
+ self._dump_ur(self.untagged_responses)
+ raise self.readonly('%s is not writable' % mailbox)
+ return typ, self.untagged_responses.get('EXISTS', [None])
+
+
+ def setacl(self, mailbox, who, what):
+ """Set a mailbox acl.
+
+ (typ, [data]) = .setacl(mailbox, who, what)
+ """
+ return self._simple_command('SETACL', mailbox, who, what)
+
+
+ def setannotation(self, *args):
+ """(typ, [data]) = .setannotation(mailbox[, entry, attribute]+)
+ Set ANNOTATIONs."""
+
+ typ, dat = self._simple_command('SETANNOTATION', *args)
+ return self._untagged_response(typ, dat, 'ANNOTATION')
+
+
+ def setquota(self, root, limits):
+ """Set the quota root's resource limits.
+
+ (typ, [data]) = .setquota(root, limits)
+ """
+ typ, dat = self._simple_command('SETQUOTA', root, limits)
+ return self._untagged_response(typ, dat, 'QUOTA')
+
+
+ def sort(self, sort_criteria, charset, *search_criteria):
+ """IMAP4rev1 extension SORT command.
+
+ (typ, [data]) = .sort(sort_criteria, charset, search_criteria, ...)
+ """
+ name = 'SORT'
+ #if not name in self.capabilities: # Let the server decide!
+ # raise self.error('unimplemented extension command: %s' % name)
+ if (sort_criteria[0],sort_criteria[-1]) != ('(',')'):
+ sort_criteria = '(%s)' % sort_criteria
+ typ, dat = self._simple_command(name, sort_criteria, charset, *search_criteria)
+ return self._untagged_response(typ, dat, name)
+
+
+ def starttls(self, ssl_context=None):
+ name = 'STARTTLS'
+ if not HAVE_SSL:
+ raise self.error('SSL support missing')
+ if self._tls_established:
+ raise self.abort('TLS session already established')
+ if name not in self.capabilities:
+ raise self.abort('TLS not supported by server')
+ # Generate a default SSL context if none was passed.
+ if ssl_context is None:
+ ssl_context = ssl._create_stdlib_context()
+ typ, dat = self._simple_command(name)
+ if typ == 'OK':
+ self.sock = ssl_context.wrap_socket(self.sock,
+ server_hostname=self.host)
+ self._file = self.sock.makefile('rb')
+ self._tls_established = True
+ self._get_capabilities()
+ else:
+ raise self.error("Couldn't establish TLS session")
+ return self._untagged_response(typ, dat, name)
+
+
+ def status(self, mailbox, names):
+ """Request named status conditions for mailbox.
+
+ (typ, [data]) = .status(mailbox, names)
+ """
+ name = 'STATUS'
+ #if self.PROTOCOL_VERSION == 'IMAP4': # Let the server decide!
+ # raise self.error('%s unimplemented in IMAP4 (obtain IMAP4rev1 server, or re-code)' % name)
+ typ, dat = self._simple_command(name, mailbox, names)
+ return self._untagged_response(typ, dat, name)
+
+
+ def store(self, message_set, command, flags):
+ """Alters flag dispositions for messages in mailbox.
+
+ (typ, [data]) = .store(message_set, command, flags)
+ """
+ if (flags[0],flags[-1]) != ('(',')'):
+ flags = '(%s)' % flags # Avoid quoting the flags
+ typ, dat = self._simple_command('STORE', message_set, command, flags)
+ return self._untagged_response(typ, dat, 'FETCH')
+
+
+ def subscribe(self, mailbox):
+ """Subscribe to new mailbox.
+
+ (typ, [data]) = .subscribe(mailbox)
+ """
+ return self._simple_command('SUBSCRIBE', mailbox)
+
+
+ def thread(self, threading_algorithm, charset, *search_criteria):
+ """IMAPrev1 extension THREAD command.
+
+ (type, [data]) = .thread(threading_algorithm, charset, search_criteria, ...)
+ """
+ name = 'THREAD'
+ typ, dat = self._simple_command(name, threading_algorithm, charset, *search_criteria)
+ return self._untagged_response(typ, dat, name)
+
+
+ def uid(self, command, *args):
+ """Execute "command arg ..." with messages identified by UID,
+ rather than message number.
+
+ (typ, [data]) = .uid(command, arg1, arg2, ...)
+
+ Returns response appropriate to 'command'.
+ """
+ command = command.upper()
+ if not command in Commands:
+ raise self.error("Unknown IMAP4 UID command: %s" % command)
+ if self.state not in Commands[command]:
+ raise self.error("command %s illegal in state %s, "
+ "only allowed in states %s" %
+ (command, self.state,
+ ', '.join(Commands[command])))
+ name = 'UID'
+ typ, dat = self._simple_command(name, command, *args)
+ if command in ('SEARCH', 'SORT', 'THREAD'):
+ name = command
+ else:
+ name = 'FETCH'
+ return self._untagged_response(typ, dat, name)
+
+
+ def unsubscribe(self, mailbox):
+ """Unsubscribe from old mailbox.
+
+ (typ, [data]) = .unsubscribe(mailbox)
+ """
+ return self._simple_command('UNSUBSCRIBE', mailbox)
+
+
+ def unselect(self):
+ """Free server's resources associated with the selected mailbox
+ and returns the server to the authenticated state.
+ This command performs the same actions as CLOSE, except
+ that no messages are permanently removed from the currently
+ selected mailbox.
+
+ (typ, [data]) = .unselect()
+ """
+ try:
+ typ, data = self._simple_command('UNSELECT')
+ finally:
+ self.state = 'AUTH'
+ return typ, data
+
+
+ def xatom(self, name, *args):
+ """Allow simple extension commands
+ notified by server in CAPABILITY response.
+
+ Assumes command is legal in current state.
+
+ (typ, [data]) = .xatom(name, arg, ...)
+
+ Returns response appropriate to extension command 'name'.
+ """
+ name = name.upper()
+ #if not name in self.capabilities: # Let the server decide!
+ # raise self.error('unknown extension command: %s' % name)
+ if not name in Commands:
+ Commands[name] = (self.state,)
+ return self._simple_command(name, *args)
+
+
+
+ # Private methods
+
+
+ def _append_untagged(self, typ, dat):
+ if dat is None:
+ dat = b''
+
+ # During idle, queue untagged responses for delivery via iteration
+ if self._idle_capture:
+ # Responses containing literal strings are passed to us one data
+ # fragment at a time, while others arrive in a single call.
+ if (not self._idle_responses or
+ isinstance(self._idle_responses[-1][1][-1], bytes)):
+ # We are not continuing a fragmented response; start a new one
+ self._idle_responses.append((typ, [dat]))
+ else:
+ # We are continuing a fragmented response; append the fragment
+ response = self._idle_responses[-1]
+ assert response[0] == typ
+ response[1].append(dat)
+ if __debug__ and self.debug >= 5:
+ self._mesg(f'idle: queue untagged {typ} {dat!r}')
+ return
+
+ ur = self.untagged_responses
+ if __debug__:
+ if self.debug >= 5:
+ self._mesg('untagged_responses[%s] %s += ["%r"]' %
+ (typ, len(ur.get(typ,'')), dat))
+ if typ in ur:
+ ur[typ].append(dat)
+ else:
+ ur[typ] = [dat]
+
+
+ def _check_bye(self):
+ bye = self.untagged_responses.get('BYE')
+ if bye:
+ raise self.abort(bye[-1].decode(self._encoding, 'replace'))
+
+
+ def _command(self, name, *args):
+
+ if self.state not in Commands[name]:
+ self.literal = None
+ raise self.error("command %s illegal in state %s, "
+ "only allowed in states %s" %
+ (name, self.state,
+ ', '.join(Commands[name])))
+
+ for typ in ('OK', 'NO', 'BAD'):
+ if typ in self.untagged_responses:
+ del self.untagged_responses[typ]
+
+ if 'READ-ONLY' in self.untagged_responses \
+ and not self.is_readonly:
+ raise self.readonly('mailbox status changed to READ-ONLY')
+
+ tag = self._new_tag()
+ name = bytes(name, self._encoding)
+ data = tag + b' ' + name
+ for arg in args:
+ if arg is None: continue
+ if isinstance(arg, str):
+ arg = bytes(arg, self._encoding)
+ data = data + b' ' + arg
+
+ literal = self.literal
+ if literal is not None:
+ self.literal = None
+ if type(literal) is type(self._command):
+ literator = literal
+ else:
+ literator = None
+ if self.utf8_enabled:
+ data = data + bytes(' UTF8 (~{%s}' % len(literal), self._encoding)
+ literal = literal + b')'
+ else:
+ data = data + bytes(' {%s}' % len(literal), self._encoding)
+
+ if __debug__:
+ if self.debug >= 4:
+ self._mesg('> %r' % data)
+ else:
+ self._log('> %r' % data)
+
+ try:
+ self.send(data + CRLF)
+ except OSError as val:
+ raise self.abort('socket error: %s' % val)
+
+ if literal is None:
+ return tag
+
+ while 1:
+ # Wait for continuation response
+
+ while self._get_response():
+ if self.tagged_commands[tag]: # BAD/NO?
+ return tag
+
+ # Send literal
+
+ if literator:
+ literal = literator(self.continuation_response)
+
+ if __debug__:
+ if self.debug >= 4:
+ self._mesg('write literal size %s' % len(literal))
+
+ try:
+ self.send(literal)
+ self.send(CRLF)
+ except OSError as val:
+ raise self.abort('socket error: %s' % val)
+
+ if not literator:
+ break
+
+ return tag
+
+
+ def _command_complete(self, name, tag):
+ logout = (name == 'LOGOUT')
+ # BYE is expected after LOGOUT
+ if not logout:
+ self._check_bye()
+ try:
+ typ, data = self._get_tagged_response(tag, expect_bye=logout)
+ except self.abort as val:
+ raise self.abort('command: %s => %s' % (name, val))
+ except self.error as val:
+ raise self.error('command: %s => %s' % (name, val))
+ if not logout:
+ self._check_bye()
+ if typ == 'BAD':
+ raise self.error('%s command error: %s %s' % (name, typ, data))
+ return typ, data
+
+
+ def _get_capabilities(self):
+ typ, dat = self.capability()
+ if dat == [None]:
+ raise self.error('no CAPABILITY response from server')
+ dat = str(dat[-1], self._encoding)
+ dat = dat.upper()
+ self.capabilities = tuple(dat.split())
+
+
+ def _get_response(self, start_timeout=False):
+
+ # Read response and store.
+ #
+ # Returns None for continuation responses,
+ # otherwise first response line received.
+ #
+ # If start_timeout is given, temporarily uses it as a socket
+ # timeout while waiting for the start of a response, raising
+ # _responsetimeout if one doesn't arrive. (Used by Idler.)
+
+ if start_timeout is not False and self.sock:
+ assert start_timeout is None or start_timeout > 0
+ saved_timeout = self.sock.gettimeout()
+ self.sock.settimeout(start_timeout)
+ try:
+ resp = self._get_line()
+ except TimeoutError as err:
+ raise self._responsetimeout from err
+ finally:
+ self.sock.settimeout(saved_timeout)
+ else:
+ resp = self._get_line()
+
+ # Command completion response?
+
+ if self._match(self.tagre, resp):
+ tag = self.mo.group('tag')
+ if not tag in self.tagged_commands:
+ raise self.abort('unexpected tagged response: %r' % resp)
+
+ typ = self.mo.group('type')
+ typ = str(typ, self._encoding)
+ dat = self.mo.group('data')
+ self.tagged_commands[tag] = (typ, [dat])
+ else:
+ dat2 = None
+
+ # '*' (untagged) responses?
+
+ if not self._match(Untagged_response, resp):
+ if self._match(self.Untagged_status, resp):
+ dat2 = self.mo.group('data2')
+
+ if self.mo is None:
+ # Only other possibility is '+' (continuation) response...
+
+ if self._match(Continuation, resp):
+ self.continuation_response = self.mo.group('data')
+ return None # NB: indicates continuation
+
+ raise self.abort("unexpected response: %r" % resp)
+
+ typ = self.mo.group('type')
+ typ = str(typ, self._encoding)
+ dat = self.mo.group('data')
+ if dat is None: dat = b'' # Null untagged response
+ if dat2: dat = dat + b' ' + dat2
+
+ # Is there a literal to come?
+
+ while self._match(self.Literal, dat):
+
+ # Read literal direct from connection.
+
+ size = int(self.mo.group('size'))
+ if __debug__:
+ if self.debug >= 4:
+ self._mesg('read literal size %s' % size)
+ data = self.read(size)
+
+ # Store response with literal as tuple
+
+ self._append_untagged(typ, (dat, data))
+
+ # Read trailer - possibly containing another literal
+
+ dat = self._get_line()
+
+ self._append_untagged(typ, dat)
+
+ # Bracketed response information?
+
+ if typ in ('OK', 'NO', 'BAD') and self._match(Response_code, dat):
+ typ = self.mo.group('type')
+ typ = str(typ, self._encoding)
+ self._append_untagged(typ, self.mo.group('data'))
+
+ if __debug__:
+ if self.debug >= 1 and typ in ('NO', 'BAD', 'BYE'):
+ self._mesg('%s response: %r' % (typ, dat))
+
+ return resp
+
+
+ def _get_tagged_response(self, tag, expect_bye=False):
+
+ while 1:
+ result = self.tagged_commands[tag]
+ if result is not None:
+ del self.tagged_commands[tag]
+ return result
+
+ if expect_bye:
+ typ = 'BYE'
+ bye = self.untagged_responses.pop(typ, None)
+ if bye is not None:
+ # Server replies to the "LOGOUT" command with "BYE"
+ return (typ, bye)
+
+ # If we've seen a BYE at this point, the socket will be
+ # closed, so report the BYE now.
+ self._check_bye()
+
+ # Some have reported "unexpected response" exceptions.
+ # Note that ignoring them here causes loops.
+ # Instead, send me details of the unexpected response and
+ # I'll update the code in '_get_response()'.
+
+ try:
+ self._get_response()
+ except self.abort as val:
+ if __debug__:
+ if self.debug >= 1:
+ self.print_log()
+ raise
+
+
+ def _get_line(self):
+
+ line = self.readline()
+ if not line:
+ raise self.abort('socket error: EOF')
+
+ # Protocol mandates all lines terminated by CRLF
+ if not line.endswith(b'\r\n'):
+ raise self.abort('socket error: unterminated line: %r' % line)
+
+ line = line[:-2]
+ if __debug__:
+ if self.debug >= 4:
+ self._mesg('< %r' % line)
+ else:
+ self._log('< %r' % line)
+ return line
+
+
+ def _match(self, cre, s):
+
+ # Run compiled regular expression match method on 's'.
+ # Save result, return success.
+
+ self.mo = cre.match(s)
+ if __debug__:
+ if self.mo is not None and self.debug >= 5:
+ self._mesg("\tmatched %r => %r" % (cre.pattern, self.mo.groups()))
+ return self.mo is not None
+
+
+ def _new_tag(self):
+
+ tag = self.tagpre + bytes(str(self.tagnum), self._encoding)
+ self.tagnum = self.tagnum + 1
+ self.tagged_commands[tag] = None
+ return tag
+
+
+ def _quote(self, arg):
+
+ arg = arg.replace('\\', '\\\\')
+ arg = arg.replace('"', '\\"')
+
+ return '"' + arg + '"'
+
+
+ def _simple_command(self, name, *args):
+
+ return self._command_complete(name, self._command(name, *args))
+
+
+ def _untagged_response(self, typ, dat, name):
+ if typ == 'NO':
+ return typ, dat
+ if not name in self.untagged_responses:
+ return typ, [None]
+ data = self.untagged_responses.pop(name)
+ if __debug__:
+ if self.debug >= 5:
+ self._mesg('untagged_responses[%s] => %s' % (name, data))
+ return typ, data
+
+
+ if __debug__:
+
+ def _mesg(self, s, secs=None):
+ if secs is None:
+ secs = time.time()
+ tm = time.strftime('%M:%S', time.localtime(secs))
+ sys.stderr.write(' %s.%02d %s\n' % (tm, (secs*100)%100, s))
+ sys.stderr.flush()
+
+ def _dump_ur(self, untagged_resp_dict):
+ if not untagged_resp_dict:
+ return
+ items = (f'{key}: {value!r}'
+ for key, value in untagged_resp_dict.items())
+ self._mesg('untagged responses dump:' + '\n\t\t'.join(items))
+
+ def _log(self, line):
+ # Keep log of last '_cmd_log_len' interactions for debugging.
+ self._cmd_log[self._cmd_log_idx] = (line, time.time())
+ self._cmd_log_idx += 1
+ if self._cmd_log_idx >= self._cmd_log_len:
+ self._cmd_log_idx = 0
+
+ def print_log(self):
+ self._mesg('last %d IMAP4 interactions:' % len(self._cmd_log))
+ i, n = self._cmd_log_idx, self._cmd_log_len
+ while n:
+ try:
+ self._mesg(*self._cmd_log[i])
+ except:
+ pass
+ i += 1
+ if i >= self._cmd_log_len:
+ i = 0
+ n -= 1
+
+
+class Idler:
+ """Iterable IDLE context manager: start IDLE & produce untagged responses.
+
+ An object of this type is returned by the IMAP4.idle() method.
+
+ Note: The name and structure of this class are subject to change.
+ """
+
+ def __init__(self, imap, duration=None):
+ if 'IDLE' not in imap.capabilities:
+ raise imap.error("Server does not support IMAP4 IDLE")
+ if duration is not None and not imap.sock:
+ # IMAP4_stream pipes don't support timeouts
+ raise imap.error('duration requires a socket connection')
+ self._duration = duration
+ self._deadline = None
+ self._imap = imap
+ self._tag = None
+ self._saved_state = None
+
+ def __enter__(self):
+ imap = self._imap
+ assert not imap._idle_responses
+ assert not imap._idle_capture
+
+ if __debug__ and imap.debug >= 4:
+ imap._mesg(f'idle start duration={self._duration}')
+
+ # Start capturing untagged responses before sending IDLE,
+ # so we can deliver via iteration any that arrive while
+ # the IDLE command continuation request is still pending.
+ imap._idle_capture = True
+
+ try:
+ self._tag = imap._command('IDLE')
+ # As with any command, the server is allowed to send us unrelated,
+ # untagged responses before acting on IDLE. These lines will be
+ # returned by _get_response(). When the server is ready, it will
+ # send an IDLE continuation request, indicated by _get_response()
+ # returning None. We therefore process responses in a loop until
+ # this occurs.
+ while resp := imap._get_response():
+ if imap.tagged_commands[self._tag]:
+ typ, data = imap.tagged_commands.pop(self._tag)
+ if typ == 'NO':
+ raise imap.error(f'idle denied: {data}')
+ raise imap.abort(f'unexpected status response: {resp}')
+
+ if __debug__ and imap.debug >= 4:
+ prompt = imap.continuation_response
+ imap._mesg(f'idle continuation prompt: {prompt}')
+ except BaseException:
+ imap._idle_capture = False
+ raise
+
+ if self._duration is not None:
+ self._deadline = time.monotonic() + self._duration
+
+ self._saved_state = imap.state
+ imap.state = 'IDLING'
+
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ imap = self._imap
+
+ if __debug__ and imap.debug >= 4:
+ imap._mesg('idle done')
+ imap.state = self._saved_state
+
+ # Stop intercepting untagged responses before sending DONE,
+ # since we can no longer deliver them via iteration.
+ imap._idle_capture = False
+
+ # If we captured untagged responses while the IDLE command
+ # continuation request was still pending, but the user did not
+ # iterate over them before exiting IDLE, we must put them
+ # someplace where the user can retrieve them. The only
+ # sensible place for this is the untagged_responses dict,
+ # despite its unfortunate inability to preserve the relative
+ # order of different response types.
+ if leftovers := len(imap._idle_responses):
+ if __debug__ and imap.debug >= 4:
+ imap._mesg(f'idle quit with {leftovers} leftover responses')
+ while imap._idle_responses:
+ typ, data = imap._idle_responses.pop(0)
+ # Append one fragment at a time, just as _get_response() does
+ for datum in data:
+ imap._append_untagged(typ, datum)
+
+ try:
+ imap.send(b'DONE' + CRLF)
+ status, [msg] = imap._command_complete('IDLE', self._tag)
+ if __debug__ and imap.debug >= 4:
+ imap._mesg(f'idle status: {status} {msg!r}')
+ except OSError:
+ if not exc_type:
+ raise
+
+ return False # Do not suppress context body exceptions
+
+ def __iter__(self):
+ return self
+
+ def _pop(self, timeout, default=('', None)):
+ # Get the next response, or a default value on timeout.
+ # The timeout arg can be an int or float, or None for no timeout.
+ # Timeouts require a socket connection (not IMAP4_stream).
+ # This method ignores self._duration.
+
+ # Historical Note:
+ # The timeout was originally implemented using select() after
+ # checking for the presence of already-buffered data.
+ # That allowed timeouts on pipe connetions like IMAP4_stream.
+ # However, it seemed possible that SSL data arriving without any
+ # IMAP data afterward could cause select() to indicate available
+ # application data when there was none, leading to a read() call
+ # that would block with no timeout. It was unclear under what
+ # conditions this would happen in practice. Our implementation was
+ # changed to use socket timeouts instead of select(), just to be
+ # safe.
+
+ imap = self._imap
+ if imap.state != 'IDLING':
+ raise imap.error('_pop() only works during IDLE')
+
+ if imap._idle_responses:
+ # Response is ready to return to the user
+ resp = imap._idle_responses.pop(0)
+ if __debug__ and imap.debug >= 4:
+ imap._mesg(f'idle _pop({timeout}) de-queued {resp[0]}')
+ return resp
+
+ if __debug__ and imap.debug >= 4:
+ imap._mesg(f'idle _pop({timeout}) reading')
+
+ if timeout is not None:
+ if timeout <= 0:
+ return default
+ timeout = float(timeout) # Required by socket.settimeout()
+
+ try:
+ imap._get_response(timeout) # Reads line, calls _append_untagged()
+ except IMAP4._responsetimeout:
+ if __debug__ and imap.debug >= 4:
+ imap._mesg(f'idle _pop({timeout}) done')
+ return default
+
+ resp = imap._idle_responses.pop(0)
+
+ if __debug__ and imap.debug >= 4:
+ imap._mesg(f'idle _pop({timeout}) read {resp[0]}')
+ return resp
+
+ def __next__(self):
+ imap = self._imap
+
+ if self._duration is None:
+ timeout = None
+ else:
+ timeout = self._deadline - time.monotonic()
+ typ, data = self._pop(timeout)
+
+ if not typ:
+ if __debug__ and imap.debug >= 4:
+ imap._mesg('idle iterator exhausted')
+ raise StopIteration
+
+ return typ, data
+
+ def burst(self, interval=0.1):
+ """Yield a burst of responses no more than 'interval' seconds apart.
+
+ with M.idle() as idler:
+ # get a response and any others following by < 0.1 seconds
+ batch = list(idler.burst())
+ print(f'processing {len(batch)} responses...')
+ print(batch)
+
+ Note: This generator requires a socket connection (not IMAP4_stream).
+ """
+ if not self._imap.sock:
+ raise self._imap.error('burst() requires a socket connection')
+
+ try:
+ yield next(self)
+ except StopIteration:
+ return
+
+ while response := self._pop(interval, None):
+ yield response
+
+
+if HAVE_SSL:
+
+ class IMAP4_SSL(IMAP4):
+
+ """IMAP4 client class over SSL connection
+
+ Instantiate with: IMAP4_SSL([host[, port[, ssl_context[, timeout=None]]]])
+
+ host - host's name (default: localhost);
+ port - port number (default: standard IMAP4 SSL port);
+ ssl_context - a SSLContext object that contains your certificate chain
+ and private key (default: None)
+ timeout - socket timeout (default: None) If timeout is not given or is None,
+ the global default socket timeout is used
+
+ for more documentation see the docstring of the parent class IMAP4.
+ """
+
+
+ def __init__(self, host='', port=IMAP4_SSL_PORT,
+ *, ssl_context=None, timeout=None):
+ if ssl_context is None:
+ ssl_context = ssl._create_stdlib_context()
+ self.ssl_context = ssl_context
+ IMAP4.__init__(self, host, port, timeout)
+
+ def _create_socket(self, timeout):
+ sock = IMAP4._create_socket(self, timeout)
+ return self.ssl_context.wrap_socket(sock,
+ server_hostname=self.host)
+
+ def open(self, host='', port=IMAP4_SSL_PORT, timeout=None):
+ """Setup connection to remote server on "host:port".
+ (default: localhost:standard IMAP4 SSL port).
+ This connection will be used by the routines:
+ read, readline, send, shutdown.
+ """
+ IMAP4.open(self, host, port, timeout)
+
+ __all__.append("IMAP4_SSL")
+
+
+class IMAP4_stream(IMAP4):
+
+ """IMAP4 client class over a stream
+
+ Instantiate with: IMAP4_stream(command)
+
+ "command" - a string that can be passed to subprocess.Popen()
+
+ for more documentation see the docstring of the parent class IMAP4.
+ """
+
+
+ def __init__(self, command):
+ self.command = command
+ IMAP4.__init__(self)
+
+
+ def open(self, host=None, port=None, timeout=None):
+ """Setup a stream connection.
+ This connection will be used by the routines:
+ read, readline, send, shutdown.
+ """
+ self.host = None # For compatibility with parent class
+ self.port = None
+ self.sock = None
+ self._file = None
+ self.process = subprocess.Popen(self.command,
+ bufsize=DEFAULT_BUFFER_SIZE,
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ shell=True, close_fds=True)
+ self.writefile = self.process.stdin
+ self.readfile = self.process.stdout
+
+ def read(self, size):
+ """Read 'size' bytes from remote."""
+ return self.readfile.read(size)
+
+
+ def readline(self):
+ """Read line from remote."""
+ return self.readfile.readline()
+
+
+ def send(self, data):
+ """Send data to remote."""
+ self.writefile.write(data)
+ self.writefile.flush()
+
+
+ def shutdown(self):
+ """Close I/O established in "open"."""
+ self.readfile.close()
+ self.writefile.close()
+ self.process.wait()
+
+
+
+class _Authenticator:
+
+ """Private class to provide en/decoding
+ for base64-based authentication conversation.
+ """
+
+ def __init__(self, mechinst):
+ self.mech = mechinst # Callable object to provide/process data
+
+ def process(self, data):
+ ret = self.mech(self.decode(data))
+ if ret is None:
+ return b'*' # Abort conversation
+ return self.encode(ret)
+
+ def encode(self, inp):
+ #
+ # Invoke binascii.b2a_base64 iteratively with
+ # short even length buffers, strip the trailing
+ # line feed from the result and append. "Even"
+ # means a number that factors to both 6 and 8,
+ # so when it gets to the end of the 8-bit input
+ # there's no partial 6-bit output.
+ #
+ oup = b''
+ if isinstance(inp, str):
+ inp = inp.encode('utf-8')
+ while inp:
+ if len(inp) > 48:
+ t = inp[:48]
+ inp = inp[48:]
+ else:
+ t = inp
+ inp = b''
+ e = binascii.b2a_base64(t)
+ if e:
+ oup = oup + e[:-1]
+ return oup
+
+ def decode(self, inp):
+ if not inp:
+ return b''
+ return binascii.a2b_base64(inp)
+
+Months = ' Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ')
+Mon2num = {s.encode():n+1 for n, s in enumerate(Months[1:])}
+
+def Internaldate2tuple(resp):
+ """Parse an IMAP4 INTERNALDATE string.
+
+ Return corresponding local time. The return value is a
+ time.struct_time tuple or None if the string has wrong format.
+ """
+
+ mo = InternalDate.match(resp)
+ if not mo:
+ return None
+
+ mon = Mon2num[mo.group('mon')]
+ zonen = mo.group('zonen')
+
+ day = int(mo.group('day'))
+ year = int(mo.group('year'))
+ hour = int(mo.group('hour'))
+ min = int(mo.group('min'))
+ sec = int(mo.group('sec'))
+ zoneh = int(mo.group('zoneh'))
+ zonem = int(mo.group('zonem'))
+
+ # INTERNALDATE timezone must be subtracted to get UT
+
+ zone = (zoneh*60 + zonem)*60
+ if zonen == b'-':
+ zone = -zone
+
+ tt = (year, mon, day, hour, min, sec, -1, -1, -1)
+ utc = calendar.timegm(tt) - zone
+
+ return time.localtime(utc)
+
+
+
+def Int2AP(num):
+
+ """Convert integer to A-P string representation."""
+
+ val = b''; AP = b'ABCDEFGHIJKLMNOP'
+ num = int(abs(num))
+ while num:
+ num, mod = divmod(num, 16)
+ val = AP[mod:mod+1] + val
+ return val
+
+
+
+def ParseFlags(resp):
+
+ """Convert IMAP4 flags response to python tuple."""
+
+ mo = Flags.match(resp)
+ if not mo:
+ return ()
+
+ return tuple(mo.group('flags').split())
+
+
+def Time2Internaldate(date_time):
+
+ """Convert date_time to IMAP4 INTERNALDATE representation.
+
+ Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'. The
+ date_time argument can be a number (int or float) representing
+ seconds since epoch (as returned by time.time()), a 9-tuple
+ representing local time, an instance of time.struct_time (as
+ returned by time.localtime()), an aware datetime instance or a
+ double-quoted string. In the last case, it is assumed to already
+ be in the correct format.
+ """
+ if isinstance(date_time, (int, float)):
+ dt = datetime.fromtimestamp(date_time,
+ timezone.utc).astimezone()
+ elif isinstance(date_time, tuple):
+ try:
+ gmtoff = date_time.tm_gmtoff
+ except AttributeError:
+ if time.daylight:
+ dst = date_time[8]
+ if dst == -1:
+ dst = time.localtime(time.mktime(date_time))[8]
+ gmtoff = -(time.timezone, time.altzone)[dst]
+ else:
+ gmtoff = -time.timezone
+ delta = timedelta(seconds=gmtoff)
+ dt = datetime(*date_time[:6], tzinfo=timezone(delta))
+ elif isinstance(date_time, datetime):
+ if date_time.tzinfo is None:
+ raise ValueError("date_time must be aware")
+ dt = date_time
+ elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'):
+ return date_time # Assume in correct format
+ else:
+ raise ValueError("date_time not of a known type")
+ fmt = '"%d-{}-%Y %H:%M:%S %z"'.format(Months[dt.month])
+ return dt.strftime(fmt)
+
+
+
+if __name__ == '__main__':
+
+ # To test: invoke either as 'python imaplib.py [IMAP4_server_hostname]'
+ # or 'python imaplib.py -s "rsh IMAP4_server_hostname exec /etc/rimapd"'
+ # to test the IMAP4_stream class
+
+ import getopt, getpass
+
+ try:
+ optlist, args = getopt.getopt(sys.argv[1:], 'd:s:')
+ except getopt.error as val:
+ optlist, args = (), ()
+
+ stream_command = None
+ for opt,val in optlist:
+ if opt == '-d':
+ Debug = int(val)
+ elif opt == '-s':
+ stream_command = val
+ if not args: args = (stream_command,)
+
+ if not args: args = ('',)
+
+ host = args[0]
+
+ USER = getpass.getuser()
+ PASSWD = getpass.getpass("IMAP password for %s on %s: " % (USER, host or "localhost"))
+
+ test_mesg = 'From: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)sdata...%(lf)s' % {'user':USER, 'lf':'\n'}
+ test_seq1 = (
+ ('login', (USER, PASSWD)),
+ ('create', ('/tmp/xxx 1',)),
+ ('rename', ('/tmp/xxx 1', '/tmp/yyy')),
+ ('CREATE', ('/tmp/yyz 2',)),
+ ('append', ('/tmp/yyz 2', None, None, test_mesg)),
+ ('list', ('/tmp', 'yy*')),
+ ('select', ('/tmp/yyz 2',)),
+ ('search', (None, 'SUBJECT', 'test')),
+ ('fetch', ('1', '(FLAGS INTERNALDATE RFC822)')),
+ ('store', ('1', 'FLAGS', r'(\Deleted)')),
+ ('namespace', ()),
+ ('expunge', ()),
+ ('recent', ()),
+ ('close', ()),
+ )
+
+ test_seq2 = (
+ ('select', ()),
+ ('response',('UIDVALIDITY',)),
+ ('uid', ('SEARCH', 'ALL')),
+ ('response', ('EXISTS',)),
+ ('append', (None, None, None, test_mesg)),
+ ('recent', ()),
+ ('logout', ()),
+ )
+
+ def run(cmd, args):
+ M._mesg('%s %s' % (cmd, args))
+ typ, dat = getattr(M, cmd)(*args)
+ M._mesg('%s => %s %s' % (cmd, typ, dat))
+ if typ == 'NO': raise dat[0]
+ return dat
+
+ try:
+ if stream_command:
+ M = IMAP4_stream(stream_command)
+ else:
+ M = IMAP4(host)
+ if M.state == 'AUTH':
+ test_seq1 = test_seq1[1:] # Login not needed
+ M._mesg('PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION)
+ M._mesg('CAPABILITIES = %r' % (M.capabilities,))
+
+ for cmd,args in test_seq1:
+ run(cmd, args)
+
+ for ml in run('list', ('/tmp/', 'yy%')):
+ mo = re.match(r'.*"([^"]+)"$', ml)
+ if mo: path = mo.group(1)
+ else: path = ml.split()[-1]
+ run('delete', (path,))
+
+ for cmd,args in test_seq2:
+ dat = run(cmd, args)
+
+ if (cmd,args) != ('uid', ('SEARCH', 'ALL')):
+ continue
+
+ uid = dat[-1].split()
+ if not uid: continue
+ run('uid', ('FETCH', '%s' % uid[-1],
+ '(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)'))
+
+ print('\nAll tests OK.')
+
+ except:
+ print('\nTests failed.')
+
+ if not Debug:
+ print('''
+If you would like to see debugging output,
+try: %s -d5
+''' % sys.argv[0])
+
+ raise
diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/inspect.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/inspect.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d229051b4d3c4f0ef8b0d6dfa153fc609108557
--- /dev/null
+++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/python-3.14.4-h4b44e0e_100_cp314/Lib/inspect.py
@@ -0,0 +1,3409 @@
+"""Get useful information from live Python objects.
+
+This module encapsulates the interface provided by the internal special
+attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion.
+It also provides some help for examining source code and class layout.
+
+Here are some of the useful functions provided by this module:
+
+ ismodule(), isclass(), ismethod(), ispackage(), isfunction(),
+ isgeneratorfunction(), isgenerator(), istraceback(), isframe(),
+ iscode(), isbuiltin(), isroutine() - check object types
+ getmembers() - get members of an object that satisfy a given condition
+
+ getfile(), getsourcefile(), getsource() - find an object's source code
+ getdoc(), getcomments() - get documentation on an object
+ getmodule() - determine the module that an object came from
+ getclasstree() - arrange classes so as to represent their hierarchy
+
+ getargvalues(), getcallargs() - get info about function arguments
+ getfullargspec() - same, with support for Python 3 features
+ formatargvalues() - format an argument spec
+ getouterframes(), getinnerframes() - get info about frames
+ currentframe() - get the current stack frame
+ stack(), trace() - get info about frames on the stack or in a traceback
+
+ signature() - get a Signature object for the callable
+"""
+
+# This module is in the public domain. No warranties.
+
+__author__ = ('Ka-Ping Yee ',
+ 'Yury Selivanov ')
+
+__all__ = [
+ "AGEN_CLOSED",
+ "AGEN_CREATED",
+ "AGEN_RUNNING",
+ "AGEN_SUSPENDED",
+ "ArgInfo",
+ "Arguments",
+ "Attribute",
+ "BlockFinder",
+ "BoundArguments",
+ "BufferFlags",
+ "CORO_CLOSED",
+ "CORO_CREATED",
+ "CORO_RUNNING",
+ "CORO_SUSPENDED",
+ "CO_ASYNC_GENERATOR",
+ "CO_COROUTINE",
+ "CO_GENERATOR",
+ "CO_ITERABLE_COROUTINE",
+ "CO_NESTED",
+ "CO_NEWLOCALS",
+ "CO_NOFREE",
+ "CO_OPTIMIZED",
+ "CO_VARARGS",
+ "CO_VARKEYWORDS",
+ "CO_HAS_DOCSTRING",
+ "CO_METHOD",
+ "ClassFoundException",
+ "ClosureVars",
+ "EndOfBlock",
+ "FrameInfo",
+ "FullArgSpec",
+ "GEN_CLOSED",
+ "GEN_CREATED",
+ "GEN_RUNNING",
+ "GEN_SUSPENDED",
+ "Parameter",
+ "Signature",
+ "TPFLAGS_IS_ABSTRACT",
+ "Traceback",
+ "classify_class_attrs",
+ "cleandoc",
+ "currentframe",
+ "findsource",
+ "formatannotation",
+ "formatannotationrelativeto",
+ "formatargvalues",
+ "get_annotations",
+ "getabsfile",
+ "getargs",
+ "getargvalues",
+ "getasyncgenlocals",
+ "getasyncgenstate",
+ "getattr_static",
+ "getblock",
+ "getcallargs",
+ "getclasstree",
+ "getclosurevars",
+ "getcomments",
+ "getcoroutinelocals",
+ "getcoroutinestate",
+ "getdoc",
+ "getfile",
+ "getframeinfo",
+ "getfullargspec",
+ "getgeneratorlocals",
+ "getgeneratorstate",
+ "getinnerframes",
+ "getlineno",
+ "getmembers",
+ "getmembers_static",
+ "getmodule",
+ "getmodulename",
+ "getmro",
+ "getouterframes",
+ "getsource",
+ "getsourcefile",
+ "getsourcelines",
+ "indentsize",
+ "isabstract",
+ "isasyncgen",
+ "isasyncgenfunction",
+ "isawaitable",
+ "isbuiltin",
+ "isclass",
+ "iscode",
+ "iscoroutine",
+ "iscoroutinefunction",
+ "isdatadescriptor",
+ "isframe",
+ "isfunction",
+ "isgenerator",
+ "isgeneratorfunction",
+ "isgetsetdescriptor",
+ "ismemberdescriptor",
+ "ismethod",
+ "ismethoddescriptor",
+ "ismethodwrapper",
+ "ismodule",
+ "ispackage",
+ "isroutine",
+ "istraceback",
+ "markcoroutinefunction",
+ "signature",
+ "stack",
+ "trace",
+ "unwrap",
+ "walktree",
+]
+
+
+import abc
+from annotationlib import Format, ForwardRef
+from annotationlib import get_annotations # re-exported
+import ast
+import dis
+import collections.abc
+import enum
+import importlib.machinery
+import itertools
+import linecache
+import os
+import re
+import sys
+import tokenize
+import token
+import types
+import functools
+import builtins
+from keyword import iskeyword
+from operator import attrgetter
+from collections import namedtuple, OrderedDict
+from weakref import ref as make_weakref
+
+# Create constants for the compiler flags in Include/code.h
+# We try to get them from dis to avoid duplication
+mod_dict = globals()
+for k, v in dis.COMPILER_FLAG_NAMES.items():
+ mod_dict["CO_" + v] = k
+del k, v, mod_dict
+
+# See Include/object.h
+TPFLAGS_IS_ABSTRACT = 1 << 20
+
+
+# ----------------------------------------------------------- type-checking
+def ismodule(object):
+ """Return true if the object is a module."""
+ return isinstance(object, types.ModuleType)
+
+def isclass(object):
+ """Return true if the object is a class."""
+ return isinstance(object, type)
+
+def ismethod(object):
+ """Return true if the object is an instance method."""
+ return isinstance(object, types.MethodType)
+
+def ispackage(object):
+ """Return true if the object is a package."""
+ return ismodule(object) and hasattr(object, "__path__")
+
+def ismethoddescriptor(object):
+ """Return true if the object is a method descriptor.
+
+ But not if ismethod() or isclass() or isfunction() are true.
+
+ This is new in Python 2.2, and, for example, is true of int.__add__.
+ An object passing this test has a __get__ attribute, but not a
+ __set__ attribute or a __delete__ attribute. Beyond that, the set
+ of attributes varies; __name__ is usually sensible, and __doc__
+ often is.
+
+ Methods implemented via descriptors that also pass one of the other
+ tests return false from the ismethoddescriptor() test, simply because
+ the other tests promise more -- you can, e.g., count on having the
+ __func__ attribute (etc) when an object passes ismethod()."""
+ if isclass(object) or ismethod(object) or isfunction(object):
+ # mutual exclusion
+ return False
+ tp = type(object)
+ return (hasattr(tp, "__get__")
+ and not hasattr(tp, "__set__")
+ and not hasattr(tp, "__delete__"))
+
+def isdatadescriptor(object):
+ """Return true if the object is a data descriptor.
+
+ Data descriptors have a __set__ or a __delete__ attribute. Examples are
+ properties (defined in Python) and getsets and members (defined in C).
+ Typically, data descriptors will also have __name__ and __doc__ attributes
+ (properties, getsets, and members have both of these attributes), but this
+ is not guaranteed."""
+ if isclass(object) or ismethod(object) or isfunction(object):
+ # mutual exclusion
+ return False
+ tp = type(object)
+ return hasattr(tp, "__set__") or hasattr(tp, "__delete__")
+
+if hasattr(types, 'MemberDescriptorType'):
+ # CPython and equivalent
+ def ismemberdescriptor(object):
+ """Return true if the object is a member descriptor.
+
+ Member descriptors are specialized descriptors defined in extension
+ modules."""
+ return isinstance(object, types.MemberDescriptorType)
+else:
+ # Other implementations
+ def ismemberdescriptor(object):
+ """Return true if the object is a member descriptor.
+
+ Member descriptors are specialized descriptors defined in extension
+ modules."""
+ return False
+
+if hasattr(types, 'GetSetDescriptorType'):
+ # CPython and equivalent
+ def isgetsetdescriptor(object):
+ """Return true if the object is a getset descriptor.
+
+ getset descriptors are specialized descriptors defined in extension
+ modules."""
+ return isinstance(object, types.GetSetDescriptorType)
+else:
+ # Other implementations
+ def isgetsetdescriptor(object):
+ """Return true if the object is a getset descriptor.
+
+ getset descriptors are specialized descriptors defined in extension
+ modules."""
+ return False
+
+def isfunction(object):
+ """Return true if the object is a user-defined function.
+
+ Function objects provide these attributes:
+ __doc__ documentation string
+ __name__ name with which this function was defined
+ __qualname__ qualified name of this function
+ __module__ name of the module the function was defined in or None
+ __code__ code object containing compiled function bytecode
+ __defaults__ tuple of any default values for arguments
+ __globals__ global namespace in which this function was defined
+ __annotations__ dict of parameter annotations
+ __kwdefaults__ dict of keyword only parameters with defaults
+ __dict__ namespace which is supporting arbitrary function attributes
+ __closure__ a tuple of cells or None
+ __type_params__ tuple of type parameters"""
+ return isinstance(object, types.FunctionType)
+
+def _has_code_flag(f, flag):
+ """Return true if ``f`` is a function (or a method or functools.partial
+ wrapper wrapping a function or a functools.partialmethod wrapping a
+ function) whose code object has the given ``flag``
+ set in its flags."""
+ f = functools._unwrap_partialmethod(f)
+ while ismethod(f):
+ f = f.__func__
+ f = functools._unwrap_partial(f)
+ if not (isfunction(f) or _signature_is_functionlike(f)):
+ return False
+ return bool(f.__code__.co_flags & flag)
+
+def isgeneratorfunction(obj):
+ """Return true if the object is a user-defined generator function.
+
+ Generator function objects provide the same attributes as functions.
+ See help(isfunction) for a list of attributes."""
+ return _has_code_flag(obj, CO_GENERATOR)
+
+# A marker for markcoroutinefunction and iscoroutinefunction.
+_is_coroutine_mark = object()
+
+def _has_coroutine_mark(f):
+ while ismethod(f):
+ f = f.__func__
+ f = functools._unwrap_partial(f)
+ return getattr(f, "_is_coroutine_marker", None) is _is_coroutine_mark
+
+def markcoroutinefunction(func):
+ """
+ Decorator to ensure callable is recognised as a coroutine function.
+ """
+ if hasattr(func, '__func__'):
+ func = func.__func__
+ func._is_coroutine_marker = _is_coroutine_mark
+ return func
+
+def iscoroutinefunction(obj):
+ """Return true if the object is a coroutine function.
+
+ Coroutine functions are normally defined with "async def" syntax, but may
+ be marked via markcoroutinefunction.
+ """
+ return _has_code_flag(obj, CO_COROUTINE) or _has_coroutine_mark(obj)
+
+def isasyncgenfunction(obj):
+ """Return true if the object is an asynchronous generator function.
+
+ Asynchronous generator functions are defined with "async def"
+ syntax and have "yield" expressions in their body.
+ """
+ return _has_code_flag(obj, CO_ASYNC_GENERATOR)
+
+def isasyncgen(object):
+ """Return true if the object is an asynchronous generator."""
+ return isinstance(object, types.AsyncGeneratorType)
+
+def isgenerator(object):
+ """Return true if the object is a generator.
+
+ Generator objects provide these attributes:
+ gi_code code object
+ gi_frame frame object or possibly None once the generator has
+ been exhausted
+ gi_running set to 1 when generator is executing, 0 otherwise
+ gi_suspended set to 1 when the generator is suspended at a yield point, 0 otherwise
+ gi_yieldfrom object being iterated by yield from or None
+
+ __iter__() defined to support iteration over container
+ close() raises a new GeneratorExit exception inside the
+ generator to terminate the iteration
+ send() resumes the generator and "sends" a value that becomes
+ the result of the current yield-expression
+ throw() used to raise an exception inside the generator"""
+ return isinstance(object, types.GeneratorType)
+
+def iscoroutine(object):
+ """Return true if the object is a coroutine."""
+ return isinstance(object, types.CoroutineType)
+
+def isawaitable(object):
+ """Return true if object can be passed to an ``await`` expression."""
+ return (isinstance(object, types.CoroutineType) or
+ isinstance(object, types.GeneratorType) and
+ bool(object.gi_code.co_flags & CO_ITERABLE_COROUTINE) or
+ isinstance(object, collections.abc.Awaitable))
+
+def istraceback(object):
+ """Return true if the object is a traceback.
+
+ Traceback objects provide these attributes:
+ tb_frame frame object at this level
+ tb_lasti index of last attempted instruction in bytecode
+ tb_lineno current line number in Python source code
+ tb_next next inner traceback object (called by this level)"""
+ return isinstance(object, types.TracebackType)
+
+def isframe(object):
+ """Return true if the object is a frame object.
+
+ Frame objects provide these attributes:
+ f_back next outer frame object (this frame's caller)
+ f_builtins built-in namespace seen by this frame
+ f_code code object being executed in this frame
+ f_globals global namespace seen by this frame
+ f_lasti index of last attempted instruction in bytecode
+ f_lineno current line number in Python source code
+ f_locals local namespace seen by this frame
+ f_trace tracing function for this frame, or None
+ f_trace_lines is a tracing event triggered for each source line?
+ f_trace_opcodes are per-opcode events being requested?
+
+ clear() used to clear all references to local variables"""
+ return isinstance(object, types.FrameType)
+
+def iscode(object):
+ """Return true if the object is a code object.
+
+ Code objects provide these attributes:
+ co_argcount number of arguments (not including *, ** args
+ or keyword only arguments)
+ co_code string of raw compiled bytecode
+ co_cellvars tuple of names of cell variables
+ co_consts tuple of constants used in the bytecode
+ co_filename name of file in which this code object was created
+ co_firstlineno number of first line in Python source code
+ co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
+ | 16=nested | 32=generator | 64=nofree | 128=coroutine
+ | 256=iterable_coroutine | 512=async_generator
+ | 0x4000000=has_docstring
+ co_freevars tuple of names of free variables
+ co_posonlyargcount number of positional only arguments
+ co_kwonlyargcount number of keyword only arguments (not including ** arg)
+ co_lnotab encoded mapping of line numbers to bytecode indices
+ co_name name with which this code object was defined
+ co_names tuple of names other than arguments and function locals
+ co_nlocals number of local variables
+ co_stacksize virtual machine stack space required
+ co_varnames tuple of names of arguments and local variables
+ co_qualname fully qualified function name
+
+ co_lines() returns an iterator that yields successive bytecode ranges
+ co_positions() returns an iterator of source code positions for each bytecode instruction
+ replace() returns a copy of the code object with a new values"""
+ return isinstance(object, types.CodeType)
+
+def isbuiltin(object):
+ """Return true if the object is a built-in function or method.
+
+ Built-in functions and methods provide these attributes:
+ __doc__ documentation string
+ __name__ original name of this function or method
+ __self__ instance to which a method is bound, or None"""
+ return isinstance(object, types.BuiltinFunctionType)
+
+def ismethodwrapper(object):
+ """Return true if the object is a method wrapper."""
+ return isinstance(object, types.MethodWrapperType)
+
+def isroutine(object):
+ """Return true if the object is any kind of function or method."""
+ return (isbuiltin(object)
+ or isfunction(object)
+ or ismethod(object)
+ or ismethoddescriptor(object)
+ or ismethodwrapper(object)
+ or isinstance(object, functools._singledispatchmethod_get))
+
+def isabstract(object):
+ """Return true if the object is an abstract base class (ABC)."""
+ if not isinstance(object, type):
+ return False
+ if object.__flags__ & TPFLAGS_IS_ABSTRACT:
+ return True
+ if not issubclass(type(object), abc.ABCMeta):
+ return False
+ if hasattr(object, '__abstractmethods__'):
+ # It looks like ABCMeta.__new__ has finished running;
+ # TPFLAGS_IS_ABSTRACT should have been accurate.
+ return False
+ # It looks like ABCMeta.__new__ has not finished running yet; we're
+ # probably in __init_subclass__. We'll look for abstractmethods manually.
+ for name, value in object.__dict__.items():
+ if getattr(value, "__isabstractmethod__", False):
+ return True
+ for base in object.__bases__:
+ for name in getattr(base, "__abstractmethods__", ()):
+ value = getattr(object, name, None)
+ if getattr(value, "__isabstractmethod__", False):
+ return True
+ return False
+
+def _getmembers(object, predicate, getter):
+ results = []
+ processed = set()
+ names = dir(object)
+ if isclass(object):
+ mro = getmro(object)
+ # add any DynamicClassAttributes to the list of names if object is a class;
+ # this may result in duplicate entries if, for example, a virtual
+ # attribute with the same name as a DynamicClassAttribute exists
+ try:
+ for base in object.__bases__:
+ for k, v in base.__dict__.items():
+ if isinstance(v, types.DynamicClassAttribute):
+ names.append(k)
+ except AttributeError:
+ pass
+ else:
+ mro = ()
+ for key in names:
+ # First try to get the value via getattr. Some descriptors don't
+ # like calling their __get__ (see bug #1785), so fall back to
+ # looking in the __dict__.
+ try:
+ value = getter(object, key)
+ # handle the duplicate key
+ if key in processed:
+ raise AttributeError
+ except AttributeError:
+ for base in mro:
+ if key in base.__dict__:
+ value = base.__dict__[key]
+ break
+ else:
+ # could be a (currently) missing slot member, or a buggy
+ # __dir__; discard and move on
+ continue
+ if not predicate or predicate(value):
+ results.append((key, value))
+ processed.add(key)
+ results.sort(key=lambda pair: pair[0])
+ return results
+
+def getmembers(object, predicate=None):
+ """Return all members of an object as (name, value) pairs sorted by name.
+ Optionally, only return members that satisfy a given predicate."""
+ return _getmembers(object, predicate, getattr)
+
+def getmembers_static(object, predicate=None):
+ """Return all members of an object as (name, value) pairs sorted by name
+ without triggering dynamic lookup via the descriptor protocol,
+ __getattr__ or __getattribute__. Optionally, only return members that
+ satisfy a given predicate.
+
+ Note: this function may not be able to retrieve all members
+ that getmembers can fetch (like dynamically created attributes)
+ and may find members that getmembers can't (like descriptors
+ that raise AttributeError). It can also return descriptor objects
+ instead of instance members in some cases.
+ """
+ return _getmembers(object, predicate, getattr_static)
+
+Attribute = namedtuple('Attribute', 'name kind defining_class object')
+
+def classify_class_attrs(cls):
+ """Return list of attribute-descriptor tuples.
+
+ For each name in dir(cls), the return list contains a 4-tuple
+ with these elements:
+
+ 0. The name (a string).
+
+ 1. The kind of attribute this is, one of these strings:
+ 'class method' created via classmethod()
+ 'static method' created via staticmethod()
+ 'property' created via property()
+ 'method' any other flavor of method or descriptor
+ 'data' not a method
+
+ 2. The class which defined this attribute (a class).
+
+ 3. The object as obtained by calling getattr; if this fails, or if the
+ resulting object does not live anywhere in the class' mro (including
+ metaclasses) then the object is looked up in the defining class's
+ dict (found by walking the mro).
+
+ If one of the items in dir(cls) is stored in the metaclass it will now
+ be discovered and not have None be listed as the class in which it was
+ defined. Any items whose home class cannot be discovered are skipped.
+ """
+
+ mro = getmro(cls)
+ metamro = getmro(type(cls)) # for attributes stored in the metaclass
+ metamro = tuple(cls for cls in metamro if cls not in (type, object))
+ class_bases = (cls,) + mro
+ all_bases = class_bases + metamro
+ names = dir(cls)
+ # :dd any DynamicClassAttributes to the list of names;
+ # this may result in duplicate entries if, for example, a virtual
+ # attribute with the same name as a DynamicClassAttribute exists.
+ for base in mro:
+ for k, v in base.__dict__.items():
+ if isinstance(v, types.DynamicClassAttribute) and v.fget is not None:
+ names.append(k)
+ result = []
+ processed = set()
+
+ for name in names:
+ # Get the object associated with the name, and where it was defined.
+ # Normal objects will be looked up with both getattr and directly in
+ # its class' dict (in case getattr fails [bug #1785], and also to look
+ # for a docstring).
+ # For DynamicClassAttributes on the second pass we only look in the
+ # class's dict.
+ #
+ # Getting an obj from the __dict__ sometimes reveals more than
+ # using getattr. Static and class methods are dramatic examples.
+ homecls = None
+ get_obj = None
+ dict_obj = None
+ if name not in processed:
+ try:
+ if name == '__dict__':
+ raise Exception("__dict__ is special, don't want the proxy")
+ get_obj = getattr(cls, name)
+ except Exception:
+ pass
+ else:
+ homecls = getattr(get_obj, "__objclass__", homecls)
+ if homecls not in class_bases:
+ # if the resulting object does not live somewhere in the
+ # mro, drop it and search the mro manually
+ homecls = None
+ last_cls = None
+ # first look in the classes
+ for srch_cls in class_bases:
+ srch_obj = getattr(srch_cls, name, None)
+ if srch_obj is get_obj:
+ last_cls = srch_cls
+ # then check the metaclasses
+ for srch_cls in metamro:
+ try:
+ srch_obj = srch_cls.__getattr__(cls, name)
+ except AttributeError:
+ continue
+ if srch_obj is get_obj:
+ last_cls = srch_cls
+ if last_cls is not None:
+ homecls = last_cls
+ for base in all_bases:
+ if name in base.__dict__:
+ dict_obj = base.__dict__[name]
+ if homecls not in metamro:
+ homecls = base
+ break
+ if homecls is None:
+ # unable to locate the attribute anywhere, most likely due to
+ # buggy custom __dir__; discard and move on
+ continue
+ obj = get_obj if get_obj is not None else dict_obj
+ # Classify the object or its descriptor.
+ if isinstance(dict_obj, (staticmethod, types.BuiltinMethodType)):
+ kind = "static method"
+ obj = dict_obj
+ elif isinstance(dict_obj, (classmethod, types.ClassMethodDescriptorType)):
+ kind = "class method"
+ obj = dict_obj
+ elif isinstance(dict_obj, property):
+ kind = "property"
+ obj = dict_obj
+ elif isroutine(obj):
+ kind = "method"
+ else:
+ kind = "data"
+ result.append(Attribute(name, kind, homecls, obj))
+ processed.add(name)
+ return result
+
+# ----------------------------------------------------------- class helpers
+
+def getmro(cls):
+ "Return tuple of base classes (including cls) in method resolution order."
+ return cls.__mro__
+
+# -------------------------------------------------------- function helpers
+
+def unwrap(func, *, stop=None):
+ """Get the object wrapped by *func*.
+
+ Follows the chain of :attr:`__wrapped__` attributes returning the last
+ object in the chain.
+
+ *stop* is an optional callback accepting an object in the wrapper chain
+ as its sole argument that allows the unwrapping to be terminated early if
+ the callback returns a true value. If the callback never returns a true
+ value, the last object in the chain is returned as usual. For example,
+ :func:`signature` uses this to stop unwrapping if any object in the
+ chain has a ``__signature__`` attribute defined.
+
+ :exc:`ValueError` is raised if a cycle is encountered.
+
+ """
+ f = func # remember the original func for error reporting
+ # Memoise by id to tolerate non-hashable objects, but store objects to
+ # ensure they aren't destroyed, which would allow their IDs to be reused.
+ memo = {id(f): f}
+ recursion_limit = sys.getrecursionlimit()
+ while not isinstance(func, type) and hasattr(func, '__wrapped__'):
+ if stop is not None and stop(func):
+ break
+ func = func.__wrapped__
+ id_func = id(func)
+ if (id_func in memo) or (len(memo) >= recursion_limit):
+ raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
+ memo[id_func] = func
+ return func
+
+# -------------------------------------------------- source code extraction
+def indentsize(line):
+ """Return the indent size, in spaces, at the start of a line of text."""
+ expline = line.expandtabs()
+ return len(expline) - len(expline.lstrip())
+
+def _findclass(func):
+ cls = sys.modules.get(func.__module__)
+ if cls is None:
+ return None
+ for name in func.__qualname__.split('.')[:-1]:
+ cls = getattr(cls, name)
+ if not isclass(cls):
+ return None
+ return cls
+
+def _finddoc(obj):
+ if isclass(obj):
+ for base in obj.__mro__:
+ if base is not object:
+ try:
+ doc = base.__doc__
+ except AttributeError:
+ continue
+ if doc is not None:
+ return doc
+ return None
+
+ if ismethod(obj):
+ name = obj.__func__.__name__
+ self = obj.__self__
+ if (isclass(self) and
+ getattr(getattr(self, name, None), '__func__') is obj.__func__):
+ # classmethod
+ cls = self
+ else:
+ cls = self.__class__
+ elif isfunction(obj):
+ name = obj.__name__
+ cls = _findclass(obj)
+ if cls is None or getattr(cls, name) is not obj:
+ return None
+ elif isbuiltin(obj):
+ name = obj.__name__
+ self = obj.__self__
+ if (isclass(self) and
+ self.__qualname__ + '.' + name == obj.__qualname__):
+ # classmethod
+ cls = self
+ else:
+ cls = self.__class__
+ # Should be tested before isdatadescriptor().
+ elif isinstance(obj, property):
+ name = obj.__name__
+ cls = _findclass(obj.fget)
+ if cls is None or getattr(cls, name) is not obj:
+ return None
+ elif ismethoddescriptor(obj) or isdatadescriptor(obj):
+ name = obj.__name__
+ cls = obj.__objclass__
+ if getattr(cls, name) is not obj:
+ return None
+ if ismemberdescriptor(obj):
+ slots = getattr(cls, '__slots__', None)
+ if isinstance(slots, dict) and name in slots:
+ return slots[name]
+ else:
+ return None
+ for base in cls.__mro__:
+ try:
+ doc = getattr(base, name).__doc__
+ except AttributeError:
+ continue
+ if doc is not None:
+ return doc
+ return None
+
+def getdoc(object):
+ """Get the documentation string for an object.
+
+ All tabs are expanded to spaces. To clean up docstrings that are
+ indented to line up with blocks of code, any whitespace than can be
+ uniformly removed from the second line onwards is removed."""
+ try:
+ doc = object.__doc__
+ except AttributeError:
+ return None
+ if doc is None:
+ try:
+ doc = _finddoc(object)
+ except (AttributeError, TypeError):
+ return None
+ if not isinstance(doc, str):
+ return None
+ return cleandoc(doc)
+
+def cleandoc(doc):
+ """Clean up indentation from docstrings.
+
+ Any whitespace that can be uniformly removed from the second line
+ onwards is removed."""
+ lines = doc.expandtabs().split('\n')
+
+ # Find minimum indentation of any non-blank lines after first line.
+ margin = sys.maxsize
+ for line in lines[1:]:
+ content = len(line.lstrip(' '))
+ if content:
+ indent = len(line) - content
+ margin = min(margin, indent)
+ # Remove indentation.
+ if lines:
+ lines[0] = lines[0].lstrip(' ')
+ if margin < sys.maxsize:
+ for i in range(1, len(lines)):
+ lines[i] = lines[i][margin:]
+ # Remove any trailing or leading blank lines.
+ while lines and not lines[-1]:
+ lines.pop()
+ while lines and not lines[0]:
+ lines.pop(0)
+ return '\n'.join(lines)
+
+
+def getfile(object):
+ """Work out which source or compiled file an object was defined in."""
+ if ismodule(object):
+ if getattr(object, '__file__', None):
+ return object.__file__
+ raise TypeError('{!r} is a built-in module'.format(object))
+ if isclass(object):
+ if hasattr(object, '__module__'):
+ module = sys.modules.get(object.__module__)
+ if getattr(module, '__file__', None):
+ return module.__file__
+ if object.__module__ == '__main__':
+ raise OSError('source code not available')
+ raise TypeError('{!r} is a built-in class'.format(object))
+ if ismethod(object):
+ object = object.__func__
+ if isfunction(object):
+ object = object.__code__
+ if istraceback(object):
+ object = object.tb_frame
+ if isframe(object):
+ object = object.f_code
+ if iscode(object):
+ return object.co_filename
+ raise TypeError('module, class, method, function, traceback, frame, or '
+ 'code object was expected, got {}'.format(
+ type(object).__name__))
+
+def getmodulename(path):
+ """Return the module name for a given file, or None."""
+ fname = os.path.basename(path)
+ # Check for paths that look like an actual module file
+ suffixes = [(-len(suffix), suffix)
+ for suffix in importlib.machinery.all_suffixes()]
+ suffixes.sort() # try longest suffixes first, in case they overlap
+ for neglen, suffix in suffixes:
+ if fname.endswith(suffix):
+ return fname[:neglen]
+ return None
+
+def getsourcefile(object):
+ """Return the filename that can be used to locate an object's source.
+ Return None if no way can be identified to get the source.
+ """
+ filename = getfile(object)
+ all_bytecode_suffixes = importlib.machinery.BYTECODE_SUFFIXES[:]
+ if any(filename.endswith(s) for s in all_bytecode_suffixes):
+ filename = (os.path.splitext(filename)[0] +
+ importlib.machinery.SOURCE_SUFFIXES[0])
+ elif any(filename.endswith(s) for s in
+ importlib.machinery.EXTENSION_SUFFIXES):
+ return None
+ elif filename.endswith(".fwork"):
+ # Apple mobile framework markers are another type of non-source file
+ return None
+
+ # return a filename found in the linecache even if it doesn't exist on disk
+ if filename in linecache.cache:
+ return filename
+ if os.path.exists(filename):
+ return filename
+ # only return a non-existent filename if the module has a PEP 302 loader
+ module = getmodule(object, filename)
+ if getattr(module, '__loader__', None) is not None:
+ return filename
+ elif getattr(getattr(module, "__spec__", None), "loader", None) is not None:
+ return filename
+
+def getabsfile(object, _filename=None):
+ """Return an absolute path to the source or compiled file for an object.
+
+ The idea is for each object to have a unique origin, so this routine
+ normalizes the result as much as possible."""
+ if _filename is None:
+ _filename = getsourcefile(object) or getfile(object)
+ return os.path.normcase(os.path.abspath(_filename))
+
+modulesbyfile = {}
+_filesbymodname = {}
+
+def getmodule(object, _filename=None):
+ """Return the module an object was defined in, or None if not found."""
+ if ismodule(object):
+ return object
+ if hasattr(object, '__module__'):
+ return sys.modules.get(object.__module__)
+
+ # Try the filename to modulename cache
+ if _filename is not None and _filename in modulesbyfile:
+ return sys.modules.get(modulesbyfile[_filename])
+ # Try the cache again with the absolute file name
+ try:
+ file = getabsfile(object, _filename)
+ except (TypeError, FileNotFoundError):
+ return None
+ if file in modulesbyfile:
+ return sys.modules.get(modulesbyfile[file])
+ # Update the filename to module name cache and check yet again
+ # Copy sys.modules in order to cope with changes while iterating
+ for modname, module in sys.modules.copy().items():
+ if ismodule(module) and hasattr(module, '__file__'):
+ f = module.__file__
+ if f == _filesbymodname.get(modname, None):
+ # Have already mapped this module, so skip it
+ continue
+ _filesbymodname[modname] = f
+ f = getabsfile(module)
+ # Always map to the name the module knows itself by
+ modulesbyfile[f] = modulesbyfile[
+ os.path.realpath(f)] = module.__name__
+ if file in modulesbyfile:
+ return sys.modules.get(modulesbyfile[file])
+ # Check the main module
+ main = sys.modules['__main__']
+ if not hasattr(object, '__name__'):
+ return None
+ if hasattr(main, object.__name__):
+ mainobject = getattr(main, object.__name__)
+ if mainobject is object:
+ return main
+ # Check builtins
+ builtin = sys.modules['builtins']
+ if hasattr(builtin, object.__name__):
+ builtinobject = getattr(builtin, object.__name__)
+ if builtinobject is object:
+ return builtin
+
+
+class ClassFoundException(Exception):
+ pass
+
+
+def findsource(object):
+ """Return the entire source file and starting line number for an object.
+
+ The argument may be a module, class, method, function, traceback, frame,
+ or code object. The source code is returned as a list of all the lines
+ in the file and the line number indexes a line in that list. An OSError
+ is raised if the source code cannot be retrieved."""
+
+ file = getsourcefile(object)
+ if file:
+ # Invalidate cache if needed.
+ linecache.checkcache(file)
+ else:
+ file = getfile(object)
+ # Allow filenames in form of "