content
stringlengths
1
103k
path
stringlengths
8
216
filename
stringlengths
2
179
language
stringclasses
15 values
size_bytes
int64
2
189k
quality_score
float64
0.5
0.95
complexity
float64
0
1
documentation_ratio
float64
0
1
repository
stringclasses
5 values
stars
int64
0
1k
created_date
stringdate
2023-07-10 19:21:08
2025-07-09 19:11:45
license
stringclasses
4 values
is_test
bool
2 classes
file_hash
stringlengths
32
32
# defusedxml\n#\n# Copyright (c) 2013 by Christian Heimes <christian@python.org>\n# Licensed to PSF under a Contributor Agreement.\n# See https://www.python.org/psf/license for licensing details.\n"""Defused xml.etree.ElementTree facade\n"""\nfrom __future__ import print_function, absolute_import\n\nimport sys\nimport warnings\nfrom xml.etree.ElementTree import ParseError\nfrom xml.etree.ElementTree import TreeBuilder as _TreeBuilder\nfrom xml.etree.ElementTree import parse as _parse\nfrom xml.etree.ElementTree import tostring\n\nfrom .common import PY3\n\nif PY3:\n import importlib\nelse:\n from xml.etree.ElementTree import XMLParser as _XMLParser\n from xml.etree.ElementTree import iterparse as _iterparse\n\n\nfrom .common import (\n DTDForbidden,\n EntitiesForbidden,\n ExternalReferenceForbidden,\n _generate_etree_functions,\n)\n\n__origin__ = "xml.etree.ElementTree"\n\n\ndef _get_py3_cls():\n """Python 3.3 hides the pure Python code but defusedxml requires it.\n\n The code is based on test.support.import_fresh_module().\n """\n pymodname = "xml.etree.ElementTree"\n cmodname = "_elementtree"\n\n pymod = sys.modules.pop(pymodname, None)\n cmod = sys.modules.pop(cmodname, None)\n\n sys.modules[cmodname] = None\n try:\n pure_pymod = importlib.import_module(pymodname)\n finally:\n # restore module\n sys.modules[pymodname] = pymod\n if cmod is not None:\n sys.modules[cmodname] = cmod\n else:\n sys.modules.pop(cmodname, None)\n # restore attribute on original package\n etree_pkg = sys.modules["xml.etree"]\n if pymod is not None:\n etree_pkg.ElementTree = pymod\n elif hasattr(etree_pkg, "ElementTree"):\n del etree_pkg.ElementTree\n\n _XMLParser = pure_pymod.XMLParser\n _iterparse = pure_pymod.iterparse\n # patch pure module to use ParseError from C extension\n pure_pymod.ParseError = ParseError\n\n return _XMLParser, _iterparse\n\n\nif PY3:\n _XMLParser, _iterparse = _get_py3_cls()\n\n\n_sentinel = object()\n\n\nclass DefusedXMLParser(_XMLParser):\n def __init__(\n self,\n html=_sentinel,\n target=None,\n encoding=None,\n forbid_dtd=False,\n forbid_entities=True,\n forbid_external=True,\n ):\n # Python 2.x old style class\n _XMLParser.__init__(self, target=target, encoding=encoding)\n if html is not _sentinel:\n # the 'html' argument has been deprecated and ignored in all\n # supported versions of Python. Python 3.8 finally removed it.\n if html:\n raise TypeError("'html=True' is no longer supported.")\n else:\n warnings.warn(\n "'html' keyword argument is no longer supported. Pass "\n "in arguments as keyword arguments.",\n category=DeprecationWarning,\n )\n\n self.forbid_dtd = forbid_dtd\n self.forbid_entities = forbid_entities\n self.forbid_external = forbid_external\n if PY3:\n parser = self.parser\n else:\n parser = self._parser\n if self.forbid_dtd:\n parser.StartDoctypeDeclHandler = self.defused_start_doctype_decl\n if self.forbid_entities:\n parser.EntityDeclHandler = self.defused_entity_decl\n parser.UnparsedEntityDeclHandler = self.defused_unparsed_entity_decl\n if self.forbid_external:\n parser.ExternalEntityRefHandler = self.defused_external_entity_ref_handler\n\n def defused_start_doctype_decl(self, name, sysid, pubid, has_internal_subset):\n raise DTDForbidden(name, sysid, pubid)\n\n def defused_entity_decl(\n self, name, is_parameter_entity, value, base, sysid, pubid, notation_name\n ):\n raise EntitiesForbidden(name, value, base, sysid, pubid, notation_name)\n\n def defused_unparsed_entity_decl(self, name, base, sysid, pubid, notation_name):\n # expat 1.2\n raise EntitiesForbidden(name, None, base, sysid, pubid, notation_name) # pragma: no cover\n\n def defused_external_entity_ref_handler(self, context, base, sysid, pubid):\n raise ExternalReferenceForbidden(context, base, sysid, pubid)\n\n\n# aliases\n# XMLParse is a typo, keep it for backwards compatibility\nXMLTreeBuilder = XMLParse = XMLParser = DefusedXMLParser\n\nparse, iterparse, fromstring = _generate_etree_functions(\n DefusedXMLParser, _TreeBuilder, _parse, _iterparse\n)\nXML = fromstring\n\n\n__all__ = [\n "ParseError",\n "XML",\n "XMLParse",\n "XMLParser",\n "XMLTreeBuilder",\n "fromstring",\n "iterparse",\n "parse",\n "tostring",\n]\n
.venv\Lib\site-packages\defusedxml\ElementTree.py
ElementTree.py
Python
4,640
0.95
0.136364
0.112
node-utils
687
2024-11-08T17:13:39.582823
GPL-3.0
false
70b74b1b0b08c4804caa8efc486cdf85
# defusedxml\n#\n# Copyright (c) 2013 by Christian Heimes <christian@python.org>\n# Licensed to PSF under a Contributor Agreement.\n# See https://www.python.org/psf/license for licensing details.\n"""Defused xml.dom.expatbuilder\n"""\nfrom __future__ import print_function, absolute_import\n\nfrom xml.dom.expatbuilder import ExpatBuilder as _ExpatBuilder\nfrom xml.dom.expatbuilder import Namespaces as _Namespaces\n\nfrom .common import DTDForbidden, EntitiesForbidden, ExternalReferenceForbidden\n\n__origin__ = "xml.dom.expatbuilder"\n\n\nclass DefusedExpatBuilder(_ExpatBuilder):\n """Defused document builder"""\n\n def __init__(\n self, options=None, forbid_dtd=False, forbid_entities=True, forbid_external=True\n ):\n _ExpatBuilder.__init__(self, options)\n self.forbid_dtd = forbid_dtd\n self.forbid_entities = forbid_entities\n self.forbid_external = forbid_external\n\n def defused_start_doctype_decl(self, name, sysid, pubid, has_internal_subset):\n raise DTDForbidden(name, sysid, pubid)\n\n def defused_entity_decl(\n self, name, is_parameter_entity, value, base, sysid, pubid, notation_name\n ):\n raise EntitiesForbidden(name, value, base, sysid, pubid, notation_name)\n\n def defused_unparsed_entity_decl(self, name, base, sysid, pubid, notation_name):\n # expat 1.2\n raise EntitiesForbidden(name, None, base, sysid, pubid, notation_name) # pragma: no cover\n\n def defused_external_entity_ref_handler(self, context, base, sysid, pubid):\n raise ExternalReferenceForbidden(context, base, sysid, pubid)\n\n def install(self, parser):\n _ExpatBuilder.install(self, parser)\n\n if self.forbid_dtd:\n parser.StartDoctypeDeclHandler = self.defused_start_doctype_decl\n if self.forbid_entities:\n # if self._options.entities:\n parser.EntityDeclHandler = self.defused_entity_decl\n parser.UnparsedEntityDeclHandler = self.defused_unparsed_entity_decl\n if self.forbid_external:\n parser.ExternalEntityRefHandler = self.defused_external_entity_ref_handler\n\n\nclass DefusedExpatBuilderNS(_Namespaces, DefusedExpatBuilder):\n """Defused document builder that supports namespaces."""\n\n def install(self, parser):\n DefusedExpatBuilder.install(self, parser)\n if self._options.namespace_declarations:\n parser.StartNamespaceDeclHandler = self.start_namespace_decl_handler\n\n def reset(self):\n DefusedExpatBuilder.reset(self)\n self._initNamespaces()\n\n\ndef parse(file, namespaces=True, forbid_dtd=False, forbid_entities=True, forbid_external=True):\n """Parse a document, returning the resulting Document node.\n\n 'file' may be either a file name or an open file object.\n """\n if namespaces:\n build_builder = DefusedExpatBuilderNS\n else:\n build_builder = DefusedExpatBuilder\n builder = build_builder(\n forbid_dtd=forbid_dtd, forbid_entities=forbid_entities, forbid_external=forbid_external\n )\n\n if isinstance(file, str):\n fp = open(file, "rb")\n try:\n result = builder.parseFile(fp)\n finally:\n fp.close()\n else:\n result = builder.parseFile(file)\n return result\n\n\ndef parseString(\n string, namespaces=True, forbid_dtd=False, forbid_entities=True, forbid_external=True\n):\n """Parse a document from a string, returning the resulting\n Document node.\n """\n if namespaces:\n build_builder = DefusedExpatBuilderNS\n else:\n build_builder = DefusedExpatBuilder\n builder = build_builder(\n forbid_dtd=forbid_dtd, forbid_entities=forbid_entities, forbid_external=forbid_external\n )\n return builder.parseString(string)\n
.venv\Lib\site-packages\defusedxml\expatbuilder.py
expatbuilder.py
Python
3,732
0.95
0.205607
0.082353
python-kit
307
2025-04-07T10:52:29.651084
GPL-3.0
false
06a80720f59c74d53e98810f1436c51c
# defusedxml\n#\n# Copyright (c) 2013 by Christian Heimes <christian@python.org>\n# Licensed to PSF under a Contributor Agreement.\n# See https://www.python.org/psf/license for licensing details.\n"""Defused xml.sax.expatreader\n"""\nfrom __future__ import print_function, absolute_import\n\nfrom xml.sax.expatreader import ExpatParser as _ExpatParser\n\nfrom .common import DTDForbidden, EntitiesForbidden, ExternalReferenceForbidden\n\n__origin__ = "xml.sax.expatreader"\n\n\nclass DefusedExpatParser(_ExpatParser):\n """Defused SAX driver for the pyexpat C module."""\n\n def __init__(\n self,\n namespaceHandling=0,\n bufsize=2 ** 16 - 20,\n forbid_dtd=False,\n forbid_entities=True,\n forbid_external=True,\n ):\n _ExpatParser.__init__(self, namespaceHandling, bufsize)\n self.forbid_dtd = forbid_dtd\n self.forbid_entities = forbid_entities\n self.forbid_external = forbid_external\n\n def defused_start_doctype_decl(self, name, sysid, pubid, has_internal_subset):\n raise DTDForbidden(name, sysid, pubid)\n\n def defused_entity_decl(\n self, name, is_parameter_entity, value, base, sysid, pubid, notation_name\n ):\n raise EntitiesForbidden(name, value, base, sysid, pubid, notation_name)\n\n def defused_unparsed_entity_decl(self, name, base, sysid, pubid, notation_name):\n # expat 1.2\n raise EntitiesForbidden(name, None, base, sysid, pubid, notation_name) # pragma: no cover\n\n def defused_external_entity_ref_handler(self, context, base, sysid, pubid):\n raise ExternalReferenceForbidden(context, base, sysid, pubid)\n\n def reset(self):\n _ExpatParser.reset(self)\n parser = self._parser\n if self.forbid_dtd:\n parser.StartDoctypeDeclHandler = self.defused_start_doctype_decl\n if self.forbid_entities:\n parser.EntityDeclHandler = self.defused_entity_decl\n parser.UnparsedEntityDeclHandler = self.defused_unparsed_entity_decl\n if self.forbid_external:\n parser.ExternalEntityRefHandler = self.defused_external_entity_ref_handler\n\n\ndef create_parser(*args, **kwargs):\n return DefusedExpatParser(*args, **kwargs)\n
.venv\Lib\site-packages\defusedxml\expatreader.py
expatreader.py
Python
2,196
0.95
0.213115
0.125
vue-tools
669
2025-04-09T15:03:51.018227
MIT
false
8faeac119c07f691d529859e2b1a547e
# defusedxml\n#\n# Copyright (c) 2013 by Christian Heimes <christian@python.org>\n# Licensed to PSF under a Contributor Agreement.\n# See https://www.python.org/psf/license for licensing details.\n"""DEPRECATED Example code for lxml.etree protection\n\nThe code has NO protection against decompression bombs.\n"""\nfrom __future__ import print_function, absolute_import\n\nimport threading\nimport warnings\n\nfrom lxml import etree as _etree\n\nfrom .common import DTDForbidden, EntitiesForbidden, NotSupportedError\n\nLXML3 = _etree.LXML_VERSION[0] >= 3\n\n__origin__ = "lxml.etree"\n\ntostring = _etree.tostring\n\n\nwarnings.warn(\n "defusedxml.lxml is no longer supported and will be removed in a future release.",\n category=DeprecationWarning,\n stacklevel=2,\n)\n\n\nclass RestrictedElement(_etree.ElementBase):\n """A restricted Element class that filters out instances of some classes"""\n\n __slots__ = ()\n # blacklist = (etree._Entity, etree._ProcessingInstruction, etree._Comment)\n blacklist = _etree._Entity\n\n def _filter(self, iterator):\n blacklist = self.blacklist\n for child in iterator:\n if isinstance(child, blacklist):\n continue\n yield child\n\n def __iter__(self):\n iterator = super(RestrictedElement, self).__iter__()\n return self._filter(iterator)\n\n def iterchildren(self, tag=None, reversed=False):\n iterator = super(RestrictedElement, self).iterchildren(tag=tag, reversed=reversed)\n return self._filter(iterator)\n\n def iter(self, tag=None, *tags):\n iterator = super(RestrictedElement, self).iter(tag=tag, *tags)\n return self._filter(iterator)\n\n def iterdescendants(self, tag=None, *tags):\n iterator = super(RestrictedElement, self).iterdescendants(tag=tag, *tags)\n return self._filter(iterator)\n\n def itersiblings(self, tag=None, preceding=False):\n iterator = super(RestrictedElement, self).itersiblings(tag=tag, preceding=preceding)\n return self._filter(iterator)\n\n def getchildren(self):\n iterator = super(RestrictedElement, self).__iter__()\n return list(self._filter(iterator))\n\n def getiterator(self, tag=None):\n iterator = super(RestrictedElement, self).getiterator(tag)\n return self._filter(iterator)\n\n\nclass GlobalParserTLS(threading.local):\n """Thread local context for custom parser instances"""\n\n parser_config = {\n "resolve_entities": False,\n # 'remove_comments': True,\n # 'remove_pis': True,\n }\n\n element_class = RestrictedElement\n\n def createDefaultParser(self):\n parser = _etree.XMLParser(**self.parser_config)\n element_class = self.element_class\n if self.element_class is not None:\n lookup = _etree.ElementDefaultClassLookup(element=element_class)\n parser.set_element_class_lookup(lookup)\n return parser\n\n def setDefaultParser(self, parser):\n self._default_parser = parser\n\n def getDefaultParser(self):\n parser = getattr(self, "_default_parser", None)\n if parser is None:\n parser = self.createDefaultParser()\n self.setDefaultParser(parser)\n return parser\n\n\n_parser_tls = GlobalParserTLS()\ngetDefaultParser = _parser_tls.getDefaultParser\n\n\ndef check_docinfo(elementtree, forbid_dtd=False, forbid_entities=True):\n """Check docinfo of an element tree for DTD and entity declarations\n\n The check for entity declarations needs lxml 3 or newer. lxml 2.x does\n not support dtd.iterentities().\n """\n docinfo = elementtree.docinfo\n if docinfo.doctype:\n if forbid_dtd:\n raise DTDForbidden(docinfo.doctype, docinfo.system_url, docinfo.public_id)\n if forbid_entities and not LXML3:\n # lxml < 3 has no iterentities()\n raise NotSupportedError("Unable to check for entity declarations " "in lxml 2.x")\n\n if forbid_entities:\n for dtd in docinfo.internalDTD, docinfo.externalDTD:\n if dtd is None:\n continue\n for entity in dtd.iterentities():\n raise EntitiesForbidden(entity.name, entity.content, None, None, None, None)\n\n\ndef parse(source, parser=None, base_url=None, forbid_dtd=False, forbid_entities=True):\n if parser is None:\n parser = getDefaultParser()\n elementtree = _etree.parse(source, parser, base_url=base_url)\n check_docinfo(elementtree, forbid_dtd, forbid_entities)\n return elementtree\n\n\ndef fromstring(text, parser=None, base_url=None, forbid_dtd=False, forbid_entities=True):\n if parser is None:\n parser = getDefaultParser()\n rootelement = _etree.fromstring(text, parser, base_url=base_url)\n elementtree = rootelement.getroottree()\n check_docinfo(elementtree, forbid_dtd, forbid_entities)\n return rootelement\n\n\nXML = fromstring\n\n\ndef iterparse(*args, **kwargs):\n raise NotSupportedError("defused lxml.etree.iterparse not available")\n
.venv\Lib\site-packages\defusedxml\lxml.py
lxml.py
Python
4,940
0.95
0.24183
0.080357
python-kit
329
2024-04-01T16:38:14.857328
BSD-3-Clause
false
56cf4801a5ea86f60b3f33c9c6d1b0eb
# defusedxml\n#\n# Copyright (c) 2013 by Christian Heimes <christian@python.org>\n# Licensed to PSF under a Contributor Agreement.\n# See https://www.python.org/psf/license for licensing details.\n"""Defused xml.dom.minidom\n"""\nfrom __future__ import print_function, absolute_import\n\nfrom xml.dom.minidom import _do_pulldom_parse\nfrom . import expatbuilder as _expatbuilder\nfrom . import pulldom as _pulldom\n\n__origin__ = "xml.dom.minidom"\n\n\ndef parse(\n file, parser=None, bufsize=None, forbid_dtd=False, forbid_entities=True, forbid_external=True\n):\n """Parse a file into a DOM by filename or file object."""\n if parser is None and not bufsize:\n return _expatbuilder.parse(\n file,\n forbid_dtd=forbid_dtd,\n forbid_entities=forbid_entities,\n forbid_external=forbid_external,\n )\n else:\n return _do_pulldom_parse(\n _pulldom.parse,\n (file,),\n {\n "parser": parser,\n "bufsize": bufsize,\n "forbid_dtd": forbid_dtd,\n "forbid_entities": forbid_entities,\n "forbid_external": forbid_external,\n },\n )\n\n\ndef parseString(\n string, parser=None, forbid_dtd=False, forbid_entities=True, forbid_external=True\n):\n """Parse a file into a DOM from a string."""\n if parser is None:\n return _expatbuilder.parseString(\n string,\n forbid_dtd=forbid_dtd,\n forbid_entities=forbid_entities,\n forbid_external=forbid_external,\n )\n else:\n return _do_pulldom_parse(\n _pulldom.parseString,\n (string,),\n {\n "parser": parser,\n "forbid_dtd": forbid_dtd,\n "forbid_entities": forbid_entities,\n "forbid_external": forbid_external,\n },\n )\n
.venv\Lib\site-packages\defusedxml\minidom.py
minidom.py
Python
1,884
0.95
0.079365
0.087719
node-utils
103
2024-12-17T23:00:51.682837
GPL-3.0
false
4828a5ad65c6e11c2d046a11042563e1
# defusedxml\n#\n# Copyright (c) 2013 by Christian Heimes <christian@python.org>\n# Licensed to PSF under a Contributor Agreement.\n# See https://www.python.org/psf/license for licensing details.\n"""Defused xml.dom.pulldom\n"""\nfrom __future__ import print_function, absolute_import\n\nfrom xml.dom.pulldom import parse as _parse\nfrom xml.dom.pulldom import parseString as _parseString\nfrom .sax import make_parser\n\n__origin__ = "xml.dom.pulldom"\n\n\ndef parse(\n stream_or_string,\n parser=None,\n bufsize=None,\n forbid_dtd=False,\n forbid_entities=True,\n forbid_external=True,\n):\n if parser is None:\n parser = make_parser()\n parser.forbid_dtd = forbid_dtd\n parser.forbid_entities = forbid_entities\n parser.forbid_external = forbid_external\n return _parse(stream_or_string, parser, bufsize)\n\n\ndef parseString(\n string, parser=None, forbid_dtd=False, forbid_entities=True, forbid_external=True\n):\n if parser is None:\n parser = make_parser()\n parser.forbid_dtd = forbid_dtd\n parser.forbid_entities = forbid_entities\n parser.forbid_external = forbid_external\n return _parseString(string, parser)\n
.venv\Lib\site-packages\defusedxml\pulldom.py
pulldom.py
Python
1,170
0.95
0.121951
0.142857
node-utils
298
2024-07-09T06:18:37.925624
MIT
false
9f9cdc58304a21d4af1649807740dc51
# defusedxml\n#\n# Copyright (c) 2013 by Christian Heimes <christian@python.org>\n# Licensed to PSF under a Contributor Agreement.\n# See https://www.python.org/psf/license for licensing details.\n"""Defused xml.sax\n"""\nfrom __future__ import print_function, absolute_import\n\nfrom xml.sax import InputSource as _InputSource\nfrom xml.sax import ErrorHandler as _ErrorHandler\n\nfrom . import expatreader\n\n__origin__ = "xml.sax"\n\n\ndef parse(\n source,\n handler,\n errorHandler=_ErrorHandler(),\n forbid_dtd=False,\n forbid_entities=True,\n forbid_external=True,\n):\n parser = make_parser()\n parser.setContentHandler(handler)\n parser.setErrorHandler(errorHandler)\n parser.forbid_dtd = forbid_dtd\n parser.forbid_entities = forbid_entities\n parser.forbid_external = forbid_external\n parser.parse(source)\n\n\ndef parseString(\n string,\n handler,\n errorHandler=_ErrorHandler(),\n forbid_dtd=False,\n forbid_entities=True,\n forbid_external=True,\n):\n from io import BytesIO\n\n if errorHandler is None:\n errorHandler = _ErrorHandler()\n parser = make_parser()\n parser.setContentHandler(handler)\n parser.setErrorHandler(errorHandler)\n parser.forbid_dtd = forbid_dtd\n parser.forbid_entities = forbid_entities\n parser.forbid_external = forbid_external\n\n inpsrc = _InputSource()\n inpsrc.setByteStream(BytesIO(string))\n parser.parse(inpsrc)\n\n\ndef make_parser(parser_list=[]):\n return expatreader.create_parser()\n
.venv\Lib\site-packages\defusedxml\sax.py
sax.py
Python
1,477
0.95
0.083333
0.102041
vue-tools
668
2024-02-05T08:49:21.688046
MIT
false
0ec2736d8ed8db3a42ed896b9ca4c90c
# defusedxml\n#\n# Copyright (c) 2013 by Christian Heimes <christian@python.org>\n# Licensed to PSF under a Contributor Agreement.\n# See https://www.python.org/psf/license for licensing details.\n"""Defused xmlrpclib\n\nAlso defuses gzip bomb\n"""\nfrom __future__ import print_function, absolute_import\n\nimport io\n\nfrom .common import DTDForbidden, EntitiesForbidden, ExternalReferenceForbidden, PY3\n\nif PY3:\n __origin__ = "xmlrpc.client"\n from xmlrpc.client import ExpatParser\n from xmlrpc import client as xmlrpc_client\n from xmlrpc import server as xmlrpc_server\n from xmlrpc.client import gzip_decode as _orig_gzip_decode\n from xmlrpc.client import GzipDecodedResponse as _OrigGzipDecodedResponse\nelse:\n __origin__ = "xmlrpclib"\n from xmlrpclib import ExpatParser\n import xmlrpclib as xmlrpc_client\n\n xmlrpc_server = None\n from xmlrpclib import gzip_decode as _orig_gzip_decode\n from xmlrpclib import GzipDecodedResponse as _OrigGzipDecodedResponse\n\ntry:\n import gzip\nexcept ImportError: # pragma: no cover\n gzip = None\n\n\n# Limit maximum request size to prevent resource exhaustion DoS\n# Also used to limit maximum amount of gzip decoded data in order to prevent\n# decompression bombs\n# A value of -1 or smaller disables the limit\nMAX_DATA = 30 * 1024 * 1024 # 30 MB\n\n\ndef defused_gzip_decode(data, limit=None):\n """gzip encoded data -> unencoded data\n\n Decode data using the gzip content encoding as described in RFC 1952\n """\n if not gzip: # pragma: no cover\n raise NotImplementedError\n if limit is None:\n limit = MAX_DATA\n f = io.BytesIO(data)\n gzf = gzip.GzipFile(mode="rb", fileobj=f)\n try:\n if limit < 0: # no limit\n decoded = gzf.read()\n else:\n decoded = gzf.read(limit + 1)\n except IOError: # pragma: no cover\n raise ValueError("invalid data")\n f.close()\n gzf.close()\n if limit >= 0 and len(decoded) > limit:\n raise ValueError("max gzipped payload length exceeded")\n return decoded\n\n\nclass DefusedGzipDecodedResponse(gzip.GzipFile if gzip else object):\n """a file-like object to decode a response encoded with the gzip\n method, as described in RFC 1952.\n """\n\n def __init__(self, response, limit=None):\n # response doesn't support tell() and read(), required by\n # GzipFile\n if not gzip: # pragma: no cover\n raise NotImplementedError\n self.limit = limit = limit if limit is not None else MAX_DATA\n if limit < 0: # no limit\n data = response.read()\n self.readlength = None\n else:\n data = response.read(limit + 1)\n self.readlength = 0\n if limit >= 0 and len(data) > limit:\n raise ValueError("max payload length exceeded")\n self.stringio = io.BytesIO(data)\n gzip.GzipFile.__init__(self, mode="rb", fileobj=self.stringio)\n\n def read(self, n):\n if self.limit >= 0:\n left = self.limit - self.readlength\n n = min(n, left + 1)\n data = gzip.GzipFile.read(self, n)\n self.readlength += len(data)\n if self.readlength > self.limit:\n raise ValueError("max payload length exceeded")\n return data\n else:\n return gzip.GzipFile.read(self, n)\n\n def close(self):\n gzip.GzipFile.close(self)\n self.stringio.close()\n\n\nclass DefusedExpatParser(ExpatParser):\n def __init__(self, target, forbid_dtd=False, forbid_entities=True, forbid_external=True):\n ExpatParser.__init__(self, target)\n self.forbid_dtd = forbid_dtd\n self.forbid_entities = forbid_entities\n self.forbid_external = forbid_external\n parser = self._parser\n if self.forbid_dtd:\n parser.StartDoctypeDeclHandler = self.defused_start_doctype_decl\n if self.forbid_entities:\n parser.EntityDeclHandler = self.defused_entity_decl\n parser.UnparsedEntityDeclHandler = self.defused_unparsed_entity_decl\n if self.forbid_external:\n parser.ExternalEntityRefHandler = self.defused_external_entity_ref_handler\n\n def defused_start_doctype_decl(self, name, sysid, pubid, has_internal_subset):\n raise DTDForbidden(name, sysid, pubid)\n\n def defused_entity_decl(\n self, name, is_parameter_entity, value, base, sysid, pubid, notation_name\n ):\n raise EntitiesForbidden(name, value, base, sysid, pubid, notation_name)\n\n def defused_unparsed_entity_decl(self, name, base, sysid, pubid, notation_name):\n # expat 1.2\n raise EntitiesForbidden(name, None, base, sysid, pubid, notation_name) # pragma: no cover\n\n def defused_external_entity_ref_handler(self, context, base, sysid, pubid):\n raise ExternalReferenceForbidden(context, base, sysid, pubid)\n\n\ndef monkey_patch():\n xmlrpc_client.FastParser = DefusedExpatParser\n xmlrpc_client.GzipDecodedResponse = DefusedGzipDecodedResponse\n xmlrpc_client.gzip_decode = defused_gzip_decode\n if xmlrpc_server:\n xmlrpc_server.gzip_decode = defused_gzip_decode\n\n\ndef unmonkey_patch():\n xmlrpc_client.FastParser = None\n xmlrpc_client.GzipDecodedResponse = _OrigGzipDecodedResponse\n xmlrpc_client.gzip_decode = _orig_gzip_decode\n if xmlrpc_server:\n xmlrpc_server.gzip_decode = _orig_gzip_decode\n
.venv\Lib\site-packages\defusedxml\xmlrpc.py
xmlrpc.py
Python
5,364
0.95
0.215686
0.094488
react-lib
952
2025-03-14T07:04:51.233221
Apache-2.0
false
dde618485cf4a84d339bbe468d3c1b0a
# defusedxml\n#\n# Copyright (c) 2013 by Christian Heimes <christian@python.org>\n# Licensed to PSF under a Contributor Agreement.\n# See https://www.python.org/psf/license for licensing details.\n"""Defuse XML bomb denial of service vulnerabilities\n"""\nfrom __future__ import print_function, absolute_import\n\nimport warnings\n\nfrom .common import (\n DefusedXmlException,\n DTDForbidden,\n EntitiesForbidden,\n ExternalReferenceForbidden,\n NotSupportedError,\n _apply_defusing,\n)\n\n\ndef defuse_stdlib():\n """Monkey patch and defuse all stdlib packages\n\n :warning: The monkey patch is an EXPERIMETNAL feature.\n """\n defused = {}\n\n with warnings.catch_warnings():\n from . import cElementTree\n from . import ElementTree\n from . import minidom\n from . import pulldom\n from . import sax\n from . import expatbuilder\n from . import expatreader\n from . import xmlrpc\n\n xmlrpc.monkey_patch()\n defused[xmlrpc] = None\n\n defused_mods = [\n cElementTree,\n ElementTree,\n minidom,\n pulldom,\n sax,\n expatbuilder,\n expatreader,\n ]\n\n for defused_mod in defused_mods:\n stdlib_mod = _apply_defusing(defused_mod)\n defused[defused_mod] = stdlib_mod\n\n return defused\n\n\n__version__ = "0.7.1"\n\n__all__ = [\n "DefusedXmlException",\n "DTDForbidden",\n "EntitiesForbidden",\n "ExternalReferenceForbidden",\n "NotSupportedError",\n]\n
.venv\Lib\site-packages\defusedxml\__init__.py
__init__.py
Python
1,444
0.95
0.044776
0.092593
node-utils
126
2023-08-21T02:37:37.119759
BSD-3-Clause
false
b0a3182b9e6bb072cd990e013aa2a64b
\n\n
.venv\Lib\site-packages\defusedxml\__pycache__\cElementTree.cpython-313.pyc
cElementTree.cpython-313.pyc
Other
1,212
0.95
0
0
node-utils
147
2024-04-03T18:14:54.577534
BSD-3-Clause
false
205a4dd21da5ffea28fed1c5263f7ff8
\n\n
.venv\Lib\site-packages\defusedxml\__pycache__\common.cpython-313.pyc
common.cpython-313.pyc
Other
6,116
0.95
0.016949
0.034483
python-kit
634
2025-01-11T08:25:52.398042
MIT
false
13670dda7c8d6a2e29ff13a1421074dd
\n\n
.venv\Lib\site-packages\defusedxml\__pycache__\ElementTree.cpython-313.pyc
ElementTree.cpython-313.pyc
Other
5,294
0.95
0
0
python-kit
63
2024-03-11T10:07:52.609231
BSD-3-Clause
false
e8756c2ac7091c6540b28a756e53a215
\n\n
.venv\Lib\site-packages\defusedxml\__pycache__\expatbuilder.cpython-313.pyc
expatbuilder.cpython-313.pyc
Other
4,969
0.95
0
0.022222
awesome-app
669
2024-01-29T13:57:34.368149
Apache-2.0
false
58e2905e5c42f033313f91b8a6d424f7
\n\n
.venv\Lib\site-packages\defusedxml\__pycache__\expatreader.cpython-313.pyc
expatreader.cpython-313.pyc
Other
3,111
0.95
0.047619
0
awesome-app
0
2024-04-28T14:47:04.634693
GPL-3.0
false
02573d87a6cff9a0cc78c8d6bd0f6d90
\n\n
.venv\Lib\site-packages\defusedxml\__pycache__\lxml.cpython-313.pyc
lxml.cpython-313.pyc
Other
7,219
0.95
0.111111
0
node-utils
559
2024-12-15T11:50:52.545121
MIT
false
6cf00aad041eeabed0ae1d2550ac5355
\n\n
.venv\Lib\site-packages\defusedxml\__pycache__\minidom.cpython-313.pyc
minidom.cpython-313.pyc
Other
1,457
0.95
0
0
vue-tools
296
2025-03-19T17:18:27.833796
GPL-3.0
false
89824538386ff65bcc0ae32951ed1794
\n\n
.venv\Lib\site-packages\defusedxml\__pycache__\pulldom.cpython-313.pyc
pulldom.cpython-313.pyc
Other
1,144
0.85
0
0
node-utils
847
2024-02-05T23:01:43.767874
GPL-3.0
false
d93279394fe9338831cb2506147dddb3
\n\n
.venv\Lib\site-packages\defusedxml\__pycache__\sax.cpython-313.pyc
sax.cpython-313.pyc
Other
1,833
0.95
0
0
awesome-app
316
2025-03-12T16:31:39.675581
Apache-2.0
false
8574f6bf4879f36ea52079bb55b5bf8f
\n\n
.venv\Lib\site-packages\defusedxml\__pycache__\xmlrpc.cpython-313.pyc
xmlrpc.cpython-313.pyc
Other
6,996
0.95
0
0
vue-tools
794
2025-07-09T05:56:34.168311
MIT
false
bbbfa165a68f7f634aaca09212fa4c5b
\n\n
.venv\Lib\site-packages\defusedxml\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
1,587
0.95
0
0.076923
vue-tools
476
2024-12-31T22:30:47.134361
Apache-2.0
false
c3c9524ed7ef80971b926f74d12a4f44
pip\n
.venv\Lib\site-packages\defusedxml-0.7.1.dist-info\INSTALLER
INSTALLER
Other
4
0.5
0
0
node-utils
878
2025-05-22T05:37:28.365736
Apache-2.0
false
365c9bfeb7d89244f2ce01c1de44cb85
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2\n--------------------------------------------\n\n1. This LICENSE AGREEMENT is between the Python Software Foundation\n("PSF"), and the Individual or Organization ("Licensee") accessing and\notherwise using this software ("Python") in source or binary form and\nits associated documentation.\n\n2. Subject to the terms and conditions of this License Agreement, PSF\nhereby grants Licensee a nonexclusive, royalty-free, world-wide\nlicense to reproduce, analyze, test, perform and/or display publicly,\nprepare derivative works, distribute, and otherwise use Python\nalone or in any derivative version, provided, however, that PSF's\nLicense Agreement and PSF's notice of copyright, i.e., "Copyright (c)\n2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Python Software Foundation; \nAll Rights Reserved" are retained in Python alone or in any derivative \nversion prepared by Licensee.\n\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python or any part thereof, and wants to make\nthe derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python.\n\n4. PSF is making Python available to Licensee on an "AS IS"\nbasis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n\n5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\nFOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS\nA RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,\nOR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n\n7. Nothing in this License Agreement shall be deemed to create any\nrelationship of agency, partnership, or joint venture between PSF and\nLicensee. This License Agreement does not grant permission to use PSF\ntrademarks or trade name in a trademark sense to endorse or promote\nproducts or services of Licensee, or any third party.\n\n8. By copying, installing or otherwise using Python, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\n\n
.venv\Lib\site-packages\defusedxml-0.7.1.dist-info\LICENSE
LICENSE
Other
2,409
0.7
0
0
vue-tools
421
2024-07-25T00:14:21.759120
MIT
false
056fea6a4b395a24d0d278bf5c80249e
Metadata-Version: 2.1\nName: defusedxml\nVersion: 0.7.1\nSummary: XML bomb protection for Python stdlib modules\nHome-page: https://github.com/tiran/defusedxml\nAuthor: Christian Heimes\nAuthor-email: christian@python.org\nMaintainer: Christian Heimes\nMaintainer-email: christian@python.org\nLicense: PSFL\nDownload-URL: https://pypi.python.org/pypi/defusedxml\nKeywords: xml bomb DoS\nPlatform: all\nClassifier: Development Status :: 5 - Production/Stable\nClassifier: Intended Audience :: Developers\nClassifier: License :: OSI Approved :: Python Software Foundation License\nClassifier: Natural Language :: English\nClassifier: Programming Language :: Python\nClassifier: Programming Language :: Python :: 2\nClassifier: Programming Language :: Python :: 2.7\nClassifier: Programming Language :: Python :: 3\nClassifier: Programming Language :: Python :: 3.5\nClassifier: Programming Language :: Python :: 3.6\nClassifier: Programming Language :: Python :: 3.7\nClassifier: Programming Language :: Python :: 3.8\nClassifier: Programming Language :: Python :: 3.9\nClassifier: Topic :: Text Processing :: Markup :: XML\nRequires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*\n\n===================================================\ndefusedxml -- defusing XML bombs and other exploits\n===================================================\n\n.. image:: https://img.shields.io/pypi/v/defusedxml.svg\n :target: https://pypi.org/project/defusedxml/\n :alt: Latest Version\n\n.. image:: https://img.shields.io/pypi/pyversions/defusedxml.svg\n :target: https://pypi.org/project/defusedxml/\n :alt: Supported Python versions\n\n.. image:: https://travis-ci.org/tiran/defusedxml.svg?branch=master\n :target: https://travis-ci.org/tiran/defusedxml\n :alt: Travis CI\n\n.. image:: https://codecov.io/github/tiran/defusedxml/coverage.svg?branch=master\n :target: https://codecov.io/github/tiran/defusedxml?branch=master\n :alt: codecov\n\n.. image:: https://img.shields.io/pypi/dm/defusedxml.svg\n :target: https://pypistats.org/packages/defusedxml\n :alt: PyPI downloads\n\n.. image:: https://img.shields.io/badge/code%20style-black-000000.svg\n :target: https://github.com/psf/black\n :alt: Code style: black\n\n..\n\n "It's just XML, what could probably go wrong?"\n\nChristian Heimes <christian@python.org>\n\nSynopsis\n========\n\nThe results of an attack on a vulnerable XML library can be fairly dramatic.\nWith just a few hundred **Bytes** of XML data an attacker can occupy several\n**Gigabytes** of memory within **seconds**. An attacker can also keep\nCPUs busy for a long time with a small to medium size request. Under some\ncircumstances it is even possible to access local files on your\nserver, to circumvent a firewall, or to abuse services to rebound attacks to\nthird parties.\n\nThe attacks use and abuse less common features of XML and its parsers. The\nmajority of developers are unacquainted with features such as processing\ninstructions and entity expansions that XML inherited from SGML. At best\nthey know about ``<!DOCTYPE>`` from experience with HTML but they are not\naware that a document type definition (DTD) can generate an HTTP request\nor load a file from the file system.\n\nNone of the issues is new. They have been known for a long time. Billion\nlaughs was first reported in 2003. Nevertheless some XML libraries and\napplications are still vulnerable and even heavy users of XML are\nsurprised by these features. It's hard to say whom to blame for the\nsituation. It's too short sighted to shift all blame on XML parsers and\nXML libraries for using insecure default settings. After all they\nproperly implement XML specifications. Application developers must not rely\nthat a library is always configured for security and potential harmful data\nby default.\n\n\n.. contents:: Table of Contents\n :depth: 2\n\n\nAttack vectors\n==============\n\nbillion laughs / exponential entity expansion\n---------------------------------------------\n\nThe `Billion Laughs`_ attack -- also known as exponential entity expansion --\nuses multiple levels of nested entities. The original example uses 9 levels\nof 10 expansions in each level to expand the string ``lol`` to a string of\n3 * 10 :sup:`9` bytes, hence the name "billion laughs". The resulting string\noccupies 3 GB (2.79 GiB) of memory; intermediate strings require additional\nmemory. Because most parsers don't cache the intermediate step for every\nexpansion it is repeated over and over again. It increases the CPU load even\nmore.\n\nAn XML document of just a few hundred bytes can disrupt all services on a\nmachine within seconds.\n\nExample XML::\n\n <!DOCTYPE xmlbomb [\n <!ENTITY a "1234567890" >\n <!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;">\n <!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;">\n <!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;">\n ]>\n <bomb>&d;</bomb>\n\n\nquadratic blowup entity expansion\n---------------------------------\n\nA quadratic blowup attack is similar to a `Billion Laughs`_ attack; it abuses\nentity expansion, too. Instead of nested entities it repeats one large entity\nwith a couple of thousand chars over and over again. The attack isn't as\nefficient as the exponential case but it avoids triggering countermeasures of\nparsers against heavily nested entities. Some parsers limit the depth and\nbreadth of a single entity but not the total amount of expanded text\nthroughout an entire XML document.\n\nA medium-sized XML document with a couple of hundred kilobytes can require a\ncouple of hundred MB to several GB of memory. When the attack is combined\nwith some level of nested expansion an attacker is able to achieve a higher\nratio of success.\n\n::\n\n <!DOCTYPE bomb [\n <!ENTITY a "xxxxxxx... a couple of ten thousand chars">\n ]>\n <bomb>&a;&a;&a;... repeat</bomb>\n\n\nexternal entity expansion (remote)\n----------------------------------\n\nEntity declarations can contain more than just text for replacement. They can\nalso point to external resources by public identifiers or system identifiers.\nSystem identifiers are standard URIs. When the URI is a URL (e.g. a\n``http://`` locator) some parsers download the resource from the remote\nlocation and embed them into the XML document verbatim.\n\nSimple example of a parsed external entity::\n\n <!DOCTYPE external [\n <!ENTITY ee SYSTEM "http://www.python.org/some.xml">\n ]>\n <root>&ee;</root>\n\nThe case of parsed external entities works only for valid XML content. The\nXML standard also supports unparsed external entities with a\n``NData declaration``.\n\nExternal entity expansion opens the door to plenty of exploits. An attacker\ncan abuse a vulnerable XML library and application to rebound and forward\nnetwork requests with the IP address of the server. It highly depends\non the parser and the application what kind of exploit is possible. For\nexample:\n\n* An attacker can circumvent firewalls and gain access to restricted\n resources as all the requests are made from an internal and trustworthy\n IP address, not from the outside.\n* An attacker can abuse a service to attack, spy on or DoS your servers but\n also third party services. The attack is disguised with the IP address of\n the server and the attacker is able to utilize the high bandwidth of a big\n machine.\n* An attacker can exhaust additional resources on the machine, e.g. with\n requests to a service that doesn't respond or responds with very large\n files.\n* An attacker may gain knowledge, when, how often and from which IP address\n an XML document is accessed.\n* An attacker could send mail from inside your network if the URL handler\n supports ``smtp://`` URIs.\n\n\nexternal entity expansion (local file)\n--------------------------------------\n\nExternal entities with references to local files are a sub-case of external\nentity expansion. It's listed as an extra attack because it deserves extra\nattention. Some XML libraries such as lxml disable network access by default\nbut still allow entity expansion with local file access by default. Local\nfiles are either referenced with a ``file://`` URL or by a file path (either\nrelative or absolute).\n\nAn attacker may be able to access and download all files that can be read by\nthe application process. This may include critical configuration files, too.\n\n::\n\n <!DOCTYPE external [\n <!ENTITY ee SYSTEM "file:///PATH/TO/simple.xml">\n ]>\n <root>&ee;</root>\n\n\nDTD retrieval\n-------------\n\nThis case is similar to external entity expansion, too. Some XML libraries\nlike Python's xml.dom.pulldom retrieve document type definitions from remote\nor local locations. Several attack scenarios from the external entity case\napply to this issue as well.\n\n::\n\n <?xml version="1.0" encoding="utf-8"?>\n <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\n "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n <html>\n <head/>\n <body>text</body>\n </html>\n\n\nPython XML Libraries\n====================\n\n.. csv-table:: vulnerabilities and features\n :header: "kind", "sax", "etree", "minidom", "pulldom", "xmlrpc", "lxml", "genshi"\n :widths: 24, 7, 8, 8, 7, 8, 8, 8\n :stub-columns: 0\n\n "billion laughs", "**True**", "**True**", "**True**", "**True**", "**True**", "False (1)", "False (5)"\n "quadratic blowup", "**True**", "**True**", "**True**", "**True**", "**True**", "**True**", "False (5)"\n "external entity expansion (remote)", "**True**", "False (3)", "False (4)", "**True**", "false", "False (1)", "False (5)"\n "external entity expansion (local file)", "**True**", "False (3)", "False (4)", "**True**", "false", "**True**", "False (5)"\n "DTD retrieval", "**True**", "False", "False", "**True**", "false", "False (1)", "False"\n "gzip bomb", "False", "False", "False", "False", "**True**", "**partly** (2)", "False"\n "xpath support (7)", "False", "False", "False", "False", "False", "**True**", "False"\n "xsl(t) support (7)", "False", "False", "False", "False", "False", "**True**", "False"\n "xinclude support (7)", "False", "**True** (6)", "False", "False", "False", "**True** (6)", "**True**"\n "C library", "expat", "expat", "expat", "expat", "expat", "libxml2", "expat"\n\n1. Lxml is protected against billion laughs attacks and doesn't do network\n lookups by default.\n2. libxml2 and lxml are not directly vulnerable to gzip decompression bombs\n but they don't protect you against them either.\n3. xml.etree doesn't expand entities and raises a ParserError when an entity\n occurs.\n4. minidom doesn't expand entities and simply returns the unexpanded entity\n verbatim.\n5. genshi.input of genshi 0.6 doesn't support entity expansion and raises a\n ParserError when an entity occurs.\n6. Library has (limited) XInclude support but requires an additional step to\n process inclusion.\n7. These are features but they may introduce exploitable holes, see\n `Other things to consider`_\n\n\nSettings in standard library\n----------------------------\n\n\nxml.sax.handler Features\n........................\n\nfeature_external_ges (http://xml.org/sax/features/external-general-entities)\n disables external entity expansion\n\nfeature_external_pes (http://xml.org/sax/features/external-parameter-entities)\n the option is ignored and doesn't modify any functionality\n\nDOM xml.dom.xmlbuilder.Options\n..............................\n\nexternal_parameter_entities\n ignored\n\nexternal_general_entities\n ignored\n\nexternal_dtd_subset\n ignored\n\nentities\n unsure\n\n\ndefusedxml\n==========\n\nThe `defusedxml package`_ (`defusedxml on PyPI`_)\ncontains several Python-only workarounds and fixes\nfor denial of service and other vulnerabilities in Python's XML libraries.\nIn order to benefit from the protection you just have to import and use the\nlisted functions / classes from the right defusedxml module instead of the\noriginal module. Merely `defusedxml.xmlrpc`_ is implemented as monkey patch.\n\nInstead of::\n\n >>> from xml.etree.ElementTree import parse\n >>> et = parse(xmlfile)\n\nalter code to::\n\n >>> from defusedxml.ElementTree import parse\n >>> et = parse(xmlfile)\n\nAdditionally the package has an **untested** function to monkey patch\nall stdlib modules with ``defusedxml.defuse_stdlib()``.\n\nAll functions and parser classes accept three additional keyword arguments.\nThey return either the same objects as the original functions or compatible\nsubclasses.\n\nforbid_dtd (default: False)\n disallow XML with a ``<!DOCTYPE>`` processing instruction and raise a\n *DTDForbidden* exception when a DTD processing instruction is found.\n\nforbid_entities (default: True)\n disallow XML with ``<!ENTITY>`` declarations inside the DTD and raise an\n *EntitiesForbidden* exception when an entity is declared.\n\nforbid_external (default: True)\n disallow any access to remote or local resources in external entities\n or DTD and raising an *ExternalReferenceForbidden* exception when a DTD\n or entity references an external resource.\n\n\ndefusedxml (package)\n--------------------\n\nDefusedXmlException, DTDForbidden, EntitiesForbidden,\nExternalReferenceForbidden, NotSupportedError\n\ndefuse_stdlib() (*experimental*)\n\n\ndefusedxml.cElementTree\n-----------------------\n\n**NOTE** ``defusedxml.cElementTree`` is deprecated and will be removed in a\nfuture release. Import from ``defusedxml.ElementTree`` instead.\n\nparse(), iterparse(), fromstring(), XMLParser\n\n\ndefusedxml.ElementTree\n-----------------------\n\nparse(), iterparse(), fromstring(), XMLParser\n\n\ndefusedxml.expatreader\n----------------------\n\ncreate_parser(), DefusedExpatParser\n\n\ndefusedxml.sax\n--------------\n\nparse(), parseString(), make_parser()\n\n\ndefusedxml.expatbuilder\n-----------------------\n\nparse(), parseString(), DefusedExpatBuilder, DefusedExpatBuilderNS\n\n\ndefusedxml.minidom\n------------------\n\nparse(), parseString()\n\n\ndefusedxml.pulldom\n------------------\n\nparse(), parseString()\n\n\ndefusedxml.xmlrpc\n-----------------\n\nThe fix is implemented as monkey patch for the stdlib's xmlrpc package (3.x)\nor xmlrpclib module (2.x). The function `monkey_patch()` enables the fixes,\n`unmonkey_patch()` removes the patch and puts the code in its former state.\n\nThe monkey patch protects against XML related attacks as well as\ndecompression bombs and excessively large requests or responses. The default\nsetting is 30 MB for requests, responses and gzip decompression. You can\nmodify the default by changing the module variable `MAX_DATA`. A value of\n`-1` disables the limit.\n\n\ndefusedxml.lxml\n---------------\n\n**DEPRECATED** The module is deprecated and will be removed in a future\nrelease.\n\nThe module acts as an *example* how you could protect code that uses\nlxml.etree. It implements a custom Element class that filters out\nEntity instances, a custom parser factory and a thread local storage for\nparser instances. It also has a check_docinfo() function which inspects\na tree for internal or external DTDs and entity declarations. In order to\ncheck for entities lxml > 3.0 is required.\n\nparse(), fromstring()\nRestrictedElement, GlobalParserTLS, getDefaultParser(), check_docinfo()\n\n\ndefusedexpat\n============\n\nThe `defusedexpat package`_ (`defusedexpat on PyPI`_)\ncomes with binary extensions and a\n`modified expat`_ library instead of the standard `expat parser`_. It's\nbasically a stand-alone version of the patches for Python's standard\nlibrary C extensions.\n\nModifications in expat\n----------------------\n\nnew definitions::\n\n XML_BOMB_PROTECTION\n XML_DEFAULT_MAX_ENTITY_INDIRECTIONS\n XML_DEFAULT_MAX_ENTITY_EXPANSIONS\n XML_DEFAULT_RESET_DTD\n\nnew XML_FeatureEnum members::\n\n XML_FEATURE_MAX_ENTITY_INDIRECTIONS\n XML_FEATURE_MAX_ENTITY_EXPANSIONS\n XML_FEATURE_IGNORE_DTD\n\nnew XML_Error members::\n\n XML_ERROR_ENTITY_INDIRECTIONS\n XML_ERROR_ENTITY_EXPANSION\n\nnew API functions::\n\n int XML_GetFeature(XML_Parser parser,\n enum XML_FeatureEnum feature,\n long *value);\n int XML_SetFeature(XML_Parser parser,\n enum XML_FeatureEnum feature,\n long value);\n int XML_GetFeatureDefault(enum XML_FeatureEnum feature,\n long *value);\n int XML_SetFeatureDefault(enum XML_FeatureEnum feature,\n long value);\n\nXML_FEATURE_MAX_ENTITY_INDIRECTIONS\n Limit the amount of indirections that are allowed to occur during the\n expansion of a nested entity. A counter starts when an entity reference\n is encountered. It resets after the entity is fully expanded. The limit\n protects the parser against exponential entity expansion attacks (aka\n billion laughs attack). When the limit is exceeded the parser stops and\n fails with `XML_ERROR_ENTITY_INDIRECTIONS`.\n A value of 0 disables the protection.\n\n Supported range\n 0 .. UINT_MAX\n Default\n 40\n\nXML_FEATURE_MAX_ENTITY_EXPANSIONS\n Limit the total length of all entity expansions throughout the entire\n document. The lengths of all entities are accumulated in a parser variable.\n The setting protects against quadratic blowup attacks (lots of expansions\n of a large entity declaration). When the sum of all entities exceeds\n the limit, the parser stops and fails with `XML_ERROR_ENTITY_EXPANSION`.\n A value of 0 disables the protection.\n\n Supported range\n 0 .. UINT_MAX\n Default\n 8 MiB\n\nXML_FEATURE_RESET_DTD\n Reset all DTD information after the <!DOCTYPE> block has been parsed. When\n the flag is set (default: false) all DTD information after the\n endDoctypeDeclHandler has been called. The flag can be set inside the\n endDoctypeDeclHandler. Without DTD information any entity reference in\n the document body leads to `XML_ERROR_UNDEFINED_ENTITY`.\n\n Supported range\n 0, 1\n Default\n 0\n\n\nHow to avoid XML vulnerabilities\n================================\n\nBest practices\n--------------\n\n* Don't allow DTDs\n* Don't expand entities\n* Don't resolve externals\n* Limit parse depth\n* Limit total input size\n* Limit parse time\n* Favor a SAX or iterparse-like parser for potential large data\n* Validate and properly quote arguments to XSL transformations and\n XPath queries\n* Don't use XPath expression from untrusted sources\n* Don't apply XSL transformations that come untrusted sources\n\n(based on Brad Hill's `Attacking XML Security`_)\n\n\nOther things to consider\n========================\n\nXML, XML parsers and processing libraries have more features and possible\nissue that could lead to DoS vulnerabilities or security exploits in\napplications. I have compiled an incomplete list of theoretical issues that\nneed further research and more attention. The list is deliberately pessimistic\nand a bit paranoid, too. It contains things that might go wrong under daffy\ncircumstances.\n\n\nattribute blowup / hash collision attack\n----------------------------------------\n\nXML parsers may use an algorithm with quadratic runtime O(n :sup:`2`) to\nhandle attributes and namespaces. If it uses hash tables (dictionaries) to\nstore attributes and namespaces the implementation may be vulnerable to\nhash collision attacks, thus reducing the performance to O(n :sup:`2`) again.\nIn either case an attacker is able to forge a denial of service attack with\nan XML document that contains thousands upon thousands of attributes in\na single node.\n\nI haven't researched yet if expat, pyexpat or libxml2 are vulnerable.\n\n\ndecompression bomb\n------------------\n\nThe issue of decompression bombs (aka `ZIP bomb`_) apply to all XML libraries\nthat can parse compressed XML stream like gzipped HTTP streams or LZMA-ed\nfiles. For an attacker it can reduce the amount of transmitted data by three\nmagnitudes or more. Gzip is able to compress 1 GiB zeros to roughly 1 MB,\nlzma is even better::\n\n $ dd if=/dev/zero bs=1M count=1024 | gzip > zeros.gz\n $ dd if=/dev/zero bs=1M count=1024 | lzma -z > zeros.xy\n $ ls -sh zeros.*\n 1020K zeros.gz\n 148K zeros.xy\n\nNone of Python's standard XML libraries decompress streams except for\n``xmlrpclib``. The module is vulnerable <https://bugs.python.org/issue16043>\nto decompression bombs.\n\nlxml can load and process compressed data through libxml2 transparently.\nlibxml2 can handle even very large blobs of compressed data efficiently\nwithout using too much memory. But it doesn't protect applications from\ndecompression bombs. A carefully written SAX or iterparse-like approach can\nbe safe.\n\n\nProcessing Instruction\n----------------------\n\n`PI`_'s like::\n\n <?xml-stylesheet type="text/xsl" href="style.xsl"?>\n\nmay impose more threats for XML processing. It depends if and how a\nprocessor handles processing instructions. The issue of URL retrieval with\nnetwork or local file access apply to processing instructions, too.\n\n\nOther DTD features\n------------------\n\n`DTD`_ has more features like ``<!NOTATION>``. I haven't researched how\nthese features may be a security threat.\n\n\nXPath\n-----\n\nXPath statements may introduce DoS vulnerabilities. Code should never execute\nqueries from untrusted sources. An attacker may also be able to create an XML\ndocument that makes certain XPath queries costly or resource hungry.\n\n\nXPath injection attacks\n-----------------------\n\nXPath injeciton attacks pretty much work like SQL injection attacks.\nArguments to XPath queries must be quoted and validated properly, especially\nwhen they are taken from the user. The page `Avoid the dangers of XPath injection`_\nlist some ramifications of XPath injections.\n\nPython's standard library doesn't have XPath support. Lxml supports\nparameterized XPath queries which does proper quoting. You just have to use\nits xpath() method correctly::\n\n # DON'T\n >>> tree.xpath("/tag[@id='%s']" % value)\n\n # instead do\n >>> tree.xpath("/tag[@id=$tagid]", tagid=name)\n\n\nXInclude\n--------\n\n`XML Inclusion`_ is another way to load and include external files::\n\n <root xmlns:xi="http://www.w3.org/2001/XInclude">\n <xi:include href="filename.txt" parse="text" />\n </root>\n\nThis feature should be disabled when XML files from an untrusted source are\nprocessed. Some Python XML libraries and libxml2 support XInclude but don't\nhave an option to sandbox inclusion and limit it to allowed directories.\n\n\nXMLSchema location\n------------------\n\nA validating XML parser may download schema files from the information in a\n``xsi:schemaLocation`` attribute.\n\n::\n\n <ead xmlns="urn:isbn:1-931666-22-9"\n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n xsi:schemaLocation="urn:isbn:1-931666-22-9 http://www.loc.gov/ead/ead.xsd">\n </ead>\n\n\nXSL Transformation\n------------------\n\nYou should keep in mind that XSLT is a Turing complete language. Never\nprocess XSLT code from unknown or untrusted source! XSLT processors may\nallow you to interact with external resources in ways you can't even imagine.\nSome processors even support extensions that allow read/write access to file\nsystem, access to JRE objects or scripting with Jython.\n\nExample from `Attacking XML Security`_ for Xalan-J::\n\n <xsl:stylesheet version="1.0"\n xmlns:xsl="http://www.w3.org/1999/XSL/Transform"\n xmlns:rt="http://xml.apache.org/xalan/java/java.lang.Runtime"\n xmlns:ob="http://xml.apache.org/xalan/java/java.lang.Object"\n exclude-result-prefixes= "rt ob">\n <xsl:template match="/">\n <xsl:variable name="runtimeObject" select="rt:getRuntime()"/>\n <xsl:variable name="command"\n select="rt:exec($runtimeObject, &apos;c:\Windows\system32\cmd.exe&apos;)"/>\n <xsl:variable name="commandAsString" select="ob:toString($command)"/>\n <xsl:value-of select="$commandAsString"/>\n </xsl:template>\n </xsl:stylesheet>\n\n\nRelated CVEs\n============\n\nCVE-2013-1664\n Unrestricted entity expansion induces DoS vulnerabilities in Python XML\n libraries (XML bomb)\n\nCVE-2013-1665\n External entity expansion in Python XML libraries inflicts potential\n security flaws and DoS vulnerabilities\n\n\nOther languages / frameworks\n=============================\n\nSeveral other programming languages and frameworks are vulnerable as well. A\ncouple of them are affected by the fact that libxml2 up to 2.9.0 has no\nprotection against quadratic blowup attacks. Most of them have potential\ndangerous default settings for entity expansion and external entities, too.\n\nPerl\n----\n\nPerl's XML::Simple is vulnerable to quadratic entity expansion and external\nentity expansion (both local and remote).\n\n\nRuby\n----\n\nRuby's REXML document parser is vulnerable to entity expansion attacks\n(both quadratic and exponential) but it doesn't do external entity\nexpansion by default. In order to counteract entity expansion you have to\ndisable the feature::\n\n REXML::Document.entity_expansion_limit = 0\n\nlibxml-ruby and hpricot don't expand entities in their default configuration.\n\n\nPHP\n---\n\nPHP's SimpleXML API is vulnerable to quadratic entity expansion and loads\nentities from local and remote resources. The option ``LIBXML_NONET`` disables\nnetwork access but still allows local file access. ``LIBXML_NOENT`` seems to\nhave no effect on entity expansion in PHP 5.4.6.\n\n\nC# / .NET / Mono\n----------------\n\nInformation in `XML DoS and Defenses (MSDN)`_ suggest that .NET is\nvulnerable with its default settings. The article contains code snippets\nhow to create a secure XML reader::\n\n XmlReaderSettings settings = new XmlReaderSettings();\n settings.ProhibitDtd = false;\n settings.MaxCharactersFromEntities = 1024;\n settings.XmlResolver = null;\n XmlReader reader = XmlReader.Create(stream, settings);\n\n\nJava\n----\n\nUntested. The documentation of Xerces and its `Xerces SecurityMananger`_\nsounds like Xerces is also vulnerable to billion laugh attacks with its\ndefault settings. It also does entity resolving when an\n``org.xml.sax.EntityResolver`` is configured. I'm not yet sure about the\ndefault setting here.\n\nJava specialists suggest to have a custom builder factory::\n\n DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();\n builderFactory.setXIncludeAware(False);\n builderFactory.setExpandEntityReferences(False);\n builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, True);\n # either\n builderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", True);\n # or if you need DTDs\n builderFactory.setFeature("http://xml.org/sax/features/external-general-entities", False);\n builderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", False);\n builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", False);\n builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", False);\n\n\nTODO\n====\n\n* DOM: Use xml.dom.xmlbuilder options for entity handling\n* SAX: take feature_external_ges and feature_external_pes (?) into account\n* test experimental monkey patching of stdlib modules\n* improve documentation\n\n\nLicense\n=======\n\nCopyright (c) 2013-2017 by Christian Heimes <christian@python.org>\n\nLicensed to PSF under a Contributor Agreement.\n\nSee https://www.python.org/psf/license for licensing details.\n\n\nAcknowledgements\n================\n\nBrett Cannon (Python Core developer)\n review and code cleanup\n\nAntoine Pitrou (Python Core developer)\n code review\n\nAaron Patterson, Ben Murphy and Michael Koziarski (Ruby community)\n Many thanks to Aaron, Ben and Michael from the Ruby community for their\n report and assistance.\n\nThierry Carrez (OpenStack)\n Many thanks to Thierry for his report to the Python Security Response\n Team on behalf of the OpenStack security team.\n\nCarl Meyer (Django)\n Many thanks to Carl for his report to PSRT on behalf of the Django security\n team.\n\nDaniel Veillard (libxml2)\n Many thanks to Daniel for his insight and assistance with libxml2.\n\nsemantics GmbH (https://www.semantics.de/)\n Many thanks to my employer semantics for letting me work on the issue\n during working hours as part of semantics's open source initiative.\n\n\nReferences\n==========\n\n* `XML DoS and Defenses (MSDN)`_\n* `Billion Laughs`_ on Wikipedia\n* `ZIP bomb`_ on Wikipedia\n* `Configure SAX parsers for secure processing`_\n* `Testing for XML Injection`_\n\n.. _defusedxml package: https://github.com/tiran/defusedxml\n.. _defusedxml on PyPI: https://pypi.python.org/pypi/defusedxml\n.. _defusedexpat package: https://github.com/tiran/defusedexpat\n.. _defusedexpat on PyPI: https://pypi.python.org/pypi/defusedexpat\n.. _modified expat: https://github.com/tiran/expat\n.. _expat parser: http://expat.sourceforge.net/\n.. _Attacking XML Security: https://www.isecpartners.com/media/12976/iSEC-HILL-Attacking-XML-Security-bh07.pdf\n.. _Billion Laughs: https://en.wikipedia.org/wiki/Billion_laughs\n.. _XML DoS and Defenses (MSDN): https://msdn.microsoft.com/en-us/magazine/ee335713.aspx\n.. _ZIP bomb: https://en.wikipedia.org/wiki/Zip_bomb\n.. _DTD: https://en.wikipedia.org/wiki/Document_Type_Definition\n.. _PI: https://en.wikipedia.org/wiki/Processing_Instruction\n.. _Avoid the dangers of XPath injection: http://www.ibm.com/developerworks/xml/library/x-xpathinjection/index.html\n.. _Configure SAX parsers for secure processing: http://www.ibm.com/developerworks/xml/library/x-tipcfsx/index.html\n.. _Testing for XML Injection: https://www.owasp.org/index.php/Testing_for_XML_Injection_(OWASP-DV-008)\n.. _Xerces SecurityMananger: https://xerces.apache.org/xerces2-j/javadocs/xerces2/org/apache/xerces/util/SecurityManager.html\n.. _XML Inclusion: https://www.w3.org/TR/xinclude/#include_element\n\nChangelog\n=========\n\ndefusedxml 0.7.1\n---------------------\n\n*Release date: 08-Mar-2021*\n\n- Fix regression ``defusedxml.ElementTree.ParseError`` (#63)\n The ``ParseError`` exception is now the same class object as\n ``xml.etree.ElementTree.ParseError`` again.\n\n\ndefusedxml 0.7.0\n----------------\n\n*Release date: 4-Mar-2021*\n\n- No changes\n\n\ndefusedxml 0.7.0rc2\n-------------------\n\n*Release date: 12-Jan-2021*\n\n- Re-add and deprecate ``defusedxml.cElementTree``\n- Use GitHub Actions instead of TravisCI\n- Restore ``ElementTree`` attribute of ``xml.etree`` module after patching\n\ndefusedxml 0.7.0rc1\n-------------------\n\n*Release date: 04-May-2020*\n\n- Add support for Python 3.9\n- ``defusedxml.cElementTree`` is not available with Python 3.9.\n- Python 2 is deprecate. Support for Python 2 will be removed in 0.8.0.\n\n\ndefusedxml 0.6.0\n----------------\n\n*Release date: 17-Apr-2019*\n\n- Increase test coverage.\n- Add badges to README.\n\n\ndefusedxml 0.6.0rc1\n-------------------\n\n*Release date: 14-Apr-2019*\n\n- Test on Python 3.7 stable and 3.8-dev\n- Drop support for Python 3.4\n- No longer pass *html* argument to XMLParse. It has been deprecated and\n ignored for a long time. The DefusedXMLParser still takes a html argument.\n A deprecation warning is issued when the argument is False and a TypeError\n when it's True.\n- defusedxml now fails early when pyexpat stdlib module is not available or\n broken.\n- defusedxml.ElementTree.__all__ now lists ParseError as public attribute.\n- The defusedxml.ElementTree and defusedxml.cElementTree modules had a typo\n and used XMLParse instead of XMLParser as an alias for DefusedXMLParser.\n Both the old and fixed name are now available.\n\n\ndefusedxml 0.5.0\n----------------\n\n*Release date: 07-Feb-2017*\n\n- No changes\n\n\ndefusedxml 0.5.0.rc1\n--------------------\n\n*Release date: 28-Jan-2017*\n\n- Add compatibility with Python 3.6\n- Drop support for Python 2.6, 3.1, 3.2, 3.3\n- Fix lxml tests (XMLSyntaxError: Detected an entity reference loop)\n\n\ndefusedxml 0.4.1\n----------------\n\n*Release date: 28-Mar-2013*\n\n- Add more demo exploits, e.g. python_external.py and Xalan XSLT demos.\n- Improved documentation.\n\n\ndefusedxml 0.4\n--------------\n\n*Release date: 25-Feb-2013*\n\n- As per http://seclists.org/oss-sec/2013/q1/340 please REJECT\n CVE-2013-0278, CVE-2013-0279 and CVE-2013-0280 and use CVE-2013-1664,\n CVE-2013-1665 for OpenStack/etc.\n- Add missing parser_list argument to sax.make_parser(). The argument is\n ignored, though. (thanks to Florian Apolloner)\n- Add demo exploit for external entity attack on Python's SAX parser, XML-RPC\n and WebDAV.\n\n\ndefusedxml 0.3\n--------------\n\n*Release date: 19-Feb-2013*\n\n- Improve documentation\n\n\ndefusedxml 0.2\n--------------\n\n*Release date: 15-Feb-2013*\n\n- Rename ExternalEntitiesForbidden to ExternalReferenceForbidden\n- Rename defusedxml.lxml.check_dtd() to check_docinfo()\n- Unify argument names in callbacks\n- Add arguments and formatted representation to exceptions\n- Add forbid_external argument to all functions and classes\n- More tests\n- LOTS of documentation\n- Add example code for other languages (Ruby, Perl, PHP) and parsers (Genshi)\n- Add protection against XML and gzip attacks to xmlrpclib\n\ndefusedxml 0.1\n--------------\n\n*Release date: 08-Feb-2013*\n\n- Initial and internal release for PSRT review\n\n\n
.venv\Lib\site-packages\defusedxml-0.7.1.dist-info\METADATA
METADATA
Other
32,518
0.95
0.054192
0.065714
react-lib
484
2024-04-04T22:40:46.636066
GPL-3.0
false
c27dac922de0f5919ee1e871488a27fa
defusedxml-0.7.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4\ndefusedxml-0.7.1.dist-info/LICENSE,sha256=uAzp2oxCofkQeWJ_u-K_JyEK4Qig_-Xwd9WwjgdsJMg,2409\ndefusedxml-0.7.1.dist-info/METADATA,sha256=Np0872SHDa-En7pxHLjQWn7-PI2asPdjrcNAef43i7E,32518\ndefusedxml-0.7.1.dist-info/RECORD,,\ndefusedxml-0.7.1.dist-info/WHEEL,sha256=kGT74LWyRUZrL4VgLh6_g12IeVl_9u9ZVhadrgXZUEY,110\ndefusedxml-0.7.1.dist-info/top_level.txt,sha256=QGHa90F50pVKhWSFlERI0jtSKtqDiGyfeZX7dQNZAAw,11\ndefusedxml/ElementTree.py,sha256=GLSqpCz58oXGPGyzf_HylsPS9_dcGVP5SN4dK7yvyPw,4640\ndefusedxml/__init__.py,sha256=RczeaVJG64p2Fgy1jlCzbuRdchEPnEaCBrxgk8JJ_pM,1444\ndefusedxml/__pycache__/ElementTree.cpython-313.pyc,,\ndefusedxml/__pycache__/__init__.cpython-313.pyc,,\ndefusedxml/__pycache__/cElementTree.cpython-313.pyc,,\ndefusedxml/__pycache__/common.cpython-313.pyc,,\ndefusedxml/__pycache__/expatbuilder.cpython-313.pyc,,\ndefusedxml/__pycache__/expatreader.cpython-313.pyc,,\ndefusedxml/__pycache__/lxml.cpython-313.pyc,,\ndefusedxml/__pycache__/minidom.cpython-313.pyc,,\ndefusedxml/__pycache__/pulldom.cpython-313.pyc,,\ndefusedxml/__pycache__/sax.cpython-313.pyc,,\ndefusedxml/__pycache__/xmlrpc.cpython-313.pyc,,\ndefusedxml/cElementTree.py,sha256=PpaKMh3rU29sY8amAK4fzHQKl8gcAYD0h1LCoW62Rtk,1449\ndefusedxml/common.py,sha256=3d26jNW4fNXzgjWhvUfs83Afiz5EVxFDupQbugkSMZc,4036\ndefusedxml/expatbuilder.py,sha256=b4Q05vsBMJ5StkiTFf4my2rGGo1gZyEl_hC5MeFTOAA,3732\ndefusedxml/expatreader.py,sha256=KOpSrwkSvj5SGOY9pTXOM26Dnz00rsJt33WueVvzpvc,2196\ndefusedxml/lxml.py,sha256=HW-LFKdrfMRzHdi0Vcucq4-n8yz7v_OQwEQWFg1JQYA,4940\ndefusedxml/minidom.py,sha256=3QcgygVwJqcWDQ3IZ2iol8zsH4cx3BRX70SPcd0bG2g,1884\ndefusedxml/pulldom.py,sha256=DYj2D2lc7xoxZ38gfzujXmdznd8ovzDqGFXqyXbtxjk,1170\ndefusedxml/sax.py,sha256=-SF08Msc2mWEYAMw62pJ5FMwWccOctFSnQwDLYLLlVE,1477\ndefusedxml/xmlrpc.py,sha256=7rZQey3tqXcc1hrrM3RprOICU6fiFny9B9l4nmTioxA,5364\n
.venv\Lib\site-packages\defusedxml-0.7.1.dist-info\RECORD
RECORD
Other
1,938
0.7
0
0
vue-tools
239
2025-06-24T12:52:12.937517
GPL-3.0
false
f62d7f23ec6c9fff0f93d3b61e8e556f
defusedxml\n
.venv\Lib\site-packages\defusedxml-0.7.1.dist-info\top_level.txt
top_level.txt
Other
11
0.5
0
0
awesome-app
117
2025-02-28T03:57:12.434952
Apache-2.0
false
3b3494db6d750cd7739de7394250169a
Wheel-Version: 1.0\nGenerator: bdist_wheel (0.34.2)\nRoot-Is-Purelib: true\nTag: py2-none-any\nTag: py3-none-any\n\n
.venv\Lib\site-packages\defusedxml-0.7.1.dist-info\WHEEL
WHEEL
Other
110
0.7
0
0
react-lib
953
2024-04-29T04:21:42.011717
MIT
false
d2a91f104288b412dbc67b54de94e3ac
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_abc.cpython-313.pyc
test_abc.cpython-313.pyc
Other
8,184
0.95
0.016667
0.025641
vue-tools
612
2023-09-19T08:36:12.198972
GPL-3.0
true
92add65af53350f35739edc99f7ce7ff
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_check.cpython-313.pyc
test_check.cpython-313.pyc
Other
2,117
0.8
0
0.055556
awesome-app
577
2023-11-17T14:43:27.100569
MIT
true
4a52399f7419a442eda37928dc14f6d8
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_classdef.cpython-313.pyc
test_classdef.cpython-313.pyc
Other
20,757
0.95
0.00431
0.004525
python-kit
482
2024-05-17T08:35:00.428927
Apache-2.0
true
f86e3124fc907e9098fd24e1f8ac80e2
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_dataclasses.cpython-313.pyc
test_dataclasses.cpython-313.pyc
Other
1,678
0.7
0
0
python-kit
789
2023-09-04T11:23:50.505593
MIT
true
b2e9cd7d8a7de9702e65a8a6f0665d85
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_detect.cpython-313.pyc
test_detect.cpython-313.pyc
Other
7,667
0.8
0
0.014286
react-lib
303
2023-09-20T02:55:46.024557
BSD-3-Clause
true
b44978b04625563e620db959929a4df2
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_dictviews.cpython-313.pyc
test_dictviews.cpython-313.pyc
Other
2,286
0.7
0
0
react-lib
794
2024-11-17T10:54:54.348117
Apache-2.0
true
23c034a02fe0398aefa5a1ca372f09fc
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_diff.cpython-313.pyc
test_diff.cpython-313.pyc
Other
3,850
0.8
0
0
awesome-app
829
2023-07-25T23:52:54.653116
BSD-3-Clause
true
a2d1bf90bc86b07fa4ef838f263ce0e6
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_extendpickle.cpython-313.pyc
test_extendpickle.cpython-313.pyc
Other
2,203
0.8
0
0
awesome-app
505
2024-11-13T21:31:00.521097
BSD-3-Clause
true
70795882903706959d6fcadb4adcf7a2
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_fglobals.cpython-313.pyc
test_fglobals.cpython-313.pyc
Other
2,954
0.95
0
0
python-kit
86
2024-05-21T12:49:24.006833
GPL-3.0
true
a649da75b90f2eecab1469b7669e0b52
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_file.cpython-313.pyc
test_file.cpython-313.pyc
Other
19,605
0.8
0
0
python-kit
664
2023-10-19T17:40:35.399563
GPL-3.0
true
273d99e76138c05a083f18045a1b4339
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_functions.cpython-313.pyc
test_functions.cpython-313.pyc
Other
7,240
0.95
0.010309
0.010753
vue-tools
78
2023-07-23T13:31:38.235106
GPL-3.0
true
e5dace6643e2e8b2e60633cfd88aba65
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_functors.cpython-313.pyc
test_functors.cpython-313.pyc
Other
1,489
0.8
0
0
react-lib
708
2025-01-18T09:31:45.978993
BSD-3-Clause
true
dcec2e1b4fb8ddabfa72e23bbbdabd82
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_logger.cpython-313.pyc
test_logger.cpython-313.pyc
Other
3,664
0.8
0
0.025641
vue-tools
802
2024-02-26T08:07:10.537157
MIT
true
b6ecb1ebf4ac53aa38f5ca6b4edada59
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_mixins.cpython-313.pyc
test_mixins.cpython-313.pyc
Other
6,902
0.95
0.11194
0.015748
node-utils
752
2024-06-02T02:02:39.167587
MIT
true
9b8331a29c80dda8eb468f1620fe2f79
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_module.cpython-313.pyc
test_module.cpython-313.pyc
Other
3,245
0.95
0
0
react-lib
746
2023-08-15T06:14:33.859467
Apache-2.0
true
fc135382ba5ec6bef91f0078d85ac2d0
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_moduledict.cpython-313.pyc
test_moduledict.cpython-313.pyc
Other
2,173
0.7
0
0
awesome-app
790
2024-11-29T03:57:19.619037
MIT
true
0cb1ab1cffd82b7e236b3d135c933f03
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_nested.cpython-313.pyc
test_nested.cpython-313.pyc
Other
6,548
0.95
0
0
python-kit
469
2025-03-31T09:25:40.350117
Apache-2.0
true
224279867073cf5fae6a942a9b9a026f
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_objects.cpython-313.pyc
test_objects.cpython-313.pyc
Other
2,779
0.8
0.027778
0
react-lib
300
2025-06-27T03:22:11.130033
MIT
true
4637d9a18e579f65535c7e13eb3c71e8
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_properties.cpython-313.pyc
test_properties.cpython-313.pyc
Other
2,528
0.8
0
0
react-lib
490
2024-01-29T09:48:58.571474
BSD-3-Clause
true
19790d46185f19db3a2d3c35364f00f0
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_pycapsule.cpython-313.pyc
test_pycapsule.cpython-313.pyc
Other
2,115
0.8
0
0
vue-tools
902
2024-03-11T07:29:35.881719
Apache-2.0
true
959d5519e48342e674440f2960159ac2
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_recursive.cpython-313.pyc
test_recursive.cpython-313.pyc
Other
9,282
0.95
0
0.031746
awesome-app
708
2024-05-18T09:21:53.100734
BSD-3-Clause
true
4ceceaf0e4a0c16ae5e79665d692d399
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_registered.cpython-313.pyc
test_registered.cpython-313.pyc
Other
2,684
0.8
0
0.04878
react-lib
449
2025-02-14T00:06:09.043031
BSD-3-Clause
true
329317304344a16b40ecfd00b018e8f7
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_restricted.cpython-313.pyc
test_restricted.cpython-313.pyc
Other
1,282
0.85
0.066667
0
node-utils
238
2025-07-03T01:03:00.399719
GPL-3.0
true
aea7551e6bb9f5beb7c4603d33a63dd6
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_selected.cpython-313.pyc
test_selected.cpython-313.pyc
Other
6,345
0.8
0
0
python-kit
537
2025-02-24T12:59:14.748722
GPL-3.0
true
ba101066dcdfdb42d27e0ce647d66f6e
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_session.cpython-313.pyc
test_session.cpython-313.pyc
Other
14,713
0.95
0.032258
0.022222
react-lib
300
2023-10-16T01:59:50.836946
BSD-3-Clause
true
0f7a3e2a041426329d6031706d0b1e41
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_source.cpython-313.pyc
test_source.cpython-313.pyc
Other
8,867
0.95
0.092784
0
awesome-app
486
2024-11-08T00:37:01.703998
BSD-3-Clause
true
c8a1a382de48d885d144546c33213835
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_temp.cpython-313.pyc
test_temp.cpython-313.pyc
Other
4,363
0.95
0
0.051282
react-lib
387
2025-05-17T07:51:07.867743
GPL-3.0
true
1ff39d633f4a4bd6123b2594f2d53ea8
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\test_weakref.cpython-313.pyc
test_weakref.cpython-313.pyc
Other
2,934
0.95
0
0
react-lib
445
2023-10-07T06:05:34.386839
BSD-3-Clause
true
d3731c04ae8b78c17988fbfed2f85be6
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
393
0.7
0.055556
0
node-utils
498
2024-02-14T00:54:11.285799
BSD-3-Clause
true
22025e6bcbcbfe89aec7e3afea7fa275
\n\n
.venv\Lib\site-packages\dill\tests\__pycache__\__main__.cpython-313.pyc
__main__.cpython-313.pyc
Other
1,315
0.8
0
0
react-lib
464
2023-12-30T10:12:32.877177
BSD-3-Clause
true
83049a2b0d38ea290f18f3dd66c18cde
\n\n
.venv\Lib\site-packages\dill\__pycache__\detect.cpython-313.pyc
detect.cpython-313.pyc
Other
13,865
0.95
0.084746
0
react-lib
66
2025-01-12T20:28:20.004507
MIT
false
4f9b4587a509bd5a69ba937282fd30b7
\n\n
.venv\Lib\site-packages\dill\__pycache__\logger.cpython-313.pyc
logger.cpython-313.pyc
Other
12,748
0.95
0.080247
0.028169
python-kit
10
2023-08-29T20:59:39.200937
Apache-2.0
false
2e280e6b1b787c43fd463c4fd62a261c
\n\n
.venv\Lib\site-packages\dill\__pycache__\objtypes.cpython-313.pyc
objtypes.cpython-313.pyc
Other
656
0.7
0
0
node-utils
545
2024-05-16T06:53:02.373733
MIT
false
761f5cc8c3a7f1bb3227fed07bfd2de9
\n\n
.venv\Lib\site-packages\dill\__pycache__\pointers.cpython-313.pyc
pointers.cpython-313.pyc
Other
4,988
0.8
0.064935
0
vue-tools
966
2024-12-22T01:43:44.280439
BSD-3-Clause
false
6aef3edaa3f15feb90dbd9c93c292111
\n\n
.venv\Lib\site-packages\dill\__pycache__\session.cpython-313.pyc
session.cpython-313.pyc
Other
26,051
0.95
0.0625
0.016234
react-lib
659
2024-06-26T19:32:29.247255
BSD-3-Clause
false
80d0e465d1cebe10680bc947572bc67c
\n\n
.venv\Lib\site-packages\dill\__pycache__\settings.cpython-313.pyc
settings.cpython-313.pyc
Other
381
0.7
0.2
0
node-utils
85
2024-12-24T22:09:48.822679
GPL-3.0
false
aabdfe5671f31ba41a04971be22febde
\n\n
.venv\Lib\site-packages\dill\__pycache__\source.cpython-313.pyc
source.cpython-313.pyc
Other
41,871
0.95
0.149254
0.002237
python-kit
947
2025-01-15T16:04:53.185521
Apache-2.0
false
dc79753ae0f3d44c73d3ec6c77e62e1d
\n\n
.venv\Lib\site-packages\dill\__pycache__\temp.cpython-313.pyc
temp.cpython-313.pyc
Other
9,303
0.95
0.023529
0.006993
vue-tools
524
2024-12-04T05:15:53.845203
BSD-3-Clause
false
9561944b0dbc10006bf4ba58c96aeb29
\n\n
.venv\Lib\site-packages\dill\__pycache__\_dill.cpython-313.pyc
_dill.cpython-313.pyc
Other
102,351
0.75
0.025552
0.008663
awesome-app
944
2024-07-15T02:27:12.129842
GPL-3.0
false
485a303ac8ddbcc2a458b3d83eaf4a6c
\n\n
.venv\Lib\site-packages\dill\__pycache__\_objects.cpython-313.pyc
_objects.cpython-313.pyc
Other
25,845
0.95
0
0
node-utils
970
2023-07-21T13:49:28.683862
MIT
false
5b9df53304f5d467037c4f6730de8865
\n\n
.venv\Lib\site-packages\dill\__pycache__\_shims.cpython-313.pyc
_shims.cpython-313.pyc
Other
7,562
0.95
0.169355
0.009709
react-lib
769
2024-03-02T16:03:47.795919
GPL-3.0
false
68dbf46e9336930076d3b5d9d92d40d2
\n\n
.venv\Lib\site-packages\dill\__pycache__\__diff.cpython-313.pyc
__diff.cpython-313.pyc
Other
9,298
0.95
0.026786
0.018018
vue-tools
754
2024-01-24T17:43:58.798187
Apache-2.0
false
ef4b3916770706366fee932260846e20
\n\n
.venv\Lib\site-packages\dill\__pycache__\__info__.cpython-313.pyc
__info__.cpython-313.pyc
Other
10,696
0.95
0.052817
0.028846
python-kit
142
2024-12-08T08:23:36.067148
MIT
false
d7428673970d9e88de5008fbb15b5fb1
\n\n
.venv\Lib\site-packages\dill\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
4,717
0.95
0.09434
0
awesome-app
921
2024-08-19T09:06:52.610238
Apache-2.0
false
dd3c0f4054ebb2ff615e105410500e90
pip\n
.venv\Lib\site-packages\dill-0.3.8.dist-info\INSTALLER
INSTALLER
Other
4
0.5
0
0
awesome-app
415
2025-04-17T10:53:58.779342
BSD-3-Clause
false
365c9bfeb7d89244f2ce01c1de44cb85
Copyright (c) 2004-2016 California Institute of Technology.\nCopyright (c) 2016-2024 The Uncertainty Quantification Foundation.\nAll rights reserved.\n\nThis software is available subject to the conditions and terms laid\nout below. By downloading and using this software you are agreeing\nto the following conditions.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n - Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n - Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n - Neither the names of the copyright holders nor the names of any of\n the contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\nTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\nOR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\nWHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\nOTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n
.venv\Lib\site-packages\dill-0.3.8.dist-info\LICENSE
LICENSE
Other
1,790
0.7
0
0
vue-tools
742
2023-11-01T03:27:07.102720
MIT
false
a41509b57cc475ed93f8cb1dbbfaeec1
Metadata-Version: 2.1\nName: dill\nVersion: 0.3.8\nSummary: serialize all of Python\nHome-page: https://github.com/uqfoundation/dill\nAuthor: Mike McKerns\nAuthor-email: mmckerns@uqfoundation.org\nMaintainer: Mike McKerns\nMaintainer-email: mmckerns@uqfoundation.org\nLicense: BSD-3-Clause\nDownload-URL: https://pypi.org/project/dill/#files\nProject-URL: Documentation, http://dill.rtfd.io\nProject-URL: Source Code, https://github.com/uqfoundation/dill\nProject-URL: Bug Tracker, https://github.com/uqfoundation/dill/issues\nPlatform: Linux\nPlatform: Windows\nPlatform: Mac\nClassifier: Development Status :: 5 - Production/Stable\nClassifier: Intended Audience :: Developers\nClassifier: Intended Audience :: Science/Research\nClassifier: License :: OSI Approved :: BSD License\nClassifier: Programming Language :: Python :: 3\nClassifier: Programming Language :: Python :: 3.8\nClassifier: Programming Language :: Python :: 3.9\nClassifier: Programming Language :: Python :: 3.10\nClassifier: Programming Language :: Python :: 3.11\nClassifier: Programming Language :: Python :: 3.12\nClassifier: Programming Language :: Python :: Implementation :: CPython\nClassifier: Programming Language :: Python :: Implementation :: PyPy\nClassifier: Topic :: Scientific/Engineering\nClassifier: Topic :: Software Development\nRequires-Python: >=3.8\nProvides-Extra: graph\nRequires-Dist: objgraph (>=1.7.2) ; extra == 'graph'\nProvides-Extra: profile\nRequires-Dist: gprof2dot (>=2022.7.29) ; extra == 'profile'\nProvides-Extra: readline\n\n-----------------------------\ndill: serialize all of Python\n-----------------------------\n\nAbout Dill\n==========\n\n``dill`` extends Python's ``pickle`` module for serializing and de-serializing\nPython objects to the majority of the built-in Python types. Serialization\nis the process of converting an object to a byte stream, and the inverse\nof which is converting a byte stream back to a Python object hierarchy.\n\n``dill`` provides the user the same interface as the ``pickle`` module, and\nalso includes some additional features. In addition to pickling Python\nobjects, ``dill`` provides the ability to save the state of an interpreter\nsession in a single command. Hence, it would be feasible to save an\ninterpreter session, close the interpreter, ship the pickled file to\nanother computer, open a new interpreter, unpickle the session and\nthus continue from the 'saved' state of the original interpreter\nsession.\n\n``dill`` can be used to store Python objects to a file, but the primary\nusage is to send Python objects across the network as a byte stream.\n``dill`` is quite flexible, and allows arbitrary user defined classes\nand functions to be serialized. Thus ``dill`` is not intended to be\nsecure against erroneously or maliciously constructed data. It is\nleft to the user to decide whether the data they unpickle is from\na trustworthy source.\n\n``dill`` is part of ``pathos``, a Python framework for heterogeneous computing.\n``dill`` is in active development, so any user feedback, bug reports, comments,\nor suggestions are highly appreciated. A list of issues is located at\nhttps://github.com/uqfoundation/dill/issues, with a legacy list maintained at\nhttps://uqfoundation.github.io/project/pathos/query.\n\n\nMajor Features\n==============\n\n``dill`` can pickle the following standard types:\n\n - none, type, bool, int, float, complex, bytes, str,\n - tuple, list, dict, file, buffer, builtin,\n - Python classes, namedtuples, dataclasses, metaclasses,\n - instances of classes,\n - set, frozenset, array, functions, exceptions\n\n``dill`` can also pickle more 'exotic' standard types:\n\n - functions with yields, nested functions, lambdas,\n - cell, method, unboundmethod, module, code, methodwrapper,\n - methoddescriptor, getsetdescriptor, memberdescriptor, wrapperdescriptor,\n - dictproxy, slice, notimplemented, ellipsis, quit\n\n``dill`` cannot yet pickle these standard types:\n\n - frame, generator, traceback\n\n``dill`` also provides the capability to:\n\n - save and load Python interpreter sessions\n - save and extract the source code from functions and classes\n - interactively diagnose pickling errors\n\n\nCurrent Release\n===============\n\nThe latest released version of ``dill`` is available from:\n\n https://pypi.org/project/dill\n\n``dill`` is distributed under a 3-clause BSD license.\n\n\nDevelopment Version\n===================\n\nYou can get the latest development version with all the shiny new features at:\n\n https://github.com/uqfoundation\n\nIf you have a new contribution, please submit a pull request.\n\n\nInstallation\n============\n\n``dill`` can be installed with ``pip``::\n\n $ pip install dill\n\nTo optionally include the ``objgraph`` diagnostic tool in the install::\n\n $ pip install dill[graph]\n\nTo optionally include the ``gprof2dot`` diagnostic tool in the install::\n\n $ pip install dill[profile]\n\nFor windows users, to optionally install session history tools::\n\n $ pip install dill[readline]\n\n\nRequirements\n============\n\n``dill`` requires:\n\n - ``python`` (or ``pypy``), **>=3.8**\n - ``setuptools``, **>=42**\n\nOptional requirements:\n\n - ``objgraph``, **>=1.7.2**\n - ``gprof2dot``, **>=2022.7.29**\n - ``pyreadline``, **>=1.7.1** (on windows)\n\n\nBasic Usage\n===========\n\n``dill`` is a drop-in replacement for ``pickle``. Existing code can be\nupdated to allow complete pickling using::\n\n >>> import dill as pickle\n\nor::\n\n >>> from dill import dumps, loads\n\n``dumps`` converts the object to a unique byte string, and ``loads`` performs\nthe inverse operation::\n\n >>> squared = lambda x: x**2\n >>> loads(dumps(squared))(3)\n 9\n\nThere are a number of options to control serialization which are provided\nas keyword arguments to several ``dill`` functions:\n\n* with *protocol*, the pickle protocol level can be set. This uses the\n same value as the ``pickle`` module, *DEFAULT_PROTOCOL*.\n* with *byref=True*, ``dill`` to behave a lot more like pickle with\n certain objects (like modules) pickled by reference as opposed to\n attempting to pickle the object itself.\n* with *recurse=True*, objects referred to in the global dictionary are\n recursively traced and pickled, instead of the default behavior of\n attempting to store the entire global dictionary.\n* with *fmode*, the contents of the file can be pickled along with the file\n handle, which is useful if the object is being sent over the wire to a\n remote system which does not have the original file on disk. Options are\n *HANDLE_FMODE* for just the handle, *CONTENTS_FMODE* for the file content\n and *FILE_FMODE* for content and handle.\n* with *ignore=False*, objects reconstructed with types defined in the\n top-level script environment use the existing type in the environment\n rather than a possibly different reconstructed type.\n\nThe default serialization can also be set globally in *dill.settings*.\nThus, we can modify how ``dill`` handles references to the global dictionary\nlocally or globally::\n\n >>> import dill.settings\n >>> dumps(absolute) == dumps(absolute, recurse=True)\n False\n >>> dill.settings['recurse'] = True\n >>> dumps(absolute) == dumps(absolute, recurse=True)\n True\n\n``dill`` also includes source code inspection, as an alternate to pickling::\n\n >>> import dill.source\n >>> print(dill.source.getsource(squared))\n squared = lambda x:x**2\n\nTo aid in debugging pickling issues, use *dill.detect* which provides\ntools like pickle tracing::\n\n >>> import dill.detect\n >>> with dill.detect.trace():\n >>> dumps(squared)\n ┬ F1: <function <lambda> at 0x7fe074f8c280>\n ├┬ F2: <function _create_function at 0x7fe074c49c10>\n │└ # F2 [34 B]\n ├┬ Co: <code object <lambda> at 0x7fe07501eb30, file "<stdin>", line 1>\n │├┬ F2: <function _create_code at 0x7fe074c49ca0>\n ││└ # F2 [19 B]\n │└ # Co [87 B]\n ├┬ D1: <dict object at 0x7fe0750d4680>\n │└ # D1 [22 B]\n ├┬ D2: <dict object at 0x7fe074c5a1c0>\n │└ # D2 [2 B]\n ├┬ D2: <dict object at 0x7fe074f903c0>\n │├┬ D2: <dict object at 0x7fe074f8ebc0>\n ││└ # D2 [2 B]\n │└ # D2 [23 B]\n └ # F1 [180 B]\n\nWith trace, we see how ``dill`` stored the lambda (``F1``) by first storing\n``_create_function``, the underlying code object (``Co``) and ``_create_code``\n(which is used to handle code objects), then we handle the reference to\nthe global dict (``D2``) plus other dictionaries (``D1`` and ``D2``) that\nsave the lambda object's state. A ``#`` marks when the object is actually stored.\n\n\nMore Information\n================\n\nProbably the best way to get started is to look at the documentation at\nhttp://dill.rtfd.io. Also see ``dill.tests`` for a set of scripts that\ndemonstrate how ``dill`` can serialize different Python objects. You can\nrun the test suite with ``python -m dill.tests``. The contents of any\npickle file can be examined with ``undill``. As ``dill`` conforms to\nthe ``pickle`` interface, the examples and documentation found at\nhttp://docs.python.org/library/pickle.html also apply to ``dill``\nif one will ``import dill as pickle``. The source code is also generally\nwell documented, so further questions may be resolved by inspecting the\ncode itself. Please feel free to submit a ticket on github, or ask a\nquestion on stackoverflow (**@Mike McKerns**).\nIf you would like to share how you use ``dill`` in your work, please send\nan email (to **mmckerns at uqfoundation dot org**).\n\n\nCitation\n========\n\nIf you use ``dill`` to do research that leads to publication, we ask that you\nacknowledge use of ``dill`` by citing the following in your publication::\n\n M.M. McKerns, L. Strand, T. Sullivan, A. Fang, M.A.G. Aivazis,\n "Building a framework for predictive science", Proceedings of\n the 10th Python in Science Conference, 2011;\n http://arxiv.org/pdf/1202.1056\n\n Michael McKerns and Michael Aivazis,\n "pathos: a framework for heterogeneous computing", 2010- ;\n https://uqfoundation.github.io/project/pathos\n\nPlease see https://uqfoundation.github.io/project/pathos or\nhttp://arxiv.org/pdf/1202.1056 for further information.\n\n
.venv\Lib\site-packages\dill-0.3.8.dist-info\METADATA
METADATA
Other
10,106
0.95
0.053571
0.028436
react-lib
399
2024-10-10T02:01:36.506241
MIT
false
519815514d38b60136c4d7b8a95a6282
../../Scripts/get_gprof,sha256=8aW52LJ_uV7JXVLl-2t9K-xhUUU7qT-fvTjax9ZPNrg,2508\n../../Scripts/get_objgraph,sha256=sBOS1eLROO_uST9_amIAg4LIGQQelNtwXZ3F7V8Bbvk,1702\n../../Scripts/undill,sha256=ENp9_jGBtzEp3Hy5kUFpKKCwj7zx5sI_-bq_uZZJNwo,638\ndill-0.3.8.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4\ndill-0.3.8.dist-info/LICENSE,sha256=UeiKI-eId86r1yfCGcel4z9l2pugOsT9KFupBKoc4is,1790\ndill-0.3.8.dist-info/METADATA,sha256=UxkSs2cU8JyrJsV5kS0QR9crJ07hrUJS2RiIMQaC4ss,10106\ndill-0.3.8.dist-info/RECORD,,\ndill-0.3.8.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92\ndill-0.3.8.dist-info/top_level.txt,sha256=HLSIyYIjQzJiBvs3_-16ntezE3j6mWGTW0DT1xDd7X0,5\ndill/__diff.py,sha256=kirMxzB7E8lfjo21M5oIf7if95ny0aWhYB790KMpN08,7143\ndill/__info__.py,sha256=Kmel_yLTyH-hwNC5cVfzN-LV08AbS_AvSa2uwMeIQdk,10756\ndill/__init__.py,sha256=j-Jxl3H6bxatS0h2f8ywWs7DChwk7B9ozuZQBVcjYGU,3798\ndill/__pycache__/__diff.cpython-313.pyc,,\ndill/__pycache__/__info__.cpython-313.pyc,,\ndill/__pycache__/__init__.cpython-313.pyc,,\ndill/__pycache__/_dill.cpython-313.pyc,,\ndill/__pycache__/_objects.cpython-313.pyc,,\ndill/__pycache__/_shims.cpython-313.pyc,,\ndill/__pycache__/detect.cpython-313.pyc,,\ndill/__pycache__/logger.cpython-313.pyc,,\ndill/__pycache__/objtypes.cpython-313.pyc,,\ndill/__pycache__/pointers.cpython-313.pyc,,\ndill/__pycache__/session.cpython-313.pyc,,\ndill/__pycache__/settings.cpython-313.pyc,,\ndill/__pycache__/source.cpython-313.pyc,,\ndill/__pycache__/temp.cpython-313.pyc,,\ndill/_dill.py,sha256=3Eo6gKj1sODJjgPgYNT8TU-YL6QNQ7rIeWPUVnRzyqQ,88548\ndill/_objects.py,sha256=dPlUXzQIh8CA0fMy9NMbwwLGUPmXe5H8MdQtRWB1b_M,19605\ndill/_shims.py,sha256=IuzQcyPET5VWmWMoSGStieoedvNXlb5suDpa4bykTbQ,6635\ndill/detect.py,sha256=Mb-PfCxn1mg0l3TmHXyPNVEc4n3fuxc_nue6eL3-q_o,11114\ndill/logger.py,sha256=YS5ZloAOKjJRZaOBRCaMUDWmWVQZcicvbXVSrz8L8XU,11134\ndill/objtypes.py,sha256=BamGH3BEM6lLlxisuvXcGjsCRLNeoLs4_rFZrM5r2yM,736\ndill/pointers.py,sha256=vnQzjwGtKMGnmbdYRXRWNLMyceNPSw4f7UpvwCXLYbE,4467\ndill/session.py,sha256=NvCWpoP9r_rGBL2pOwwxOri8mFly5KlIWG3GwkBFnc0,23525\ndill/settings.py,sha256=7I3yvSpPKstOqpoW2gv3X77kXK-hZlqCnF7nJUGhxTY,630\ndill/source.py,sha256=DWfIxcBjpjbbKYz2DstV9kRdjajBdZLOcLXfsZsPo9U,45121\ndill/temp.py,sha256=KJUry4t0UjQCh5t4LXcxNyMF_uOGHwcjTuNYTJD9qdA,8027\ndill/tests/__init__.py,sha256=Gx-chVB-l-e7ncsGp2zF4BimTjbUyO7BY7RkrO835vY,479\ndill/tests/__main__.py,sha256=fHhioQwcOvTPlf1RM_wVQ0Y3ndETWJOuXJQ2rVtqliA,899\ndill/tests/__pycache__/__init__.cpython-313.pyc,,\ndill/tests/__pycache__/__main__.cpython-313.pyc,,\ndill/tests/__pycache__/test_abc.cpython-313.pyc,,\ndill/tests/__pycache__/test_check.cpython-313.pyc,,\ndill/tests/__pycache__/test_classdef.cpython-313.pyc,,\ndill/tests/__pycache__/test_dataclasses.cpython-313.pyc,,\ndill/tests/__pycache__/test_detect.cpython-313.pyc,,\ndill/tests/__pycache__/test_dictviews.cpython-313.pyc,,\ndill/tests/__pycache__/test_diff.cpython-313.pyc,,\ndill/tests/__pycache__/test_extendpickle.cpython-313.pyc,,\ndill/tests/__pycache__/test_fglobals.cpython-313.pyc,,\ndill/tests/__pycache__/test_file.cpython-313.pyc,,\ndill/tests/__pycache__/test_functions.cpython-313.pyc,,\ndill/tests/__pycache__/test_functors.cpython-313.pyc,,\ndill/tests/__pycache__/test_logger.cpython-313.pyc,,\ndill/tests/__pycache__/test_mixins.cpython-313.pyc,,\ndill/tests/__pycache__/test_module.cpython-313.pyc,,\ndill/tests/__pycache__/test_moduledict.cpython-313.pyc,,\ndill/tests/__pycache__/test_nested.cpython-313.pyc,,\ndill/tests/__pycache__/test_objects.cpython-313.pyc,,\ndill/tests/__pycache__/test_properties.cpython-313.pyc,,\ndill/tests/__pycache__/test_pycapsule.cpython-313.pyc,,\ndill/tests/__pycache__/test_recursive.cpython-313.pyc,,\ndill/tests/__pycache__/test_registered.cpython-313.pyc,,\ndill/tests/__pycache__/test_restricted.cpython-313.pyc,,\ndill/tests/__pycache__/test_selected.cpython-313.pyc,,\ndill/tests/__pycache__/test_session.cpython-313.pyc,,\ndill/tests/__pycache__/test_source.cpython-313.pyc,,\ndill/tests/__pycache__/test_temp.cpython-313.pyc,,\ndill/tests/__pycache__/test_weakref.cpython-313.pyc,,\ndill/tests/test_abc.py,sha256=BSjSKKCQ5_iPfFxAd0yBq4KSAJxelrlC3IzoAhjd1C4,4227\ndill/tests/test_check.py,sha256=4F5gkX6zxY7C5sD2_0Tkqf3T3jmQl0K15FOxYUTZQl0,1396\ndill/tests/test_classdef.py,sha256=fI3fVk4SlsjNMMs5RfU6DUCaxpP7YYRjvLZ2nhXMHuc,8600\ndill/tests/test_dataclasses.py,sha256=yKjFuG24ymLtjk-sZZdhvNY7aDqerTDpMcfi_eV4ft0,890\ndill/tests/test_detect.py,sha256=sE9THufHXCDysBPQ4QkN5DHn6DaIldVRAEciseIRH08,4083\ndill/tests/test_dictviews.py,sha256=Jhol0cQWPwoQrp7OPxGhU8FNRX2GgfFp9fTahCvQEPA,1337\ndill/tests/test_diff.py,sha256=5VIWf2fpV6auLHNfzkHLTrgx6AJBlE2xe5Wanfmq8TM,2667\ndill/tests/test_extendpickle.py,sha256=gONrMBHO94Edhnqm1wo49hgzwmaxHs7L-86Hs-7albY,1315\ndill/tests/test_fglobals.py,sha256=DCvdojmKcLN_X9vX4Qe1FbsqjeoJK-wsY2uJwBfNFro,1676\ndill/tests/test_file.py,sha256=jUU2h8qaDOIe1mn_Ng7wqCZcd7Ucx3TAaI-K_90_Tbk,13578\ndill/tests/test_functions.py,sha256=-mqTpUbzRu8GynjBGD25dRDm8qInIe07sRZmCcA_iXY,4267\ndill/tests/test_functors.py,sha256=7rx9wLmrgFwF0gUm_-SGOISPYSok0XjmrQ-jFMRt6gs,930\ndill/tests/test_logger.py,sha256=D9zGRaA-CEadG13orPS_D4gPVZlkqXf9Zu8wn2oMiYc,2385\ndill/tests/test_mixins.py,sha256=YtB24BjodooLj85ijFbAxiM7LlFQZAUL8RQVx9vIAwY,4007\ndill/tests/test_module.py,sha256=KLl_gZJJqDY7S_bD5wCqKL8JQCS0MDMoipVQSDfASlo,1943\ndill/tests/test_moduledict.py,sha256=faXG6-5AcmCfP3xe2FYGOUdSosU-9TWnKU_ZVqPDaxY,1182\ndill/tests/test_nested.py,sha256=ViWiOrChLZktS0z6qyKqMxDdTuy9kAX4qMgH_OreMcc,3146\ndill/tests/test_objects.py,sha256=pPAth0toC_UWztuKHC7NZlsRBb0g_gSAt70UbUtXEXo,1931\ndill/tests/test_properties.py,sha256=h35c-lYir1JG6oLPtrA0eYE0xoSohIimsA3yIfRw6yA,1346\ndill/tests/test_pycapsule.py,sha256=EXFyB6g1Wx9O9LM6StIeUKhrhln4_hou1xrtGwkt4Cw,1417\ndill/tests/test_recursive.py,sha256=bfr-BsK1Xu0PU7l2srHsDXdY2l1LeM3L3w7NraXO0cc,4182\ndill/tests/test_registered.py,sha256=J3oku053VfdJgYh4Z5_kyFRf-C52JglIzjcyxEaYOhk,1573\ndill/tests/test_restricted.py,sha256=xLMIae8sYJksAj9hKKyHFHIL8vtbGpFeOULz59snYM4,783\ndill/tests/test_selected.py,sha256=Hp-AAd6Qp5FJZ-vY_Bbejo5Rg6xFstec5QkSg5D7Aac,3218\ndill/tests/test_session.py,sha256=KoSPvs4c4VJ8mFMF7EUlD_3GwcOhhipt9fqHr--Go-4,10161\ndill/tests/test_source.py,sha256=wZTYBbpzUwj3Mz5OjrHQKfskaVVwuy2UQDg5p2wLbT4,6036\ndill/tests/test_temp.py,sha256=F_7nJkSetLIBSAYMw1-hYh03iVrEYwGs-4GIUzoBOfY,2619\ndill/tests/test_weakref.py,sha256=mrjZP5aPtUP1wBD6ibPsDsfI9ffmq_Ykt7ltoodi5Lg,1602\n
.venv\Lib\site-packages\dill-0.3.8.dist-info\RECORD
RECORD
Other
6,513
0.85
0
0
react-lib
611
2024-12-02T01:23:03.793815
Apache-2.0
false
d4fddf88fd467efc8293bfddf4c5f5e9
dill\n
.venv\Lib\site-packages\dill-0.3.8.dist-info\top_level.txt
top_level.txt
Other
5
0.5
0
0
awesome-app
602
2025-05-12T02:48:59.739447
MIT
false
2263b82901a6ecb9e4696122a6512e4d
Wheel-Version: 1.0\nGenerator: bdist_wheel (0.37.1)\nRoot-Is-Purelib: true\nTag: py3-none-any\n\n
.venv\Lib\site-packages\dill-0.3.8.dist-info\WHEEL
WHEEL
Other
92
0.5
0
0
vue-tools
205
2025-01-12T16:42:08.022317
Apache-2.0
false
4d57030133e279ceb6a8236264823dfd
__version__ = '2.2.0'
.venv\Lib\site-packages\executing\version.py
version.py
Python
21
0.5
0.1
0
node-utils
975
2024-09-24T22:03:38.885519
BSD-3-Clause
false
ca22d493481ff96c258d8afbf8c307e1
\nclass KnownIssue(Exception):\n """\n Raised in case of an known problem. Mostly because of cpython bugs.\n Executing.node gets set to None in this case.\n """\n\n pass\n\n\nclass VerifierFailure(Exception):\n """\n Thrown for an unexpected mapping from instruction to ast node\n Executing.node gets set to None in this case.\n """\n\n def __init__(self, title, node, instruction):\n # type: (object, object, object) -> None\n self.node = node\n self.instruction = instruction\n\n super().__init__(title) # type: ignore[call-arg]\n
.venv\Lib\site-packages\executing\_exceptions.py
_exceptions.py
Python
568
0.95
0.181818
0.0625
node-utils
487
2024-09-15T07:10:57.572641
GPL-3.0
false
e31c201a203a2dba94653ab87af6d6de
import sys\n\n\n\ndef is_pytest_compatible() -> bool:\n """ returns true if executing can be used for expressions inside assert statements which are rewritten by pytest\n """\n if sys.version_info < (3, 11):\n return False\n\n try:\n import pytest\n except ImportError:\n return False\n\n return pytest.version_tuple >= (8, 3, 4)\n
.venv\Lib\site-packages\executing\_pytest_utils.py
_pytest_utils.py
Python
354
0.85
0.3125
0
awesome-app
926
2024-07-16T13:49:26.064150
Apache-2.0
true
336f736ec5ccc1bc64d5d08f5c90aa07
"""\nGet information about what a frame is currently doing. Typical usage:\n\n import executing\n\n node = executing.Source.executing(frame).node\n # node will be an AST node or None\n"""\n\nfrom collections import namedtuple\n_VersionInfo = namedtuple('_VersionInfo', ('major', 'minor', 'micro'))\nfrom .executing import Source, Executing, only, NotOneValueFound, cache, future_flags\n\nfrom ._pytest_utils import is_pytest_compatible\n\ntry:\n from .version import __version__ # type: ignore[import]\n if "dev" in __version__:\n raise ValueError\nexcept Exception:\n # version.py is auto-generated with the git tag when building\n __version__ = "???"\n __version_info__ = _VersionInfo(-1, -1, -1)\nelse:\n __version_info__ = _VersionInfo(*map(int, __version__.split('.')))\n\n\n__all__ = ["Source","is_pytest_compatible"]\n
.venv\Lib\site-packages\executing\__init__.py
__init__.py
Python
831
0.95
0.071429
0.095238
react-lib
536
2023-10-26T11:03:42.444448
BSD-3-Clause
false
e5396d7f7a8935119ef982f473e9039e
\n\n
.venv\Lib\site-packages\executing\__pycache__\executing.cpython-313.pyc
executing.cpython-313.pyc
Other
49,564
0.95
0.038986
0.006383
python-kit
886
2024-09-16T09:39:42.186905
Apache-2.0
false
a249346b06fa6ebc2b558c0dd2e2a2da
\n\n
.venv\Lib\site-packages\executing\__pycache__\version.cpython-313.pyc
version.cpython-313.pyc
Other
209
0.7
0
0
react-lib
276
2023-08-22T13:37:51.588022
Apache-2.0
false
9a4048df48b4a26786512c42977665fc
\n\n
.venv\Lib\site-packages\executing\__pycache__\_exceptions.cpython-313.pyc
_exceptions.cpython-313.pyc
Other
1,192
0.7
0.052632
0
react-lib
652
2025-03-22T03:11:32.493646
MIT
false
4f5051398b1464eedef35e08388e2295
\n\n
.venv\Lib\site-packages\executing\__pycache__\_position_node_finder.cpython-313.pyc
_position_node_finder.cpython-313.pyc
Other
36,945
0.95
0.021021
0.028846
react-lib
545
2023-10-16T22:17:37.400674
BSD-3-Clause
false
5741badfb2599ef4c694dc62980c2652
\n\n
.venv\Lib\site-packages\executing\__pycache__\_pytest_utils.cpython-313.pyc
_pytest_utils.cpython-313.pyc
Other
743
0.7
0.333333
0
awesome-app
222
2024-03-01T06:18:36.816186
Apache-2.0
true
6bc9a467d94b81b35785bd23847aa456
\n\n
.venv\Lib\site-packages\executing\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
1,114
0.95
0
0.058824
vue-tools
834
2024-12-14T03:48:23.293290
GPL-3.0
false
2b3a107c79793665e3b9aa9c19bfc82c
pip\n
.venv\Lib\site-packages\executing-2.2.0.dist-info\INSTALLER
INSTALLER
Other
4
0.5
0
0
awesome-app
6
2024-06-07T08:01:33.953273
BSD-3-Clause
false
365c9bfeb7d89244f2ce01c1de44cb85
MIT License\n\nCopyright (c) 2019 Alex Hall\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n
.venv\Lib\site-packages\executing-2.2.0.dist-info\LICENSE.txt
LICENSE.txt
Other
1,066
0.7
0
0
vue-tools
865
2025-03-22T23:59:35.218921
Apache-2.0
false
a3d6c15f7859ae235a78f2758e5a48cf
Metadata-Version: 2.1\nName: executing\nVersion: 2.2.0\nSummary: Get the currently executing AST node of a frame, and other information\nHome-page: https://github.com/alexmojaki/executing\nAuthor: Alex Hall\nAuthor-email: alex.mojaki@gmail.com\nLicense: MIT\nClassifier: License :: OSI Approved :: MIT License\nClassifier: Programming Language :: Python\nClassifier: Programming Language :: Python :: 3\nClassifier: Programming Language :: Python :: 3.8\nClassifier: Programming Language :: Python :: 3.9\nClassifier: Programming Language :: Python :: 3.10\nClassifier: Programming Language :: Python :: 3.11\nClassifier: Programming Language :: Python :: 3.12\nClassifier: Programming Language :: Python :: 3.13\nRequires-Python: >=3.8\nDescription-Content-Type: text/markdown\nLicense-File: LICENSE.txt\nProvides-Extra: tests\nRequires-Dist: asttokens>=2.1.0; extra == "tests"\nRequires-Dist: ipython; extra == "tests"\nRequires-Dist: pytest; extra == "tests"\nRequires-Dist: coverage; extra == "tests"\nRequires-Dist: coverage-enable-subprocess; extra == "tests"\nRequires-Dist: littleutils; extra == "tests"\nRequires-Dist: rich; python_version >= "3.11" and extra == "tests"\n\n# executing\n\n[![Build Status](https://github.com/alexmojaki/executing/workflows/Tests/badge.svg?branch=master)](https://github.com/alexmojaki/executing/actions) [![Coverage Status](https://coveralls.io/repos/github/alexmojaki/executing/badge.svg?branch=master)](https://coveralls.io/github/alexmojaki/executing?branch=master) [![Supports Python versions 3.5+, including PyPy](https://img.shields.io/pypi/pyversions/executing.svg)](https://pypi.python.org/pypi/executing)\n\nThis mini-package lets you get information about what a frame is currently doing, particularly the AST node being executed.\n\n* [Usage](#usage)\n * [Getting the AST node](#getting-the-ast-node)\n * [Getting the source code of the node](#getting-the-source-code-of-the-node)\n * [Getting the `__qualname__` of the current function](#getting-the-__qualname__-of-the-current-function)\n * [The Source class](#the-source-class)\n* [Installation](#installation)\n* [How does it work?](#how-does-it-work)\n* [Is it reliable?](#is-it-reliable)\n* [Which nodes can it identify?](#which-nodes-can-it-identify)\n* [Projects that use this](#projects-that-use-this)\n\n## Usage\n\n### Getting the AST node\n\n```python\nimport executing\n\nnode = executing.Source.executing(frame).node\n```\n\nThen `node` will be an AST node (from the `ast` standard library module) or None if the node couldn't be identified (which may happen often and should always be checked).\n\n`node` will always be the same instance for multiple calls with frames at the same point of execution.\n\nIf you have a traceback object, pass it directly to `Source.executing()` rather than the `tb_frame` attribute to get the correct node.\n\n### Getting the source code of the node\n\nFor this you will need to separately install the [`asttokens`](https://github.com/gristlabs/asttokens) library, then obtain an `ASTTokens` object:\n\n```python\nexecuting.Source.executing(frame).source.asttokens()\n```\n\nor:\n\n```python\nexecuting.Source.for_frame(frame).asttokens()\n```\n\nor use one of the convenience methods:\n\n```python\nexecuting.Source.executing(frame).text()\nexecuting.Source.executing(frame).text_range()\n```\n\n### Getting the `__qualname__` of the current function\n\n```python\nexecuting.Source.executing(frame).code_qualname()\n```\n\nor:\n\n```python\nexecuting.Source.for_frame(frame).code_qualname(frame.f_code)\n```\n\n### The `Source` class\n\nEverything goes through the `Source` class. Only one instance of the class is created for each filename. Subclassing it to add more attributes on creation or methods is recommended. The classmethods such as `executing` will respect this. See the source code and docstrings for more detail.\n\n## Installation\n\n pip install executing\n\nIf you don't like that you can just copy the file `executing.py`, there are no dependencies (but of course you won't get updates).\n\n## How does it work?\n\nSuppose the frame is executing this line:\n\n```python\nself.foo(bar.x)\n```\n\nand in particular it's currently obtaining the attribute `self.foo`. Looking at the bytecode, specifically `frame.f_code.co_code[frame.f_lasti]`, we can tell that it's loading an attribute, but it's not obvious which one. We can narrow down the statement being executed using `frame.f_lineno` and find the two `ast.Attribute` nodes representing `self.foo` and `bar.x`. How do we find out which one it is, without recreating the entire compiler in Python?\n\nThe trick is to modify the AST slightly for each candidate expression and observe the changes in the bytecode instructions. We change the AST to this:\n\n```python\n(self.foo ** 'longuniqueconstant')(bar.x)\n```\n \nand compile it, and the bytecode will be almost the same but there will be two new instructions:\n\n LOAD_CONST 'longuniqueconstant'\n BINARY_POWER\n\nand just before that will be a `LOAD_ATTR` instruction corresponding to `self.foo`. Seeing that it's in the same position as the original instruction lets us know we've found our match.\n\n## Is it reliable?\n\nYes - if it identifies a node, you can trust that it's identified the correct one. The tests are very thorough - in addition to unit tests which check various situations directly, there are property tests against a large number of files (see the filenames printed in [this build](https://travis-ci.org/alexmojaki/executing/jobs/557970457)) with real code. Specifically, for each file, the tests:\n \n 1. Identify as many nodes as possible from all the bytecode instructions in the file, and assert that they are all distinct\n 2. Find all the nodes that should be identifiable, and assert that they were indeed identified somewhere\n\nIn other words, it shows that there is a one-to-one mapping between the nodes and the instructions that can be handled. This leaves very little room for a bug to creep in.\n\nFurthermore, `executing` checks that the instructions compiled from the modified AST exactly match the original code save for a few small known exceptions. This accounts for all the quirks and optimisations in the interpreter. \n\n## Which nodes can it identify?\n\nCurrently it works in almost all cases for the following `ast` nodes:\n \n - `Call`, e.g. `self.foo(bar)`\n - `Attribute`, e.g. `point.x`\n - `Subscript`, e.g. `lst[1]`\n - `BinOp`, e.g. `x + y` (doesn't include `and` and `or`)\n - `UnaryOp`, e.g. `-n` (includes `not` but only works sometimes)\n - `Compare` e.g. `a < b` (not for chains such as `0 < p < 1`)\n\nThe plan is to extend to more operations in the future.\n\n## Projects that use this\n\n### My Projects\n\n- **[`stack_data`](https://github.com/alexmojaki/stack_data)**: Extracts data from stack frames and tracebacks, particularly to display more useful tracebacks than the default. Also uses another related library of mine: **[`pure_eval`](https://github.com/alexmojaki/pure_eval)**.\n- **[`futurecoder`](https://futurecoder.io/)**: Highlights the executing node in tracebacks using `executing` via `stack_data`, and provides debugging with `snoop`.\n- **[`snoop`](https://github.com/alexmojaki/snoop)**: A feature-rich and convenient debugging library. Uses `executing` to show the operation which caused an exception and to allow the `pp` function to display the source of its arguments.\n- **[`heartrate`](https://github.com/alexmojaki/heartrate)**: A simple real time visualisation of the execution of a Python program. Uses `executing` to highlight currently executing operations, particularly in each frame of the stack trace.\n- **[`sorcery`](https://github.com/alexmojaki/sorcery)**: Dark magic delights in Python. Uses `executing` to let special callables called spells know where they're being called from.\n\n### Projects I've contributed to\n\n- **[`IPython`](https://github.com/ipython/ipython/pull/12150)**: Highlights the executing node in tracebacks using `executing` via [`stack_data`](https://github.com/alexmojaki/stack_data).\n- **[`icecream`](https://github.com/gruns/icecream)**: 🍦 Sweet and creamy print debugging. Uses `executing` to identify where `ic` is called and print its arguments.\n- **[`friendly_traceback`](https://github.com/friendly-traceback/friendly-traceback)**: Uses `stack_data` and `executing` to pinpoint the cause of errors and provide helpful explanations.\n- **[`python-devtools`](https://github.com/samuelcolvin/python-devtools)**: Uses `executing` for print debugging similar to `icecream`.\n- **[`sentry_sdk`](https://github.com/getsentry/sentry-python)**: Add the integration `sentry_sdk.integrations.executingExecutingIntegration()` to show the function `__qualname__` in each frame in sentry events.\n- **[`varname`](https://github.com/pwwang/python-varname)**: Dark magics about variable names in python. Uses `executing` to find where its various magical functions like `varname` and `nameof` are called from.\n
.venv\Lib\site-packages\executing-2.2.0.dist-info\METADATA
METADATA
Other
8,863
0.95
0.135294
0.191667
node-utils
976
2025-01-09T23:57:36.596433
MIT
false
9ab72575c88eb4ff15d2e945db2651b2
executing-2.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4\nexecuting-2.2.0.dist-info/LICENSE.txt,sha256=pHaiyw70xBRQNApXeii5GsTH9mkTay7hSAR_q9X8QYE,1066\nexecuting-2.2.0.dist-info/METADATA,sha256=6MCv4qfB4fZ1Ik0HXmTLYT6KRcSNNDsRUemiGCMIY_c,8863\nexecuting-2.2.0.dist-info/RECORD,,\nexecuting-2.2.0.dist-info/WHEEL,sha256=OpXWERl2xLPRHTvd2ZXo_iluPEQd8uSbYkJ53NAER_Y,109\nexecuting-2.2.0.dist-info/top_level.txt,sha256=b9Rtf3NtSqc0_Kak6L_lvnbdKPA0GUim2p-XcFQsf5g,10\nexecuting/__init__.py,sha256=agdZWnui3FaB1FepFzVWX5ydS0mlUsVeA0zBLMxhvjk,831\nexecuting/__pycache__/__init__.cpython-313.pyc,,\nexecuting/__pycache__/_exceptions.cpython-313.pyc,,\nexecuting/__pycache__/_position_node_finder.cpython-313.pyc,,\nexecuting/__pycache__/_pytest_utils.cpython-313.pyc,,\nexecuting/__pycache__/executing.cpython-313.pyc,,\nexecuting/__pycache__/version.cpython-313.pyc,,\nexecuting/_exceptions.py,sha256=nf5P5jPnSjjo_8YWlh5AOyLZHF_hNyJpDv0OG2XFYgw,568\nexecuting/_position_node_finder.py,sha256=Itr5vfBTSKMXT36AybFvMoQAqxSoYjHLIveBXv9CS6Q,34701\nexecuting/_pytest_utils.py,sha256=NRj90nTcExS-8R2P8M1wYm9sodhrTlq74RSd4ZvjQRE,354\nexecuting/executing.py,sha256=J0mNe-49OGHG4Pe2WbkPm77F1u9qWDgCIkN_qZLPwmE,42226\nexecuting/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\nexecuting/version.py,sha256=m9ym-CJaJF3mnGNkOqNvAqYNkLuKxfEkjCkGbeFeIsQ,21\n
.venv\Lib\site-packages\executing-2.2.0.dist-info\RECORD
RECORD
Other
1,382
0.7
0
0
awesome-app
933
2024-05-15T18:18:45.767429
BSD-3-Clause
false
07b2392affda56b833c7b20710ca5d3e
executing\n
.venv\Lib\site-packages\executing-2.2.0.dist-info\top_level.txt
top_level.txt
Other
10
0.5
0
0
vue-tools
128
2023-11-26T03:19:39.508457
BSD-3-Clause
false
59a1b8fe536c21d19ad58664bbb0874b
Wheel-Version: 1.0\nGenerator: setuptools (75.3.0)\nRoot-Is-Purelib: true\nTag: py2-none-any\nTag: py3-none-any\n\n
.venv\Lib\site-packages\executing-2.2.0.dist-info\WHEEL
WHEEL
Other
109
0.7
0
0
vue-tools
357
2024-01-23T11:22:14.545234
MIT
false
ed4428a4441e611b8491a90f025ee6e7
import decimal\nimport re\n\nfrom .exceptions import JsonSchemaDefinitionException\nfrom .generator import CodeGenerator, enforce_list\n\n\nJSON_TYPE_TO_PYTHON_TYPE = {\n 'null': 'NoneType',\n 'boolean': 'bool',\n 'number': 'int, float, Decimal',\n 'integer': 'int',\n 'string': 'str',\n 'array': 'list, tuple',\n 'object': 'dict',\n}\n\nDOLLAR_FINDER = re.compile(r"(?<!\\)\$") # Finds any un-escaped $ (including inside []-sets)\n\n\n# pylint: disable=too-many-instance-attributes,too-many-public-methods\nclass CodeGeneratorDraft04(CodeGenerator):\n # pylint: disable=line-too-long\n # I was thinking about using ipaddress module instead of regexps for example, but it's big\n # difference in performance. With a module I got this difference: over 100 ms with a module\n # vs. 9 ms with a regex! Other modules are also ineffective or not available in standard\n # library. Some regexps are not 100% precise but good enough, fast and without dependencies.\n FORMAT_REGEXS = {\n 'date-time': r'^\d{4}-[01]\d-[0-3]\d(t|T)[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:[+-][0-2]\d:[0-5]\d|[+-][0-2]\d[0-5]\d|z|Z)\Z',\n 'email': r'^(?!.*\.\..*@)[^@.][^@]*(?<!\.)@[^@]+\.[^@]+\Z',\n 'hostname': r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9])\Z',\n 'ipv4': r'^((25[0-5]|2[0-4][0-9]|1?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\Z',\n 'ipv6': r'^(?:(?:[0-9A-Fa-f]{1,4}:){6}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|::(?:[0-9A-Fa-f]{1,4}:){5}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){4}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){3}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:(?:[0-9A-Fa-f]{1,4}:){,2}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){2}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:(?:[0-9A-Fa-f]{1,4}:){,3}[0-9A-Fa-f]{1,4})?::[0-9A-Fa-f]{1,4}:(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:(?:[0-9A-Fa-f]{1,4}:){,4}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:(?:[0-9A-Fa-f]{1,4}:){,5}[0-9A-Fa-f]{1,4})?::[0-9A-Fa-f]{1,4}|(?:(?:[0-9A-Fa-f]{1,4}:){,6}[0-9A-Fa-f]{1,4})?::)\Z',\n 'uri': r'^\w+:(\/?\/?)[^\s]+\Z',\n }\n\n def __init__(self, definition, resolver=None, formats={}, use_default=True, use_formats=True, detailed_exceptions=True):\n super().__init__(definition, resolver, detailed_exceptions)\n self._custom_formats = formats\n self._use_formats = use_formats\n self._use_default = use_default\n self._json_keywords_to_function.update((\n ('type', self.generate_type),\n ('enum', self.generate_enum),\n ('allOf', self.generate_all_of),\n ('anyOf', self.generate_any_of),\n ('oneOf', self.generate_one_of),\n ('not', self.generate_not),\n ('minLength', self.generate_min_length),\n ('maxLength', self.generate_max_length),\n ('pattern', self.generate_pattern),\n ('format', self.generate_format),\n ('minimum', self.generate_minimum),\n ('maximum', self.generate_maximum),\n ('multipleOf', self.generate_multiple_of),\n ('minItems', self.generate_min_items),\n ('maxItems', self.generate_max_items),\n ('uniqueItems', self.generate_unique_items),\n ('items', self.generate_items),\n ('minProperties', self.generate_min_properties),\n ('maxProperties', self.generate_max_properties),\n ('required', self.generate_required),\n # Check dependencies before properties generates default values.\n ('dependencies', self.generate_dependencies),\n ('properties', self.generate_properties),\n ('patternProperties', self.generate_pattern_properties),\n ('additionalProperties', self.generate_additional_properties),\n ))\n self._any_or_one_of_count = 0\n\n @property\n def global_state(self):\n res = super().global_state\n res['custom_formats'] = self._custom_formats\n return res\n\n def generate_type(self):\n """\n Validation of type. Can be one type or list of types.\n\n .. code-block:: python\n\n {'type': 'string'}\n {'type': ['string', 'number']}\n """\n types = enforce_list(self._definition['type'])\n try:\n python_types = ', '.join(JSON_TYPE_TO_PYTHON_TYPE[t] for t in types)\n except KeyError as exc:\n raise JsonSchemaDefinitionException('Unknown type: {}'.format(exc))\n\n extra = ''\n if ('number' in types or 'integer' in types) and 'boolean' not in types:\n extra = ' or isinstance({variable}, bool)'.format(variable=self._variable)\n\n with self.l('if not isinstance({variable}, ({})){}:', python_types, extra):\n self.exc('{name} must be {}', ' or '.join(types), rule='type')\n\n def generate_enum(self):\n """\n Means that only value specified in the enum is valid.\n\n .. code-block:: python\n\n {\n 'enum': ['a', 'b'],\n }\n """\n enum = self._definition['enum']\n if not isinstance(enum, (list, tuple)):\n raise JsonSchemaDefinitionException('enum must be an array')\n with self.l('if {variable} not in {enum}:'):\n self.exc('{name} must be one of {}', self.e(enum), rule='enum')\n\n def generate_all_of(self):\n """\n Means that value have to be valid by all of those definitions. It's like put it in\n one big definition.\n\n .. code-block:: python\n\n {\n 'allOf': [\n {'type': 'number'},\n {'minimum': 5},\n ],\n }\n\n Valid values for this definition are 5, 6, 7, ... but not 4 or 'abc' for example.\n """\n for definition_item in self._definition['allOf']:\n self.generate_func_code_block(definition_item, self._variable, self._variable_name, clear_variables=True)\n\n def generate_any_of(self):\n """\n Means that value have to be valid by any of those definitions. It can also be valid\n by all of them.\n\n .. code-block:: python\n\n {\n 'anyOf': [\n {'type': 'number', 'minimum': 10},\n {'type': 'number', 'maximum': 5},\n ],\n }\n\n Valid values for this definition are 3, 4, 5, 10, 11, ... but not 8 for example.\n """\n self._any_or_one_of_count += 1\n count = self._any_or_one_of_count\n self.l('{variable}_any_of_count{count} = 0', count=count)\n for definition_item in self._definition['anyOf']:\n # When we know it's passing (at least once), we do not need to do another expensive try-except.\n with self.l('if not {variable}_any_of_count{count}:', count=count, optimize=False):\n with self.l('try:', optimize=False):\n self.generate_func_code_block(definition_item, self._variable, self._variable_name, clear_variables=True)\n self.l('{variable}_any_of_count{count} += 1', count=count)\n self.l('except JsonSchemaValueException: pass')\n\n with self.l('if not {variable}_any_of_count{count}:', count=count, optimize=False):\n self.exc('{name} cannot be validated by any definition', rule='anyOf')\n\n def generate_one_of(self):\n """\n Means that value have to be valid by only one of those definitions. It can't be valid\n by two or more of them.\n\n .. code-block:: python\n\n {\n 'oneOf': [\n {'type': 'number', 'multipleOf': 3},\n {'type': 'number', 'multipleOf': 5},\n ],\n }\n\n Valid values for this definition are 3, 5, 6, ... but not 15 for example.\n """\n self._any_or_one_of_count += 1\n count = self._any_or_one_of_count\n self.l('{variable}_one_of_count{count} = 0', count=count)\n for definition_item in self._definition['oneOf']:\n # When we know it's failing (one of means exactly once), we do not need to do another expensive try-except.\n with self.l('if {variable}_one_of_count{count} < 2:', count=count, optimize=False):\n with self.l('try:', optimize=False):\n self.generate_func_code_block(definition_item, self._variable, self._variable_name, clear_variables=True)\n self.l('{variable}_one_of_count{count} += 1', count=count)\n self.l('except JsonSchemaValueException: pass')\n\n with self.l('if {variable}_one_of_count{count} != 1:', count=count):\n dynamic = '" (" + str({variable}_one_of_count{}) + " matches found)"'\n self.exc('{name} must be valid exactly by one definition', count, append_to_msg=dynamic, rule='oneOf')\n\n def generate_not(self):\n """\n Means that value have not to be valid by this definition.\n\n .. code-block:: python\n\n {'not': {'type': 'null'}}\n\n Valid values for this definition are 'hello', 42, {} ... but not None.\n\n Since draft 06 definition can be boolean. False means nothing, True\n means everything is invalid.\n """\n not_definition = self._definition['not']\n if not_definition is True:\n self.exc('{name} must not be there', rule='not')\n elif not_definition is False:\n return\n elif not not_definition:\n self.exc('{name} must NOT match a disallowed definition', rule='not')\n else:\n with self.l('try:', optimize=False):\n self.generate_func_code_block(not_definition, self._variable, self._variable_name)\n self.l('except JsonSchemaValueException: pass')\n with self.l('else:'):\n self.exc('{name} must NOT match a disallowed definition', rule='not')\n\n def generate_min_length(self):\n with self.l('if isinstance({variable}, str):'):\n self.create_variable_with_length()\n if not isinstance(self._definition['minLength'], (int, float)):\n raise JsonSchemaDefinitionException('minLength must be a number')\n with self.l('if {variable}_len < {minLength}:'):\n self.exc('{name} must be longer than or equal to {minLength} characters', rule='minLength')\n\n def generate_max_length(self):\n with self.l('if isinstance({variable}, str):'):\n self.create_variable_with_length()\n if not isinstance(self._definition['maxLength'], (int, float)):\n raise JsonSchemaDefinitionException('maxLength must be a number')\n with self.l('if {variable}_len > {maxLength}:'):\n self.exc('{name} must be shorter than or equal to {maxLength} characters', rule='maxLength')\n\n def generate_pattern(self):\n with self.l('if isinstance({variable}, str):'):\n pattern = self._definition['pattern']\n safe_pattern = pattern.replace('\\', '\\\\').replace('"', '\\"')\n end_of_string_fixed_pattern = DOLLAR_FINDER.sub(r'\\Z', pattern)\n self._compile_regexps[pattern] = re.compile(end_of_string_fixed_pattern)\n with self.l('if not REGEX_PATTERNS[{}].search({variable}):', repr(pattern)):\n self.exc('{name} must match pattern {}', safe_pattern, rule='pattern')\n\n def generate_format(self):\n """\n Means that value have to be in specified format. For example date, email or other.\n\n .. code-block:: python\n\n {'format': 'email'}\n\n Valid value for this definition is user@example.com but not @username\n """\n if not self._use_formats:\n return\n with self.l('if isinstance({variable}, str):'):\n format_ = self._definition['format']\n # Checking custom formats - user is allowed to override default formats.\n if format_ in self._custom_formats:\n custom_format = self._custom_formats[format_]\n if isinstance(custom_format, str):\n self._generate_format(format_, format_ + '_re_pattern', custom_format)\n else:\n with self.l('if not custom_formats["{}"]({variable}):', format_):\n self.exc('{name} must be {}', format_, rule='format')\n elif format_ in self.FORMAT_REGEXS:\n format_regex = self.FORMAT_REGEXS[format_]\n self._generate_format(format_, format_ + '_re_pattern', format_regex)\n # Format regex is used only in meta schemas.\n elif format_ == 'regex':\n self._extra_imports_lines = ['import re'] \n with self.l('try:', optimize=False):\n self.l('re.compile({variable})')\n with self.l('except Exception:'):\n self.exc('{name} must be a valid regex', rule='format')\n else:\n raise JsonSchemaDefinitionException('Unknown format: {}'.format(format_))\n\n\n def _generate_format(self, format_name, regexp_name, regexp):\n if self._definition['format'] == format_name:\n if not regexp_name in self._compile_regexps:\n self._compile_regexps[regexp_name] = re.compile(regexp)\n with self.l('if not REGEX_PATTERNS["{}"].match({variable}):', regexp_name):\n self.exc('{name} must be {}', format_name, rule='format')\n\n def generate_minimum(self):\n with self.l('if isinstance({variable}, (int, float, Decimal)):'):\n if not isinstance(self._definition['minimum'], (int, float, decimal.Decimal)):\n raise JsonSchemaDefinitionException('minimum must be a number')\n if self._definition.get('exclusiveMinimum', False):\n with self.l('if {variable} <= {minimum}:'):\n self.exc('{name} must be bigger than {minimum}', rule='minimum')\n else:\n with self.l('if {variable} < {minimum}:'):\n self.exc('{name} must be bigger than or equal to {minimum}', rule='minimum')\n\n def generate_maximum(self):\n with self.l('if isinstance({variable}, (int, float, Decimal)):'):\n if not isinstance(self._definition['maximum'], (int, float, decimal.Decimal)):\n raise JsonSchemaDefinitionException('maximum must be a number')\n if self._definition.get('exclusiveMaximum', False):\n with self.l('if {variable} >= {maximum}:'):\n self.exc('{name} must be smaller than {maximum}', rule='maximum')\n else:\n with self.l('if {variable} > {maximum}:'):\n self.exc('{name} must be smaller than or equal to {maximum}', rule='maximum')\n\n def generate_multiple_of(self):\n with self.l('if isinstance({variable}, (int, float, Decimal)):'):\n if not isinstance(self._definition['multipleOf'], (int, float, decimal.Decimal)):\n raise JsonSchemaDefinitionException('multipleOf must be a number')\n # For proper multiplication check of floats we need to use decimals,\n # because for example 19.01 / 0.01 = 1901.0000000000002.\n if isinstance(self._definition['multipleOf'], float):\n self.l('quotient = Decimal(repr({variable})) / Decimal(repr({multipleOf}))')\n else:\n self.l('quotient = {variable} / {multipleOf}')\n with self.l('if int(quotient) != quotient:'):\n self.exc('{name} must be multiple of {multipleOf}', rule='multipleOf')\n # For example, 1e308 / 0.123456789\n with self.l('if {variable} / {multipleOf} == float("inf"):'):\n self.exc('inifinity reached', rule='multipleOf')\n\n def generate_min_items(self):\n self.create_variable_is_list()\n with self.l('if {variable}_is_list:'):\n if not isinstance(self._definition['minItems'], (int, float)):\n raise JsonSchemaDefinitionException('minItems must be a number')\n self.create_variable_with_length()\n with self.l('if {variable}_len < {minItems}:'):\n self.exc('{name} must contain at least {minItems} items', rule='minItems')\n\n def generate_max_items(self):\n self.create_variable_is_list()\n with self.l('if {variable}_is_list:'):\n if not isinstance(self._definition['maxItems'], (int, float)):\n raise JsonSchemaDefinitionException('maxItems must be a number')\n self.create_variable_with_length()\n with self.l('if {variable}_len > {maxItems}:'):\n self.exc('{name} must contain less than or equal to {maxItems} items', rule='maxItems')\n\n def generate_unique_items(self):\n """\n With Python 3.4 module ``timeit`` recommended this solutions:\n\n .. code-block:: python\n\n >>> timeit.timeit("len(x) > len(set(x))", "x=range(100)+range(100)", number=100000)\n 0.5839540958404541\n >>> timeit.timeit("len({}.fromkeys(x)) == len(x)", "x=range(100)+range(100)", number=100000)\n 0.7094449996948242\n >>> timeit.timeit("seen = set(); any(i in seen or seen.add(i) for i in x)", "x=range(100)+range(100)", number=100000)\n 2.0819358825683594\n >>> timeit.timeit("np.unique(x).size == len(x)", "x=range(100)+range(100); import numpy as np", number=100000)\n 2.1439831256866455\n """\n unique_definition = self._definition['uniqueItems']\n if not unique_definition:\n return\n\n self.create_variable_is_list()\n with self.l('if {variable}_is_list:'):\n self.l(\n 'def fn(var): '\n 'return frozenset(dict((k, fn(v)) '\n 'for k, v in var.items()).items()) '\n 'if hasattr(var, "items") else tuple(fn(v) '\n 'for v in var) '\n 'if isinstance(var, (dict, list)) else str(var) '\n 'if isinstance(var, bool) else var')\n self.create_variable_with_length()\n with self.l('if {variable}_len > len(set(fn({variable}_x) for {variable}_x in {variable})):'):\n self.exc('{name} must contain unique items', rule='uniqueItems')\n\n def generate_items(self):\n """\n Means array is valid only when all items are valid by this definition.\n\n .. code-block:: python\n\n {\n 'items': [\n {'type': 'integer'},\n {'type': 'string'},\n ],\n }\n\n Valid arrays are those with integers or strings, nothing else.\n\n Since draft 06 definition can be also boolean. True means nothing, False\n means everything is invalid.\n """\n items_definition = self._definition['items']\n if items_definition is True:\n return\n\n self.create_variable_is_list()\n with self.l('if {variable}_is_list:'):\n self.create_variable_with_length()\n if items_definition is False:\n with self.l('if {variable}:'):\n self.exc('{name} must not be there', rule='items')\n elif isinstance(items_definition, list):\n for idx, item_definition in enumerate(items_definition):\n with self.l('if {variable}_len > {}:', idx):\n self.l('{variable}__{0} = {variable}[{0}]', idx)\n self.generate_func_code_block(\n item_definition,\n '{}__{}'.format(self._variable, idx),\n '{}[{}]'.format(self._variable_name, idx),\n )\n if self._use_default and isinstance(item_definition, dict) and 'default' in item_definition:\n self.l('else: {variable}.append({})', repr(item_definition['default']))\n\n if 'additionalItems' in self._definition:\n if self._definition['additionalItems'] is False:\n with self.l('if {variable}_len > {}:', len(items_definition)):\n self.exc('{name} must contain only specified items', rule='items')\n else:\n with self.l('for {variable}_x, {variable}_item in enumerate({variable}[{0}:], {0}):', len(items_definition)):\n count = self.generate_func_code_block(\n self._definition['additionalItems'],\n '{}_item'.format(self._variable),\n '{}[{{{}_x}}]'.format(self._variable_name, self._variable),\n )\n if count == 0:\n self.l('pass')\n else:\n if items_definition:\n with self.l('for {variable}_x, {variable}_item in enumerate({variable}):'):\n count = self.generate_func_code_block(\n items_definition,\n '{}_item'.format(self._variable),\n '{}[{{{}_x}}]'.format(self._variable_name, self._variable),\n )\n if count == 0:\n self.l('pass')\n\n def generate_min_properties(self):\n self.create_variable_is_dict()\n with self.l('if {variable}_is_dict:'):\n if not isinstance(self._definition['minProperties'], (int, float)):\n raise JsonSchemaDefinitionException('minProperties must be a number')\n self.create_variable_with_length()\n with self.l('if {variable}_len < {minProperties}:'):\n self.exc('{name} must contain at least {minProperties} properties', rule='minProperties')\n\n def generate_max_properties(self):\n self.create_variable_is_dict()\n with self.l('if {variable}_is_dict:'):\n if not isinstance(self._definition['maxProperties'], (int, float)):\n raise JsonSchemaDefinitionException('maxProperties must be a number')\n self.create_variable_with_length()\n with self.l('if {variable}_len > {maxProperties}:'):\n self.exc('{name} must contain less than or equal to {maxProperties} properties', rule='maxProperties')\n\n def generate_required(self):\n self.create_variable_is_dict()\n with self.l('if {variable}_is_dict:'):\n if not isinstance(self._definition['required'], (list, tuple)):\n raise JsonSchemaDefinitionException('required must be an array')\n if len(self._definition['required']) != len(set(self._definition['required'])):\n raise JsonSchemaDefinitionException('required must contain unique elements')\n if not self._definition.get('additionalProperties', True):\n not_possible = [\n prop\n for prop in self._definition['required']\n if\n prop not in self._definition.get('properties', {})\n and not any(re.search(regex, prop) for regex in self._definition.get('patternProperties', {}))\n ]\n if not_possible:\n raise JsonSchemaDefinitionException('{}: items {} are required but not allowed'.format(self._variable, not_possible))\n self.l('{variable}__missing_keys = set({required}) - {variable}.keys()')\n with self.l('if {variable}__missing_keys:'):\n dynamic = 'str(sorted({variable}__missing_keys)) + " properties"'\n self.exc('{name} must contain ', self.e(self._definition['required']), rule='required', append_to_msg=dynamic)\n\n def generate_properties(self):\n """\n Means object with defined keys.\n\n .. code-block:: python\n\n {\n 'properties': {\n 'key': {'type': 'number'},\n },\n }\n\n Valid object is containing key called 'key' and value any number.\n """\n self.create_variable_is_dict()\n with self.l('if {variable}_is_dict:'):\n self.create_variable_keys()\n for key, prop_definition in self._definition['properties'].items():\n key_name = re.sub(r'($[^a-zA-Z]|[^a-zA-Z0-9])', '', key)\n if not isinstance(prop_definition, (dict, bool)):\n raise JsonSchemaDefinitionException('{}[{}] must be object'.format(self._variable, key_name))\n with self.l('if "{}" in {variable}_keys:', self.e(key)):\n self.l('{variable}_keys.remove("{}")', self.e(key))\n self.l('{variable}__{0} = {variable}["{1}"]', key_name, self.e(key))\n self.generate_func_code_block(\n prop_definition,\n '{}__{}'.format(self._variable, key_name),\n '{}.{}'.format(self._variable_name, self.e(key)),\n clear_variables=True,\n )\n if self._use_default and isinstance(prop_definition, dict) and 'default' in prop_definition:\n self.l('else: {variable}["{}"] = {}', self.e(key), repr(prop_definition['default']))\n\n def generate_pattern_properties(self):\n """\n Means object with defined keys as patterns.\n\n .. code-block:: python\n\n {\n 'patternProperties': {\n '^x': {'type': 'number'},\n },\n }\n\n Valid object is containing key starting with a 'x' and value any number.\n """\n self.create_variable_is_dict()\n with self.l('if {variable}_is_dict:'):\n self.create_variable_keys()\n for pattern, definition in self._definition['patternProperties'].items():\n self._compile_regexps[pattern] = re.compile(pattern)\n with self.l('for {variable}_key, {variable}_val in {variable}.items():'):\n for pattern, definition in self._definition['patternProperties'].items():\n with self.l('if REGEX_PATTERNS[{}].search({variable}_key):', repr(pattern)):\n with self.l('if {variable}_key in {variable}_keys:'):\n self.l('{variable}_keys.remove({variable}_key)')\n self.generate_func_code_block(\n definition,\n '{}_val'.format(self._variable),\n '{}.{{{}_key}}'.format(self._variable_name, self._variable),\n clear_variables=True,\n )\n\n def generate_additional_properties(self):\n """\n Means object with keys with values defined by definition.\n\n .. code-block:: python\n\n {\n 'properties': {\n 'key': {'type': 'number'},\n }\n 'additionalProperties': {'type': 'string'},\n }\n\n Valid object is containing key called 'key' and it's value any number and\n any other key with any string.\n """\n self.create_variable_is_dict()\n with self.l('if {variable}_is_dict:'):\n self.create_variable_keys()\n add_prop_definition = self._definition["additionalProperties"]\n if add_prop_definition is True or add_prop_definition == {}:\n return\n if add_prop_definition:\n properties_keys = list(self._definition.get("properties", {}).keys())\n with self.l('for {variable}_key in {variable}_keys:'):\n with self.l('if {variable}_key not in {}:', properties_keys):\n self.l('{variable}_value = {variable}.get({variable}_key)')\n self.generate_func_code_block(\n add_prop_definition,\n '{}_value'.format(self._variable),\n '{}.{{{}_key}}'.format(self._variable_name, self._variable),\n )\n else:\n with self.l('if {variable}_keys:'):\n self.exc('{name} must not contain "+str({variable}_keys)+" properties', rule='additionalProperties')\n\n def generate_dependencies(self):\n """\n Means when object has property, it needs to have also other property.\n\n .. code-block:: python\n\n {\n 'dependencies': {\n 'bar': ['foo'],\n },\n }\n\n Valid object is containing only foo, both bar and foo or none of them, but not\n object with only bar.\n\n Since draft 06 definition can be boolean or empty array. True and empty array\n means nothing, False means that key cannot be there at all.\n """\n self.create_variable_is_dict()\n with self.l('if {variable}_is_dict:'):\n is_empty = True\n for key, values in self._definition["dependencies"].items():\n if values == [] or values is True:\n continue\n is_empty = False\n with self.l('if "{}" in {variable}:', self.e(key)):\n if values is False:\n self.exc('{} in {name} must not be there', key, rule='dependencies')\n elif isinstance(values, list):\n for value in values:\n with self.l('if "{}" not in {variable}:', self.e(value)):\n self.exc('{name} missing dependency {} for {}', self.e(value), self.e(key), rule='dependencies')\n else:\n self.generate_func_code_block(values, self._variable, self._variable_name, clear_variables=True)\n if is_empty:\n self.l('pass')\n
.venv\Lib\site-packages\fastjsonschema\draft04.py
draft04.py
Python
30,808
0.95
0.262136
0.026022
awesome-app
87
2024-04-23T02:09:10.134577
MIT
false
c333557f27e50e72f493881249639bb1
import decimal\nfrom .draft04 import CodeGeneratorDraft04, JSON_TYPE_TO_PYTHON_TYPE\nfrom .exceptions import JsonSchemaDefinitionException\nfrom .generator import enforce_list\n\n\nclass CodeGeneratorDraft06(CodeGeneratorDraft04):\n FORMAT_REGEXS = dict(CodeGeneratorDraft04.FORMAT_REGEXS, **{\n 'json-pointer': r'^(/(([^/~])|(~[01]))*)*\Z',\n 'uri-reference': r'^(\w+:(\/?\/?))?[^#\\\s]*(#[^\\\s]*)?\Z',\n 'uri-template': (\n r'^(?:(?:[^\x00-\x20\"\'<>%\\^`{|}]|%[0-9a-f]{2})|'\n r'\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+'\n r'(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+'\n r'(?::[1-9][0-9]{0,3}|\*)?)*\})*\Z'\n ),\n })\n\n def __init__(self, definition, resolver=None, formats={}, use_default=True, use_formats=True, detailed_exceptions=True):\n super().__init__(definition, resolver, formats, use_default, use_formats, detailed_exceptions)\n self._json_keywords_to_function.update((\n ('exclusiveMinimum', self.generate_exclusive_minimum),\n ('exclusiveMaximum', self.generate_exclusive_maximum),\n ('propertyNames', self.generate_property_names),\n ('contains', self.generate_contains),\n ('const', self.generate_const),\n ))\n\n def _generate_func_code_block(self, definition):\n if isinstance(definition, bool):\n self.generate_boolean_schema()\n elif '$ref' in definition:\n # needed because ref overrides any sibling keywords\n self.generate_ref()\n else:\n self.run_generate_functions(definition)\n\n def generate_boolean_schema(self):\n """\n Means that schema can be specified by boolean.\n True means everything is valid, False everything is invalid.\n """\n if self._definition is True:\n self.l('pass')\n if self._definition is False:\n self.exc('{name} must not be there')\n\n def generate_type(self):\n """\n Validation of type. Can be one type or list of types.\n\n Since draft 06 a float without fractional part is an integer.\n\n .. code-block:: python\n\n {'type': 'string'}\n {'type': ['string', 'number']}\n """\n types = enforce_list(self._definition['type'])\n try:\n python_types = ', '.join(JSON_TYPE_TO_PYTHON_TYPE[t] for t in types)\n except KeyError as exc:\n raise JsonSchemaDefinitionException('Unknown type: {}'.format(exc))\n\n extra = ''\n\n if 'integer' in types:\n extra += ' and not (isinstance({variable}, float) and {variable}.is_integer())'.format(\n variable=self._variable,\n )\n\n if ('number' in types or 'integer' in types) and 'boolean' not in types:\n extra += ' or isinstance({variable}, bool)'.format(variable=self._variable)\n\n with self.l('if not isinstance({variable}, ({})){}:', python_types, extra):\n self.exc('{name} must be {}', ' or '.join(types), rule='type')\n\n def generate_exclusive_minimum(self):\n with self.l('if isinstance({variable}, (int, float, Decimal)):'):\n if not isinstance(self._definition['exclusiveMinimum'], (int, float, decimal.Decimal)):\n raise JsonSchemaDefinitionException('exclusiveMinimum must be an integer, a float or a decimal')\n with self.l('if {variable} <= {exclusiveMinimum}:'):\n self.exc('{name} must be bigger than {exclusiveMinimum}', rule='exclusiveMinimum')\n\n def generate_exclusive_maximum(self):\n with self.l('if isinstance({variable}, (int, float, Decimal)):'):\n if not isinstance(self._definition['exclusiveMaximum'], (int, float, decimal.Decimal)):\n raise JsonSchemaDefinitionException('exclusiveMaximum must be an integer, a float or a decimal')\n with self.l('if {variable} >= {exclusiveMaximum}:'):\n self.exc('{name} must be smaller than {exclusiveMaximum}', rule='exclusiveMaximum')\n\n def generate_property_names(self):\n """\n Means that keys of object must to follow this definition.\n\n .. code-block:: python\n\n {\n 'propertyNames': {\n 'maxLength': 3,\n },\n }\n\n Valid keys of object for this definition are foo, bar, ... but not foobar for example.\n """\n property_names_definition = self._definition.get('propertyNames', {})\n if property_names_definition is True:\n pass\n elif property_names_definition is False:\n self.create_variable_keys()\n with self.l('if {variable}_keys:'):\n self.exc('{name} must not be there', rule='propertyNames')\n else:\n self.create_variable_is_dict()\n with self.l('if {variable}_is_dict:'):\n self.create_variable_with_length()\n with self.l('if {variable}_len != 0:'):\n self.l('{variable}_property_names = True')\n with self.l('for {variable}_key in {variable}:'):\n with self.l('try:'):\n self.generate_func_code_block(\n property_names_definition,\n '{}_key'.format(self._variable),\n self._variable_name,\n clear_variables=True,\n )\n with self.l('except JsonSchemaValueException:'):\n self.l('{variable}_property_names = False')\n with self.l('if not {variable}_property_names:'):\n self.exc('{name} must be named by propertyName definition', rule='propertyNames')\n\n def generate_contains(self):\n """\n Means that array must contain at least one defined item.\n\n .. code-block:: python\n\n {\n 'contains': {\n 'type': 'number',\n },\n }\n\n Valid array is any with at least one number.\n """\n self.create_variable_is_list()\n with self.l('if {variable}_is_list:'):\n contains_definition = self._definition['contains']\n\n if contains_definition is False:\n self.exc('{name} is always invalid', rule='contains')\n elif contains_definition is True:\n with self.l('if not {variable}:'):\n self.exc('{name} must not be empty', rule='contains')\n else:\n self.l('{variable}_contains = False')\n with self.l('for {variable}_key in {variable}:'):\n with self.l('try:'):\n self.generate_func_code_block(\n contains_definition,\n '{}_key'.format(self._variable),\n self._variable_name,\n clear_variables=True,\n )\n self.l('{variable}_contains = True')\n self.l('break')\n self.l('except JsonSchemaValueException: pass')\n\n with self.l('if not {variable}_contains:'):\n self.exc('{name} must contain one of contains definition', rule='contains')\n\n def generate_const(self):\n """\n Means that value is valid when is equeal to const definition.\n\n .. code-block:: python\n\n {\n 'const': 42,\n }\n\n Only valid value is 42 in this example.\n """\n const = self._definition['const']\n if isinstance(const, str):\n const = '"{}"'.format(self.e(const))\n with self.l('if {variable} != {}:', const):\n self.exc('{name} must be same as const definition: {definition_rule}', rule='const')\n
.venv\Lib\site-packages\fastjsonschema\draft06.py
draft06.py
Python
7,892
0.95
0.218085
0.006289
awesome-app
106
2024-09-28T00:39:48.613185
GPL-3.0
false
d96b09e9f3266e0d634ed94baef2b565
from .draft06 import CodeGeneratorDraft06\n\n\nclass CodeGeneratorDraft07(CodeGeneratorDraft06):\n FORMAT_REGEXS = dict(CodeGeneratorDraft06.FORMAT_REGEXS, **{\n 'date': r'^(?P<year>\d{4})-(?P<month>(0[1-9]|1[0-2]))-(?P<day>(0[1-9]|[12]\d|3[01]))\Z',\n 'iri': r'^\w+:(\/?\/?)[^\s]+\Z',\n 'iri-reference': r'^(\w+:(\/?\/?))?[^#\\\s]*(#[^\\\s]*)?\Z',\n 'idn-email': r'^[^@]+@[^@]+\.[^@]+\Z',\n 'idn-hostname': r'^(?!-)(xn--)?[a-zA-Z0-9][a-zA-Z0-9-_]{0,61}[a-zA-Z0-9]{0,1}\.(?!-)(xn--)?([a-zA-Z0-9\-]{1,50}|[a-zA-Z0-9-]{1,30}\.[a-zA-Z]{2,})$',\n 'relative-json-pointer': r'^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)\Z',\n #'regex': r'',\n 'time': (\n r'^(?P<hour>\d{1,2}):(?P<minute>\d{1,2})'\n r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6}))?'\n r'([zZ]|[+-]\d\d:\d\d)?)?\Z'\n ),\n })\n\n def __init__(self, definition, resolver=None, formats={}, use_default=True, use_formats=True, detailed_exceptions=True):\n super().__init__(definition, resolver, formats, use_default, use_formats, detailed_exceptions)\n # pylint: disable=duplicate-code\n self._json_keywords_to_function.update((\n ('if', self.generate_if_then_else),\n ('contentEncoding', self.generate_content_encoding),\n ('contentMediaType', self.generate_content_media_type),\n ))\n\n def generate_if_then_else(self):\n """\n Implementation of if-then-else.\n\n .. code-block:: python\n\n {\n 'if': {\n 'exclusiveMaximum': 0,\n },\n 'then': {\n 'minimum': -10,\n },\n 'else': {\n 'multipleOf': 2,\n },\n }\n\n Valid values are any between -10 and 0 or any multiplication of two.\n """\n with self.l('try:', optimize=False):\n self.generate_func_code_block(\n self._definition['if'],\n self._variable,\n self._variable_name,\n clear_variables=True\n )\n with self.l('except JsonSchemaValueException:'):\n if 'else' in self._definition:\n self.generate_func_code_block(\n self._definition['else'],\n self._variable,\n self._variable_name,\n clear_variables=True\n )\n else:\n self.l('pass')\n if 'then' in self._definition:\n with self.l('else:'):\n self.generate_func_code_block(\n self._definition['then'],\n self._variable,\n self._variable_name,\n clear_variables=True\n )\n\n def generate_content_encoding(self):\n """\n Means decoding value when it's encoded by base64.\n\n .. code-block:: python\n\n {\n 'contentEncoding': 'base64',\n }\n """\n if self._definition['contentEncoding'] == 'base64':\n with self.l('if isinstance({variable}, str):'):\n with self.l('try:'):\n self.l('import base64')\n self.l('{variable} = base64.b64decode({variable})')\n with self.l('except Exception:'):\n self.exc('{name} must be encoded by base64')\n with self.l('if {variable} == "":'):\n self.exc('contentEncoding must be base64')\n\n def generate_content_media_type(self):\n """\n Means loading value when it's specified as JSON.\n\n .. code-block:: python\n\n {\n 'contentMediaType': 'application/json',\n }\n """\n if self._definition['contentMediaType'] == 'application/json':\n with self.l('if isinstance({variable}, bytes):'):\n with self.l('try:'):\n self.l('{variable} = {variable}.decode("utf-8")')\n with self.l('except Exception:'):\n self.exc('{name} must encoded by utf8')\n with self.l('if isinstance({variable}, str):'):\n with self.l('try:'):\n self.l('import json')\n self.l('{variable} = json.loads({variable})')\n with self.l('except Exception:'):\n self.exc('{name} must be valid JSON')\n
.venv\Lib\site-packages\fastjsonschema\draft07.py
draft07.py
Python
4,449
0.95
0.181034
0.019417
python-kit
180
2023-09-27T14:38:45.218475
BSD-3-Clause
false
4ac9c69b4470838e45d82f6d398601a9
import re\n\n\nSPLIT_RE = re.compile(r'[\.\[\]]+')\n\n\nclass JsonSchemaException(ValueError):\n """\n Base exception of ``fastjsonschema`` library.\n """\n\n\nclass JsonSchemaValueException(JsonSchemaException):\n """\n Exception raised by validation function. Available properties:\n\n * ``message`` containing human-readable information what is wrong (e.g. ``data.property[index] must be smaller than or equal to 42``),\n * invalid ``value`` (e.g. ``60``),\n * ``name`` of a path in the data structure (e.g. ``data.property[index]``),\n * ``path`` as an array in the data structure (e.g. ``['data', 'property', 'index']``),\n * the whole ``definition`` which the ``value`` has to fulfil (e.g. ``{'type': 'number', 'maximum': 42}``),\n * ``rule`` which the ``value`` is breaking (e.g. ``maximum``)\n * and ``rule_definition`` (e.g. ``42``).\n\n .. versionchanged:: 2.14.0\n Added all extra properties.\n """\n\n def __init__(self, message, value=None, name=None, definition=None, rule=None):\n super().__init__(message)\n self.message = message\n self.value = value\n self.name = name\n self.definition = definition\n self.rule = rule\n\n @property\n def path(self):\n return [item for item in SPLIT_RE.split(self.name) if item != '']\n\n @property\n def rule_definition(self):\n if not self.rule or not self.definition:\n return None\n return self.definition.get(self.rule)\n\n\nclass JsonSchemaDefinitionException(JsonSchemaException):\n """\n Exception raised by generator of validation function.\n """\n
.venv\Lib\site-packages\fastjsonschema\exceptions.py
exceptions.py
Python
1,612
0.85
0.215686
0.184211
react-lib
75
2023-08-01T01:14:55.323292
Apache-2.0
false
d3e20b6be5b919a91f70ac1e9a363ac8
def indent(func):\n """\n Decorator for allowing to use method as normal method or with\n context manager for auto-indenting code blocks.\n """\n def wrapper(self, line, *args, optimize=True, **kwds):\n last_line = self._indent_last_line\n line = func(self, line, *args, **kwds)\n # When two blocks have the same condition (such as value has to be dict),\n # do the check only once and keep it under one block.\n if optimize and last_line == line:\n self._code.pop()\n self._indent_last_line = line\n return Indent(self, line)\n return wrapper\n\n\nclass Indent:\n def __init__(self, instance, line):\n self.instance = instance\n self.line = line\n\n def __enter__(self):\n self.instance._indent += 1\n\n def __exit__(self, type_, value, traceback):\n self.instance._indent -= 1\n self.instance._indent_last_line = self.line\n
.venv\Lib\site-packages\fastjsonschema\indent.py
indent.py
Python
920
0.95
0.321429
0.083333
node-utils
62
2024-07-07T11:46:53.713215
BSD-3-Clause
false
d7331ac5e83096566c39b107184d1141
"""\nJSON Schema URI resolution scopes and dereferencing\n\nhttps://tools.ietf.org/id/draft-zyp-json-schema-04.html#rfc.section.7\n\nCode adapted from https://github.com/Julian/jsonschema\n"""\n\nimport contextlib\nimport json\nimport re\nfrom urllib import parse as urlparse\nfrom urllib.parse import unquote\n\nfrom .exceptions import JsonSchemaDefinitionException\n\n\ndef get_id(schema):\n """\n Originally ID was `id` and since v7 it's `$id`.\n """\n return schema.get('$id', schema.get('id', ''))\n\n\ndef resolve_path(schema, fragment):\n """\n Return definition from path.\n\n Path is unescaped according https://tools.ietf.org/html/rfc6901\n """\n fragment = fragment.lstrip('/')\n parts = unquote(fragment).split('/') if fragment else []\n for part in parts:\n part = part.replace('~1', '/').replace('~0', '~')\n if isinstance(schema, list):\n schema = schema[int(part)]\n elif part in schema:\n schema = schema[part]\n else:\n raise JsonSchemaDefinitionException('Unresolvable ref: {}'.format(part))\n return schema\n\n\ndef normalize(uri):\n return urlparse.urlsplit(uri).geturl()\n\n\ndef resolve_remote(uri, handlers):\n """\n Resolve a remote ``uri``.\n\n .. note::\n\n urllib library is used to fetch requests from the remote ``uri``\n if handlers does notdefine otherwise.\n """\n scheme = urlparse.urlsplit(uri).scheme\n if scheme in handlers:\n result = handlers[scheme](uri)\n else:\n from urllib.request import urlopen\n\n req = urlopen(uri)\n encoding = req.info().get_content_charset() or 'utf-8'\n try:\n result = json.loads(req.read().decode(encoding),)\n except ValueError as exc:\n raise JsonSchemaDefinitionException('{} failed to decode: {}'.format(uri, exc))\n finally:\n req.close()\n return result\n\n\nclass RefResolver:\n """\n Resolve JSON References.\n """\n\n # pylint: disable=dangerous-default-value,too-many-arguments\n def __init__(self, base_uri, schema, store={}, cache=True, handlers={}):\n """\n `base_uri` is URI of the referring document from the `schema`.\n `store` is an dictionary that will be used to cache the fetched schemas\n (if `cache=True`).\n\n Please notice that you can have caching problems when compiling schemas\n with colliding `$ref`. To force overwriting use `cache=False` or\n explicitly pass the `store` argument (with a brand new dictionary)\n """\n self.base_uri = base_uri\n self.resolution_scope = base_uri\n self.schema = schema\n self.store = store\n self.cache = cache\n self.handlers = handlers\n self.walk(schema)\n\n @classmethod\n def from_schema(cls, schema, handlers={}, **kwargs):\n """\n Construct a resolver from a JSON schema object.\n """\n return cls(\n get_id(schema) if isinstance(schema, dict) else '',\n schema,\n handlers=handlers,\n **kwargs\n )\n\n @contextlib.contextmanager\n def in_scope(self, scope: str):\n """\n Context manager to handle current scope.\n """\n old_scope = self.resolution_scope\n self.resolution_scope = urlparse.urljoin(old_scope, scope)\n try:\n yield\n finally:\n self.resolution_scope = old_scope\n\n @contextlib.contextmanager\n def resolving(self, ref: str):\n """\n Context manager which resolves a JSON ``ref`` and enters the\n resolution scope of this ref.\n """\n new_uri = urlparse.urljoin(self.resolution_scope, ref)\n uri, fragment = urlparse.urldefrag(new_uri)\n\n if uri and normalize(uri) in self.store:\n schema = self.store[normalize(uri)]\n elif not uri or uri == self.base_uri:\n schema = self.schema\n else:\n schema = resolve_remote(uri, self.handlers)\n if self.cache:\n self.store[normalize(uri)] = schema\n\n old_base_uri, old_schema = self.base_uri, self.schema\n self.base_uri, self.schema = uri, schema\n try:\n with self.in_scope(uri):\n yield resolve_path(schema, fragment)\n finally:\n self.base_uri, self.schema = old_base_uri, old_schema\n\n def get_uri(self):\n return normalize(self.resolution_scope)\n\n def get_scope_name(self):\n """\n Get current scope and return it as a valid function name.\n """\n name = 'validate_' + unquote(self.resolution_scope).replace('~1', '_').replace('~0', '_').replace('"', '')\n name = re.sub(r'($[^a-zA-Z]|[^a-zA-Z0-9])', '_', name)\n name = name.lower().rstrip('_')\n return name\n\n def walk(self, node: dict):\n """\n Walk thru schema and dereferencing ``id`` and ``$ref`` instances\n """\n if isinstance(node, bool):\n pass\n elif '$ref' in node and isinstance(node['$ref'], str):\n ref = node['$ref']\n node['$ref'] = urlparse.urljoin(self.resolution_scope, ref)\n elif ('$id' in node or 'id' in node) and isinstance(get_id(node), str):\n with self.in_scope(get_id(node)):\n self.store[normalize(self.resolution_scope)] = node\n for _, item in node.items():\n if isinstance(item, dict):\n self.walk(item)\n else:\n for _, item in node.items():\n if isinstance(item, dict):\n self.walk(item)\n
.venv\Lib\site-packages\fastjsonschema\ref_resolver.py
ref_resolver.py
Python
5,577
0.95
0.168539
0.013333
vue-tools
843
2024-06-18T01:16:23.236881
GPL-3.0
false
d3c46f665f7160120771b865b5955f8d
VERSION = '2.21.1'\n
.venv\Lib\site-packages\fastjsonschema\version.py
version.py
Python
19
0.5
0
0
node-utils
164
2024-01-22T09:44:59.663083
BSD-3-Clause
false
07343de67ed3336910fec6e5be9ec6b2
import json\nimport sys\n\nfrom . import compile_to_code\n\n\ndef main():\n if len(sys.argv) == 2:\n definition = sys.argv[1]\n else:\n definition = sys.stdin.read()\n\n definition = json.loads(definition)\n code = compile_to_code(definition)\n print(code)\n\n\nif __name__ == '__main__':\n main()\n
.venv\Lib\site-packages\fastjsonschema\__main__.py
__main__.py
Python
312
0.85
0.157895
0
python-kit
736
2025-04-09T07:34:48.323225
BSD-3-Clause
false
bc6f1e3b6e5f185aa3b833b1fcee7e7f