# Copyright (c) 2010-2020 Benjamin Peterson # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE.
"""Utilities for writing code that runs on Python 2 and 3"""
if PY34: from importlib.util import spec_from_loader else:
spec_from_loader = None
def _add_doc(func, doc): """Add documentation to a function."""
func.__doc__ = doc
def _import_module(name): """Import module, returning the module after the last dot."""
__import__(name) return sys.modules[name]
class _LazyDescr(object):
def __init__(self, name):
self.name = name
def __get__(self, obj, tp):
result = self._resolve()
setattr(obj, self.name, result) # Invokes __set__. try: # This is a bit ugly, but it avoids running this again by # removing this descriptor.
delattr(obj.__class__, self.name) except AttributeError: pass return result
class MovedModule(_LazyDescr):
def __init__(self, name, old, new=None):
super(MovedModule, self).__init__(name) if PY3: if new isNone:
new = name
self.mod = new else:
self.mod = old
def find_module(self, fullname, path=None): if fullname in self.known_modules: return self returnNone
def find_spec(self, fullname, path, target=None): if fullname in self.known_modules: return spec_from_loader(fullname, self) returnNone
def __get_module(self, fullname): try: return self.known_modules[fullname] except KeyError: raise ImportError("This loader does not know module " + fullname)
def load_module(self, fullname): try: # in case of a reload return sys.modules[fullname] except KeyError: pass
mod = self.__get_module(fullname) if isinstance(mod, MovedModule):
mod = mod._resolve() else:
mod.__loader__ = self
sys.modules[fullname] = mod return mod
def is_package(self, fullname): """ Returntrue, if the named module is a package.
We need this method to get correct spec objects with
Python 3.4 (see PEP451) """ return hasattr(self.__get_module(fullname), "__path__")
def get_code(self, fullname): """Return None
Required, if is_package is implemented"""
self.__get_module(fullname) # eventually raises ImportError returnNone
get_source = get_code # same as get_code
for attr in _moved_attributes:
setattr(_MovedItems, attr.name, attr) if isinstance(attr, MovedModule):
_importer._add_module(attr, "moves." + attr.name) del attr
_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")
_add_doc(itervalues, "Return an iterator over the values of a dictionary.")
_add_doc(iteritems, "Return an iterator over the (key, value) pairs of a dictionary.")
_add_doc(iterlists, "Return an iterator over the (key, [values]) pairs of a dictionary.")
if PY3: def b(s): return s.encode("latin-1")
def u(s): return s
unichr = chr import struct
int2byte = struct.Struct(">B").pack del struct
byte2int = operator.itemgetter(0)
indexbytes = operator.getitem
iterbytes = iter import io
StringIO = io.StringIO
BytesIO = io.BytesIO del io
_assertCountEqual = "assertCountEqual" if sys.version_info[1] <= 1:
_assertRaisesRegex = "assertRaisesRegexp"
_assertRegex = "assertRegexpMatches"
_assertNotRegex = "assertNotRegexpMatches" else:
_assertRaisesRegex = "assertRaisesRegex"
_assertRegex = "assertRegex"
_assertNotRegex = "assertNotRegex" else: def b(s): return s # Workaround for standalone backslash
def reraise(tp, value, tb=None): try: if value isNone:
value = tp() if value.__traceback__ isnot tb: raise value.with_traceback(tb) raise value finally:
value = None
tb = None
else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ isNone:
frame = sys._getframe(1)
_globs_ = frame.f_globals if _locs_ isNone:
_locs_ = frame.f_locals del frame elif _locs_ isNone:
_locs_ = _globs_
exec("""exec _code_ in _globs_, _locs_""")
if sys.version_info[:2] > (3,):
exec_("""def raise_from(value, from_value): try: raise value from from_value finally:
value = None """) else: def raise_from(value, from_value): raise value
print_ = getattr(moves.builtins, "print", None) if print_ isNone: def print_(*args, **kwargs): """The new-style print function for Python 2.4 and 2.5."""
fp = kwargs.pop("file", sys.stdout) if fp isNone: return
def write(data): ifnot isinstance(data, basestring):
data = str(data) # If the file has an encoding, encode unicode with it. if (isinstance(fp, file) and
isinstance(data, unicode) and
fp.encoding isnotNone):
errors = getattr(fp, "errors", None) if errors isNone:
errors = "strict"
data = data.encode(fp.encoding, errors)
fp.write(data)
want_unicode = False
sep = kwargs.pop("sep", None) if sep isnotNone: if isinstance(sep, unicode):
want_unicode = True elifnot isinstance(sep, str): raise TypeError("sep must be None or a string")
end = kwargs.pop("end", None) if end isnotNone: if isinstance(end, unicode):
want_unicode = True elifnot isinstance(end, str): raise TypeError("end must be None or a string") if kwargs: raise TypeError("invalid keyword arguments to print()") ifnot want_unicode: for arg in args: if isinstance(arg, unicode):
want_unicode = True break if want_unicode:
newline = unicode("\n")
space = unicode(" ") else:
newline = "\n"
space = " " if sep isNone:
sep = space if end isNone:
end = newline for i, arg in enumerate(args): if i:
write(sep)
write(arg)
write(end) if sys.version_info[:2] < (3, 3):
_print = print_
def print_(*args, **kwargs):
fp = kwargs.get("file", sys.stdout)
flush = kwargs.pop("flush", False)
_print(*args, **kwargs) if flush and fp isnotNone:
fp.flush()
_add_doc(reraise, """Reraise an exception.""")
if sys.version_info[0:2] < (3, 4): # This does exactly the same what the :func:`py3:functools.update_wrapper` # function does on Python versions after 3.2. It sets the ``__wrapped__`` # attribute on ``wrapper`` object and it doesn't raise an error if any of # the attributes mentioned in ``assigned`` and ``updated`` are missing on # ``wrapped`` object. def _update_wrapper(wrapper, wrapped,
assigned=functools.WRAPPER_ASSIGNMENTS,
updated=functools.WRAPPER_UPDATES): for attr in assigned: try:
value = getattr(wrapped, attr) except AttributeError: continue else:
setattr(wrapper, attr, value) for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
wrapper.__wrapped__ = wrapped return wrapper
_update_wrapper.__doc__ = functools.update_wrapper.__doc__
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(type):
def __new__(cls, name, this_bases, d): if sys.version_info[:2] >= (3, 7): # This version introduced PEP 560 that requires a bit # of extra care (we mimic what is done by __build_class__).
resolved_bases = types.resolve_bases(bases) if resolved_bases isnot bases:
d['__orig_bases__'] = bases else:
resolved_bases = bases return meta(name, resolved_bases, d)
def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__') if slots isnotNone: if isinstance(slots, str):
slots = [slots] for slots_var in slots:
orig_vars.pop(slots_var)
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None) if hasattr(cls, '__qualname__'):
orig_vars['__qualname__'] = cls.__qualname__ return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper
def ensure_binary(s, encoding='utf-8', errors='strict'): """Coerce **s** to six.binary_type.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> encoded to `bytes`
- `bytes` -> `bytes` """ if isinstance(s, binary_type): return s if isinstance(s, text_type): return s.encode(encoding, errors) raise TypeError("not expecting type '%s'" % type(s))
def ensure_str(s, encoding='utf-8', errors='strict'): """Coerce *s* to `str`.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str` """ # Optimization: Fast return for the common case. if type(s) is str: return s if PY2 and isinstance(s, text_type): return s.encode(encoding, errors) elif PY3 and isinstance(s, binary_type): return s.decode(encoding, errors) elifnot isinstance(s, (text_type, binary_type)): raise TypeError("not expecting type '%s'" % type(s)) return s
def ensure_text(s, encoding='utf-8', errors='strict'): """Coerce *s* to six.text_type.
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str` """ if isinstance(s, binary_type): return s.decode(encoding, errors) elif isinstance(s, text_type): return s else: raise TypeError("not expecting type '%s'" % type(s))
def python_2_unicode_compatible(klass): """
A class decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class. """ if PY2: if'__str__'notin klass.__dict__: raise ValueError("@python_2_unicode_compatible cannot be applied " "to %s because it doesn't define __str__()." %
klass.__name__)
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8') return klass
# Complete the moves implementation. # This code is at the end of this module to speed up module loading. # Turn this module into a package.
__path__ = [] # required for PEP 302 and PEP 451
__package__ = __name__ # see PEP 366 @ReservedAssignment if globals().get("__spec__") isnotNone:
__spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable # Remove other six meta path importers, since they cause problems. This can # happen if six is removed from sys.modules and then reloaded. (Setuptools does # this for some reason.) if sys.meta_path: for i, importer in enumerate(sys.meta_path): # Here's some real nastiness: Another "instance" of the six module might # be floating around. Therefore, we can't use isinstance() to check for # the six meta path importer, since the other six instance will have # inserted an importer with different class. if (type(importer).__name__ == "_SixMetaPathImporter"and
importer.name == __name__): del sys.meta_path[i] break del i, importer # Finally, add the importer to the meta path import hook.
sys.meta_path.append(_importer)
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.