signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def get_float_or_none(s: str) -> Optional[float]:
try:<EOL><INDENT>return float(s)<EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>return None<EOL><DEDENT>
Returns the float value of a string, or ``None`` if it's not convertible to a ``float``.
f14684:m2
def is_1(s: str) -> bool:
return True if s == "<STR_LIT:1>" else False<EOL>
``True`` if the input is the string literal ``"1"``, otherwise ``False``.
f14684:m3
def number_to_dp(number: Optional[float],<EOL>dp: int,<EOL>default: Optional[str] = "<STR_LIT>",<EOL>en_dash_for_minus: bool = True) -> str:
if number is None:<EOL><INDENT>return default<EOL><DEDENT>if number == float("<STR_LIT>"):<EOL><INDENT>return u"<STR_LIT>"<EOL><DEDENT>if number == float("<STR_LIT>"):<EOL><INDENT>s = u"<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>s = u"<STR_LIT>".format(number, precision=dp)<EOL><DEDENT>if en_dash_for_minus:<EOL><INDENT>s = s.replace("<STR_LIT:->", u"<STR_LIT>") <EOL><DEDENT>return s<EOL>
Format number to ``dp`` decimal places, optionally using a UTF-8 en dash for minus signs.
f14684:m4
def debug_form_contents(form: cgi.FieldStorage,<EOL>to_stderr: bool = True,<EOL>to_logger: bool = False) -> None:
for k in form.keys():<EOL><INDENT>text = "<STR_LIT>".format(k, form.getvalue(k))<EOL>if to_stderr:<EOL><INDENT>sys.stderr.write(text)<EOL><DEDENT>if to_logger:<EOL><INDENT>log.info(text)<EOL><DEDENT><DEDENT>
Writes the keys and values of a CGI form to ``stderr``.
f14684:m5
def cgi_method_is_post(environ: Dict[str, str]) -> bool:
method = environ.get("<STR_LIT>", None)<EOL>if not method:<EOL><INDENT>return False<EOL><DEDENT>return method.upper() == "<STR_LIT:POST>"<EOL>
Determines if the CGI method was ``POST``, given the CGI environment.
f14684:m6
def get_cgi_parameter_str(form: cgi.FieldStorage,<EOL>key: str,<EOL>default: str = None) -> str:
paramlist = form.getlist(key)<EOL>if len(paramlist) == <NUM_LIT:0>:<EOL><INDENT>return default<EOL><DEDENT>return paramlist[<NUM_LIT:0>]<EOL>
Extracts a string parameter from a CGI form. Note: ``key`` is CASE-SENSITIVE.
f14684:m7
def get_cgi_parameter_str_or_none(form: cgi.FieldStorage,<EOL>key: str) -> Optional[str]:
s = get_cgi_parameter_str(form, key)<EOL>if s is None or len(s) == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>return s<EOL>
Extracts a string parameter from a CGI form, or ``None`` if the key doesn't exist or the string is zero-length.
f14684:m8
def get_cgi_parameter_list(form: cgi.FieldStorage, key: str) -> List[str]:
return form.getlist(key)<EOL>
Extracts a list of values, all with the same key, from a CGI form.
f14684:m9
def get_cgi_parameter_bool(form: cgi.FieldStorage, key: str) -> bool:
return is_1(get_cgi_parameter_str(form, key))<EOL>
Extracts a boolean parameter from a CGI form, on the assumption that ``"1"`` is ``True`` and everything else is ``False``.
f14684:m10
def get_cgi_parameter_bool_or_default(form: cgi.FieldStorage,<EOL>key: str,<EOL>default: bool = None) -> Optional[bool]:
s = get_cgi_parameter_str(form, key)<EOL>if s is None or len(s) == <NUM_LIT:0>:<EOL><INDENT>return default<EOL><DEDENT>return is_1(s)<EOL>
Extracts a boolean parameter from a CGI form (``"1"`` = ``True``, other string = ``False``, absent/zero-length string = default value).
f14684:m11
def get_cgi_parameter_bool_or_none(form: cgi.FieldStorage,<EOL>key: str) -> Optional[bool]:
return get_cgi_parameter_bool_or_default(form, key, default=None)<EOL>
Extracts a boolean parameter from a CGI form (``"1"`` = ``True``, other string = False, absent/zero-length string = ``None``).
f14684:m12
def get_cgi_parameter_int(form: cgi.FieldStorage, key: str) -> Optional[int]:
return get_int_or_none(get_cgi_parameter_str(form, key))<EOL>
Extracts an integer parameter from a CGI form, or ``None`` if the key is absent or the string value is not convertible to ``int``.
f14684:m13
def get_cgi_parameter_float(form: cgi.FieldStorage,<EOL>key: str) -> Optional[float]:
return get_float_or_none(get_cgi_parameter_str(form, key))<EOL>
Extracts a float parameter from a CGI form, or None if the key is absent or the string value is not convertible to ``float``.
f14684:m14
def get_cgi_parameter_datetime(form: cgi.FieldStorage,<EOL>key: str) -> Optional[datetime.datetime]:
try:<EOL><INDENT>s = get_cgi_parameter_str(form, key)<EOL>if not s:<EOL><INDENT>return None<EOL><DEDENT>d = dateutil.parser.parse(s)<EOL>if d.tzinfo is None: <EOL><INDENT>d = d.replace(tzinfo=dateutil.tz.tzlocal())<EOL><DEDENT>return d<EOL><DEDENT>except ValueError:<EOL><INDENT>return None<EOL><DEDENT>
Extracts a date/time parameter from a CGI form. Applies the LOCAL timezone if none specified.
f14684:m15
def get_cgi_parameter_file(form: cgi.FieldStorage,<EOL>key: str) -> Optional[bytes]:
(filename, filecontents) = get_cgi_parameter_filename_and_file(form, key)<EOL>return filecontents<EOL>
Extracts a file's contents from a "file" input in a CGI form, or None if no such file was uploaded.
f14684:m16
def get_cgi_parameter_filename_and_file(form: cgi.FieldStorage, key: str)-> Tuple[Optional[str], Optional[bytes]]:
if not (key in form):<EOL><INDENT>log.warning('<STR_LIT>', key)<EOL>return None, None<EOL><DEDENT>fileitem = form[key] <EOL>if isinstance(fileitem, cgi.MiniFieldStorage):<EOL><INDENT>log.warning('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>return None, None<EOL><DEDENT>if not isinstance(fileitem, cgi.FieldStorage):<EOL><INDENT>log.warning('<STR_LIT>'<EOL>'<STR_LIT>', key)<EOL>return None, None<EOL><DEDENT>if fileitem.filename and fileitem.file: <EOL><INDENT>return fileitem.filename, fileitem.file.read()<EOL><DEDENT>if not fileitem.file:<EOL><INDENT>log.warning('<STR_LIT>')<EOL><DEDENT>elif not fileitem.filename:<EOL><INDENT>log.warning('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>log.warning('<STR_LIT>')<EOL><DEDENT>return None, None<EOL>
Extracts a file's name and contents from a "file" input in a CGI form. Returns ``(name, contents)``, or ``(None, None)`` if no such file was uploaded.
f14684:m17
def cgi_parameter_exists(form: cgi.FieldStorage, key: str) -> bool:
s = get_cgi_parameter_str(form, key)<EOL>return s is not None<EOL>
Does a CGI form contain the key?
f14684:m18
def checkbox_checked(b: Any) -> str:
return '<STR_LIT>' if b else '<STR_LIT>'<EOL>
Returns ``' checked="checked"'`` if ``b`` is true; otherwise ``''``. Use this code to fill the ``{}`` in e.g.: .. code-block:: none <label> <input type="checkbox" name="myfield" value="1"{}> This will be pre-ticked if you insert " checked" where the braces are. The newer, more stringent requirement is ' checked="checked"'. </label>
f14684:m19
def getenv_escaped(key: str, default: str = None) -> Optional[str]:
value = os.getenv(key, default)<EOL>return cgi.escape(value) if value is not None else None<EOL>
Returns an environment variable's value, CGI-escaped, or ``None``.
f14684:m21
def getconfigvar_escaped(config: configparser.ConfigParser,<EOL>section: str,<EOL>key: str) -> Optional[str]:
value = config.get(section, key)<EOL>return cgi.escape(value) if value is not None else None<EOL>
Returns a CGI-escaped version of the value read from an INI file using :class:`ConfigParser`, or ``None``.
f14684:m22
def get_cgi_fieldstorage_from_wsgi_env(<EOL>env: Dict[str, str],<EOL>include_query_string: bool = True) -> cgi.FieldStorage:
<EOL>post_env = env.copy()<EOL>if not include_query_string:<EOL><INDENT>post_env['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>form = cgi.FieldStorage(<EOL>fp=env['<STR_LIT>'],<EOL>environ=post_env,<EOL>keep_blank_values=True<EOL>)<EOL>return form<EOL>
Returns a :class:`cgi.FieldStorage` object from the WSGI environment.
f14684:m23
def is_valid_png(blob: Optional[bytes]) -> bool:
if not blob:<EOL><INDENT>return False<EOL><DEDENT>return blob[:<NUM_LIT:8>] == PNG_SIGNATURE_HEX<EOL>
Does a blob have a valid PNG signature?
f14684:m24
def get_png_data_url(blob: Optional[bytes]) -> str:
return BASE64_PNG_URL_PREFIX + base64.b64encode(blob).decode('<STR_LIT:ascii>')<EOL>
Converts a PNG blob into a local URL encapsulating the PNG.
f14684:m25
def get_png_img_html(blob: Union[bytes, memoryview],<EOL>extra_html_class: str = None) -> str:
return """<STR_LIT>""".format(<EOL>'<STR_LIT>'.format(extra_html_class) if extra_html_class else "<STR_LIT>",<EOL>get_png_data_url(blob)<EOL>)<EOL>
Converts a PNG blob to an HTML IMG tag with embedded data.
f14684:m26
def pdf_result(pdf_binary: bytes,<EOL>extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None,<EOL>filename: str = None) -> WSGI_TUPLE_TYPE:
extraheaders = extraheaders or []<EOL>if filename:<EOL><INDENT>extraheaders.append(<EOL>('<STR_LIT>', '<STR_LIT>'.format(filename))<EOL>)<EOL><DEDENT>contenttype = '<STR_LIT>'<EOL>if filename:<EOL><INDENT>contenttype += '<STR_LIT>'.format(filename)<EOL><DEDENT>return contenttype, extraheaders, pdf_binary<EOL>
Returns ``(contenttype, extraheaders, data)`` tuple for a PDF.
f14684:m27
def zip_result(zip_binary: bytes,<EOL>extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None,<EOL>filename: str = None) -> WSGI_TUPLE_TYPE:
extraheaders = extraheaders or []<EOL>if filename:<EOL><INDENT>extraheaders.append(<EOL>('<STR_LIT>', '<STR_LIT>'.format(filename))<EOL>)<EOL><DEDENT>contenttype = '<STR_LIT>'<EOL>if filename:<EOL><INDENT>contenttype += '<STR_LIT>'.format(filename)<EOL><DEDENT>return contenttype, extraheaders, zip_binary<EOL>
Returns ``(contenttype, extraheaders, data)`` tuple for a ZIP.
f14684:m28
def html_result(html: str,<EOL>extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None)-> WSGI_TUPLE_TYPE:
extraheaders = extraheaders or []<EOL>return '<STR_LIT>', extraheaders, html.encode("<STR_LIT:utf-8>")<EOL>
Returns ``(contenttype, extraheaders, data)`` tuple for UTF-8 HTML.
f14684:m29
def xml_result(xml: str,<EOL>extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None)-> WSGI_TUPLE_TYPE:
extraheaders = extraheaders or []<EOL>return '<STR_LIT>', extraheaders, xml.encode("<STR_LIT:utf-8>")<EOL>
Returns ``(contenttype, extraheaders, data)`` tuple for UTF-8 XML.
f14684:m30
def text_result(text: str,<EOL>extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None,<EOL>filename: str = None) -> WSGI_TUPLE_TYPE:
extraheaders = extraheaders or []<EOL>if filename:<EOL><INDENT>extraheaders.append(<EOL>('<STR_LIT>', '<STR_LIT>'.format(filename))<EOL>)<EOL><DEDENT>contenttype = '<STR_LIT>'<EOL>if filename:<EOL><INDENT>contenttype += '<STR_LIT>'.format(filename)<EOL><DEDENT>return contenttype, extraheaders, text.encode("<STR_LIT:utf-8>")<EOL>
Returns ``(contenttype, extraheaders, data)`` tuple for UTF-8 text.
f14684:m31
def tsv_result(text: str,<EOL>extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None,<EOL>filename: str = None) -> WSGI_TUPLE_TYPE:
extraheaders = extraheaders or []<EOL>if filename:<EOL><INDENT>extraheaders.append(<EOL>('<STR_LIT>', '<STR_LIT>'.format(filename))<EOL>)<EOL><DEDENT>contenttype = '<STR_LIT>'<EOL>if filename:<EOL><INDENT>contenttype += '<STR_LIT>'.format(filename)<EOL><DEDENT>return contenttype, extraheaders, text.encode("<STR_LIT:utf-8>")<EOL>
Returns ``(contenttype, extraheaders, data)`` tuple for UTF-8 TSV.
f14684:m32
def print_result_for_plain_cgi_script_from_tuple(<EOL>contenttype_headers_content: WSGI_TUPLE_TYPE,<EOL>status: str = '<STR_LIT>') -> None:
contenttype, headers, content = contenttype_headers_content<EOL>print_result_for_plain_cgi_script(contenttype, headers, content, status)<EOL>
Writes HTTP result to stdout. Args: contenttype_headers_content: the tuple ``(contenttype, extraheaders, data)`` status: HTTP status message (default ``"200 OK``)
f14684:m33
def print_result_for_plain_cgi_script(contenttype: str,<EOL>headers: TYPE_WSGI_RESPONSE_HEADERS,<EOL>content: bytes,<EOL>status: str = '<STR_LIT>') -> None:
headers = [<EOL>("<STR_LIT>", status),<EOL>("<STR_LIT:Content-Type>", contenttype),<EOL>("<STR_LIT>", str(len(content))),<EOL>] + headers<EOL>sys.stdout.write("<STR_LIT:\n>".join([h[<NUM_LIT:0>] + "<STR_LIT>" + h[<NUM_LIT:1>] for h in headers]) + "<STR_LIT>")<EOL>sys.stdout.write(content)<EOL>
Writes HTTP request result to stdout.
f14684:m34
def wsgi_simple_responder(<EOL>result: Union[str, bytes],<EOL>handler: Callable[[Union[str, bytes]], WSGI_TUPLE_TYPE],<EOL>start_response: TYPE_WSGI_START_RESPONSE,<EOL>status: str = '<STR_LIT>',<EOL>extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None)-> TYPE_WSGI_APP_RESULT:
extraheaders = extraheaders or []<EOL>(contenttype, extraheaders2, output) = handler(result)<EOL>response_headers = [('<STR_LIT:Content-Type>', contenttype),<EOL>('<STR_LIT>', str(len(output)))]<EOL>response_headers.extend(extraheaders)<EOL>if extraheaders2 is not None:<EOL><INDENT>response_headers.extend(extraheaders2)<EOL><DEDENT>start_response(status, response_headers)<EOL>return [output]<EOL>
Simple WSGI app. Args: result: the data to be processed by ``handler`` handler: a function returning a ``(contenttype, extraheaders, data)`` tuple, e.g. ``text_result``, ``html_result`` start_response: standard WSGI ``start_response`` function status: status code (default ``"200 OK"``) extraheaders: optional extra HTTP headers Returns: WSGI application result
f14684:m35
def webify(v: Any, preserve_newlines: bool = True) -> str:
nl = "<STR_LIT>" if preserve_newlines else "<STR_LIT:U+0020>"<EOL>if v is None:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>if not isinstance(v, str):<EOL><INDENT>v = str(v)<EOL><DEDENT>return cgi.escape(v).replace("<STR_LIT:\n>", nl).replace("<STR_LIT>", nl)<EOL>
Converts a value into an HTML-safe ``str`` (formerly, in Python 2: ``unicode``). Converts value ``v`` to a string; escapes it to be safe in HTML format (escaping ampersands, replacing newlines with ``<br>``, etc.). Returns ``""`` for blank input.
f14684:m36
def websafe(value: str) -> str:
<EOL>return cgi.escape(value).encode('<STR_LIT:ascii>', '<STR_LIT>')<EOL>
Makes a string safe for inclusion in ASCII-encoded HTML.
f14684:m37
def replace_nl_with_html_br(string: str) -> str:
return _NEWLINE_REGEX.sub("<STR_LIT>", string)<EOL>
Replaces newlines with ``<br>``.
f14684:m38
def bold_if_not_blank(x: Optional[str]) -> str:
if x is None:<EOL><INDENT>return u"<STR_LIT:{}>".format(x)<EOL><DEDENT>return u"<STR_LIT>".format(x)<EOL>
HTML-emboldens content, unless blank.
f14684:m39
def make_urls_hyperlinks(text: str) -> str:
find_url = r'''<STR_LIT>'''<EOL>replace_url = r'<STR_LIT>'<EOL>find_email = re.compile(r'<STR_LIT>')<EOL>replace_email = r'<STR_LIT>'<EOL>text = re.sub(find_url, replace_url, text)<EOL>text = re.sub(find_email, replace_email, text)<EOL>return text<EOL>
Adds hyperlinks to text that appears to contain URLs. See - http://stackoverflow.com/questions/1071191 - ... except that double-replaces everything; e.g. try with ``text = "me@somewhere.com me@somewhere.com"`` - http://stackp.online.fr/?p=19
f14684:m40
def html_table_from_query(rows: Iterable[Iterable[Optional[str]]],<EOL>descriptions: Iterable[Optional[str]]) -> str:
html = u"<STR_LIT>"<EOL>html += u"<STR_LIT>"<EOL>for x in descriptions:<EOL><INDENT>if x is None:<EOL><INDENT>x = u"<STR_LIT>"<EOL><DEDENT>html += u"<STR_LIT>".format(webify(x))<EOL><DEDENT>html += u"<STR_LIT>"<EOL>for row in rows:<EOL><INDENT>html += u"<STR_LIT>"<EOL>for x in row:<EOL><INDENT>if x is None:<EOL><INDENT>x = u"<STR_LIT>"<EOL><DEDENT>html += u"<STR_LIT>".format(webify(x))<EOL><DEDENT>html += u"<STR_LIT>"<EOL><DEDENT>html += u"<STR_LIT>"<EOL>return html<EOL>
Converts rows from an SQL query result to an HTML table. Suitable for processing output from the defunct function ``rnc_db.fetchall_with_fieldnames(sql)``.
f14684:m41
def ping(hostname: str, timeout_s: int = <NUM_LIT:5>) -> bool:
if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>timeout_ms = timeout_s * <NUM_LIT:1000><EOL>args = [<EOL>"<STR_LIT>",<EOL>hostname,<EOL>"<STR_LIT>", "<STR_LIT:1>", <EOL>"<STR_LIT>", str(timeout_ms), <EOL>]<EOL><DEDENT>elif sys.platform.startswith('<STR_LIT>'):<EOL><INDENT>args = [<EOL>"<STR_LIT>",<EOL>hostname,<EOL>"<STR_LIT:-c>", "<STR_LIT:1>", <EOL>"<STR_LIT>", str(timeout_s), <EOL>]<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>proc = subprocess.Popen(args,<EOL>stdout=subprocess.PIPE, stderr=subprocess.PIPE)<EOL>proc.communicate()<EOL>retcode = proc.returncode<EOL>return retcode == <NUM_LIT:0><EOL>
Pings a host, using OS tools. Args: hostname: host name or IP address timeout_s: timeout in seconds Returns: was the ping successful?
f14685:m0
def download(url: str, filename: str,<EOL>skip_cert_verify: bool = True) -> None:
log.info("<STR_LIT>", url, filename)<EOL>ctx = ssl.create_default_context() <EOL>if skip_cert_verify:<EOL><INDENT>log.debug("<STR_LIT>" + url)<EOL>ctx.check_hostname = False<EOL>ctx.verify_mode = ssl.CERT_NONE<EOL><DEDENT>with urllib.request.urlopen(url, context=ctx) as u, open(filename,<EOL>'<STR_LIT:wb>') as f: <EOL><INDENT>f.write(u.read())<EOL><DEDENT>
Downloads a URL to a file. Args: url: URL to download from filename: file to save to skip_cert_verify: skip SSL certificate check?
f14685:m1
def gen_binary_files_from_urls(<EOL>urls: Iterable[str],<EOL>on_disk: bool = False,<EOL>show_info: bool = True) -> Generator[BinaryIO, None, None]:
for url in urls:<EOL><INDENT>if on_disk:<EOL><INDENT>with tempfile.TemporaryDirectory() as tmpdir:<EOL><INDENT>filename = os.path.join(tmpdir, "<STR_LIT>")<EOL>download(url=url, filename=filename)<EOL>with open(filename, '<STR_LIT:rb>') as f:<EOL><INDENT>yield f<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if show_info:<EOL><INDENT>log.info("<STR_LIT>", url)<EOL><DEDENT>with urllib.request.urlopen(url) as f:<EOL><INDENT>yield f<EOL><DEDENT><DEDENT>if show_info:<EOL><INDENT>log.info("<STR_LIT>", url)<EOL><DEDENT><DEDENT>
Generate binary files from a series of URLs (one per URL). Args: urls: iterable of URLs on_disk: if ``True``, yields files that are on disk (permitting random access); if ``False``, yields in-memory files (which will not permit random access) show_info: show progress to the log? Yields: files, each of type :class:`BinaryIO`
f14685:m2
def args_kwargs_to_initdict(args: ArgsList, kwargs: KwargsDict) -> InitDict:
return {ARGS_LABEL: args,<EOL>KWARGS_LABEL: kwargs}<EOL>
Converts a set of ``args`` and ``kwargs`` to an ``InitDict``.
f14687:m0
def kwargs_to_initdict(kwargs: KwargsDict) -> InitDict:
return {ARGS_LABEL: [],<EOL>KWARGS_LABEL: kwargs}<EOL>
Converts a set of ``kwargs`` to an ``InitDict``.
f14687:m1
def obj_with_no_args_to_init_dict(obj: Any) -> InitDict:
return {ARGS_LABEL: [],<EOL>KWARGS_LABEL: {}}<EOL>
Creates an empty ``InitDict``, for use with an object that takes no arguments at creation.
f14687:m2
def strip_leading_underscores_from_keys(d: Dict) -> Dict:
newdict = {}<EOL>for k, v in d.items():<EOL><INDENT>if k.startswith('<STR_LIT:_>'):<EOL><INDENT>k = k[<NUM_LIT:1>:]<EOL>if k in newdict:<EOL><INDENT>raise ValueError("<STR_LIT>".format(k=k))<EOL><DEDENT><DEDENT>newdict[k] = v<EOL><DEDENT>return newdict<EOL>
Clones a dictionary, removing leading underscores from key names. Raises ``ValueError`` if this causes an attribute conflict.
f14687:m3
def verify_initdict(initdict: InitDict) -> None:
if (not isinstance(initdict, dict) or<EOL>ARGS_LABEL not in initdict or<EOL>KWARGS_LABEL not in initdict):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>
Ensures that its parameter is a proper ``InitDict``, or raises ``ValueError``.
f14687:m4
def initdict_to_instance(d: InitDict, cls: ClassType) -> Any:
args = d.get(ARGS_LABEL, [])<EOL>kwargs = d.get(KWARGS_LABEL, {})<EOL>return cls(*args, **kwargs)<EOL>
Converse of simple_to_dict(). Given that JSON dictionary, we will end up re-instantiating the class with .. code-block:: python d = {'a': 1, 'b': 2, 'c': 3} new_x = SimpleClass(**d) We'll also support arbitrary creation, by using both ``*args`` and ``**kwargs``.
f14687:m5
def instance_to_initdict_simple(obj: Any) -> InitDict:
return kwargs_to_initdict(obj.__dict__)<EOL>
For use when object attributes (found in ``obj.__dict__``) should be mapped directly to the serialized JSON dictionary. Typically used for classes like: .. code-block:: python class SimpleClass(object): def __init__(self, a, b, c): self.a = a self.b = b self.c = c Here, after x = SimpleClass(a=1, b=2, c=3) we will find that x.__dict__ == {'a': 1, 'b': 2, 'c': 3} and that dictionary is a reasonable thing to serialize to JSON as keyword arguments. We'll also support arbitrary creation, by using both ``*args`` and ``**kwargs``. We may not use this format much, but it has the advantage of being an arbitrarily correct format for Python class construction.
f14687:m6
def instance_to_initdict_stripping_underscores(obj: Instance) -> InitDict:
return kwargs_to_initdict(<EOL>strip_leading_underscores_from_keys(obj.__dict__))<EOL>
This is appropriate when a class uses a ``'_'`` prefix for all its ``__init__`` parameters, like this: .. code-block:: python class UnderscoreClass(object): def __init__(self, a, b, c): self._a = a self._b = b self._c = c Here, after .. code-block:: python y = UnderscoreClass(a=1, b=2, c=3) we will find that .. code-block:: python y.__dict__ == {'_a': 1, '_b': 2, '_c': 3} but we would like to serialize the parameters we can pass back to ``__init__``, by removing the leading underscores, like this: .. code-block:: python {'a': 1, 'b': 2, 'c': 3}
f14687:m7
def wrap_kwargs_to_initdict(init_kwargs_fn: InitKwargsFnType,<EOL>typename: str,<EOL>check_result: bool = True)-> InstanceToInitDictFnType:
def wrapper(obj: Instance) -> InitDict:<EOL><INDENT>result = init_kwargs_fn(obj)<EOL>if check_result:<EOL><INDENT>if not isinstance(result, dict):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(typename, repr(result)))<EOL><DEDENT><DEDENT>return kwargs_to_initdict(init_kwargs_fn(obj))<EOL><DEDENT>return wrapper<EOL>
Wraps a function producing a ``KwargsDict``, making it into a function producing an ``InitDict``.
f14687:m8
def wrap_args_kwargs_to_initdict(init_args_kwargs_fn: InitArgsKwargsFnType,<EOL>typename: str,<EOL>check_result: bool = True)-> InstanceToInitDictFnType:
def wrapper(obj: Instance) -> InitDict:<EOL><INDENT>result = init_args_kwargs_fn(obj)<EOL>if check_result:<EOL><INDENT>if (not isinstance(result, tuple) or<EOL>not len(result) == <NUM_LIT:2> or<EOL>not isinstance(result[<NUM_LIT:0>], list) or<EOL>not isinstance(result[<NUM_LIT:1>], dict)):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(typename, repr(result)))<EOL><DEDENT><DEDENT>return args_kwargs_to_initdict(*result)<EOL><DEDENT>return wrapper<EOL>
Wraps a function producing a ``KwargsDict``, making it into a function producing an ``InitDict``.
f14687:m9
def make_instance_to_initdict(attributes: List[str]) -> InstanceToDictFnType:
def custom_instance_to_initdict(x: Instance) -> InitDict:<EOL><INDENT>kwargs = {}<EOL>for a in attributes:<EOL><INDENT>kwargs[a] = getattr(x, a)<EOL><DEDENT>return kwargs_to_initdict(kwargs)<EOL><DEDENT>return custom_instance_to_initdict<EOL>
Returns a function that takes an object (instance) and produces an ``InitDict`` enabling its re-creation.
f14687:m10
def register_class_for_json(<EOL>cls: ClassType,<EOL>method: str = METHOD_SIMPLE,<EOL>obj_to_dict_fn: InstanceToDictFnType = None,<EOL>dict_to_obj_fn: DictToInstanceFnType = initdict_to_instance,<EOL>default_factory: DefaultFactoryFnType = None) -> None:
typename = cls.__qualname__ <EOL>if obj_to_dict_fn and dict_to_obj_fn:<EOL><INDENT>descriptor = JsonDescriptor(<EOL>typename=typename,<EOL>obj_to_dict_fn=obj_to_dict_fn,<EOL>dict_to_obj_fn=dict_to_obj_fn,<EOL>cls=cls,<EOL>default_factory=default_factory)<EOL><DEDENT>elif method == METHOD_SIMPLE:<EOL><INDENT>descriptor = JsonDescriptor(<EOL>typename=typename,<EOL>obj_to_dict_fn=instance_to_initdict_simple,<EOL>dict_to_obj_fn=initdict_to_instance,<EOL>cls=cls,<EOL>default_factory=default_factory)<EOL><DEDENT>elif method == METHOD_STRIP_UNDERSCORE:<EOL><INDENT>descriptor = JsonDescriptor(<EOL>typename=typename,<EOL>obj_to_dict_fn=instance_to_initdict_stripping_underscores,<EOL>dict_to_obj_fn=initdict_to_instance,<EOL>cls=cls,<EOL>default_factory=default_factory)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>global TYPE_MAP<EOL>TYPE_MAP[typename] = descriptor<EOL>
Registers the class cls for JSON serialization. - If both ``obj_to_dict_fn`` and dict_to_obj_fn are registered, the framework uses these to convert instances of the class to/from Python dictionaries, which are in turn serialized to JSON. - Otherwise: .. code-block:: python if method == 'simple': # ... uses simple_to_dict and simple_from_dict (q.v.) if method == 'strip_underscore': # ... uses strip_underscore_to_dict and simple_from_dict (q.v.)
f14687:m11
def register_for_json(*args, **kwargs) -> Any:
if DEBUG:<EOL><INDENT>print("<STR_LIT>".format(repr(args)))<EOL>print("<STR_LIT>".format(repr(kwargs)))<EOL><DEDENT>if len(args) == <NUM_LIT:1> and len(kwargs) == <NUM_LIT:0> and callable(args[<NUM_LIT:0>]):<EOL><INDENT>if DEBUG:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>cls = args[<NUM_LIT:0>] <EOL>register_class_for_json(cls, method=METHOD_SIMPLE)<EOL>return cls<EOL><DEDENT>if DEBUG:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>method = kwargs.pop('<STR_LIT>', METHOD_SIMPLE) <EOL>obj_to_dict_fn = kwargs.pop('<STR_LIT>', None) <EOL>dict_to_obj_fn = kwargs.pop('<STR_LIT>', initdict_to_instance) <EOL>default_factory = kwargs.pop('<STR_LIT>', None) <EOL>check_result = kwargs.pop('<STR_LIT>', True) <EOL>def register_json_class(cls_: ClassType) -> ClassType:<EOL><INDENT>odf = obj_to_dict_fn<EOL>dof = dict_to_obj_fn<EOL>if method == METHOD_PROVIDES_INIT_ARGS_KWARGS:<EOL><INDENT>if hasattr(cls_, INIT_ARGS_KWARGS_FN_NAME):<EOL><INDENT>odf = wrap_args_kwargs_to_initdict(<EOL>getattr(cls_, INIT_ARGS_KWARGS_FN_NAME),<EOL>typename=cls_.__qualname__,<EOL>check_result=check_result<EOL>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>".format(<EOL>cls_, INIT_ARGS_KWARGS_FN_NAME))<EOL><DEDENT><DEDENT>elif method == METHOD_PROVIDES_INIT_KWARGS:<EOL><INDENT>if hasattr(cls_, INIT_KWARGS_FN_NAME):<EOL><INDENT>odf = wrap_kwargs_to_initdict(<EOL>getattr(cls_, INIT_KWARGS_FN_NAME),<EOL>typename=cls_.__qualname__,<EOL>check_result=check_result<EOL>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>".format(<EOL>cls_, INIT_KWARGS_FN_NAME))<EOL><DEDENT><DEDENT>elif method == METHOD_NO_ARGS:<EOL><INDENT>odf = obj_with_no_args_to_init_dict<EOL><DEDENT>register_class_for_json(cls_,<EOL>method=method,<EOL>obj_to_dict_fn=odf,<EOL>dict_to_obj_fn=dof,<EOL>default_factory=default_factory)<EOL>return cls_<EOL><DEDENT>return register_json_class<EOL>
Class decorator to register classes with our JSON system. - If method is ``'provides_init_args_kwargs'``, the class provides a function .. code-block:: python def init_args_kwargs(self) -> Tuple[List[Any], Dict[str, Any]] that returns an ``(args, kwargs)`` tuple, suitable for passing to its ``__init__()`` function as ``__init__(*args, **kwargs)``. - If method is ``'provides_init_kwargs'``, the class provides a function .. code-block:: python def init_kwargs(self) -> Dict that returns a dictionary ``kwargs`` suitable for passing to its ``__init__()`` function as ``__init__(**kwargs)``. - Otherwise, the method argument is as for ``register_class_for_json()``. Usage looks like: .. code-block:: python @register_for_json(method=METHOD_STRIP_UNDERSCORE) class TableId(object): def __init__(self, db: str = '', schema: str = '', table: str = '') -> None: self._db = db self._schema = schema self._table = table
f14687:m12
def dump_map(file: TextIO = sys.stdout) -> None:
pp = pprint.PrettyPrinter(indent=<NUM_LIT:4>, stream=file)<EOL>print("<STR_LIT>", file=file)<EOL>pp.pprint(TYPE_MAP)<EOL>
Prints the JSON "registered types" map to the specified file.
f14687:m13
def json_class_decoder_hook(d: Dict) -> Any:
if TYPE_LABEL in d:<EOL><INDENT>typename = d.get(TYPE_LABEL)<EOL>if typename in TYPE_MAP:<EOL><INDENT>if DEBUG:<EOL><INDENT>log.debug("<STR_LIT>", d)<EOL><DEDENT>d.pop(TYPE_LABEL)<EOL>descriptor = TYPE_MAP[typename]<EOL>obj = descriptor.to_obj(d)<EOL>if DEBUG:<EOL><INDENT>log.debug("<STR_LIT>", obj)<EOL><DEDENT>return obj<EOL><DEDENT><DEDENT>return d<EOL>
Provides a JSON decoder that converts dictionaries to Python objects if suitable methods are found in our ``TYPE_MAP``.
f14687:m14
def json_encode(obj: Instance, **kwargs) -> str:
return json.dumps(obj, cls=JsonClassEncoder, **kwargs)<EOL>
Encodes an object to JSON using our custom encoder. The ``**kwargs`` can be used to pass things like ``'indent'``, for formatting.
f14687:m15
def json_decode(s: str) -> Any:
try:<EOL><INDENT>return json.JSONDecoder(object_hook=json_class_decoder_hook).decode(s)<EOL><DEDENT>except json.JSONDecodeError:<EOL><INDENT>log.warning("<STR_LIT>", s)<EOL>return None<EOL><DEDENT>
Decodes an object from JSON using our custom decoder.
f14687:m16
def enum_to_dict_fn(e: Enum) -> Dict[str, Any]:
return {<EOL>'<STR_LIT:name>': e.name<EOL>}<EOL>
Converts an ``Enum`` to a ``dict``.
f14687:m17
def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum:
return enum_class[d['<STR_LIT:name>']]<EOL>
Converts an ``dict`` to a ``Enum``.
f14687:m18
def register_enum_for_json(*args, **kwargs) -> Any:
if len(args) == <NUM_LIT:1> and len(kwargs) == <NUM_LIT:0> and callable(args[<NUM_LIT:0>]):<EOL><INDENT>cls = args[<NUM_LIT:0>] <EOL>register_class_for_json(<EOL>cls,<EOL>obj_to_dict_fn=enum_to_dict_fn,<EOL>dict_to_obj_fn=dict_to_enum_fn<EOL>)<EOL>return cls<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>
Class decorator to register ``Enum``-derived classes with our JSON system. See comments/help for ``@register_for_json``, above.
f14687:m19
def pendulum_to_dict(p: DateTime) -> Dict[str, Any]:
return {<EOL>'<STR_LIT>': str(p)<EOL>}<EOL>
Converts a ``Pendulum`` or ``datetime`` object to a ``dict``.
f14687:m20
def dict_to_pendulum(d: Dict[str, Any],<EOL>pendulum_class: ClassType) -> DateTime:
return pendulum.parse(d['<STR_LIT>'])<EOL>
Converts a ``dict`` object back to a ``Pendulum``.
f14687:m21
def pendulumdate_to_dict(p: Date) -> Dict[str, Any]:
return {<EOL>'<STR_LIT>': str(p)<EOL>}<EOL>
Converts a ``pendulum.Date`` object to a ``dict``.
f14687:m22
def dict_to_pendulumdate(d: Dict[str, Any],<EOL>pendulumdate_class: ClassType) -> Date:
<EOL>return pendulum.parse(d['<STR_LIT>']).date()<EOL>
Converts a ``dict`` object back to a ``pendulum.Date``.
f14687:m23
def simple_eq(one: Instance, two: Instance, attrs: List[str]) -> bool:
return all(getattr(one, a) == getattr(two, a) for a in attrs)<EOL>
Test if two objects are equal, based on a comparison of the specified attributes ``attrs``.
f14687:m24
def add_info_to_exception(err: Exception, info: Dict) -> None:
<EOL>t err.args:<EOL>rr.args = ('<STR_LIT>', )<EOL>rgs += (info, )<EOL>
Adds an information dictionary to an exception. See http://stackoverflow.com/questions/9157210/how-do-i-raise-the-same-exception-with-a-custom-message-in-python Args: err: the exception to be modified info: the information to add
f14689:m0
def recover_info_from_exception(err: Exception) -> Dict:
if len(err.args) < <NUM_LIT:1>:<EOL><INDENT>return {}<EOL><DEDENT>info = err.args[-<NUM_LIT:1>]<EOL>if not isinstance(info, dict):<EOL><INDENT>return {}<EOL><DEDENT>return info<EOL>
Retrives the information added to an exception by :func:`add_info_to_exception`.
f14689:m1
def die(exc: Exception = None, exit_code: int = <NUM_LIT:1>) -> None:
<EOL>c:<EOL>ines = traceback.format_exception(<EOL>None, <EOL>exc,<EOL>exc.__traceback__) <EOL>sg = "<STR_LIT>".join(lines)<EOL><INDENT>Method <NUM_LIT:1>:<EOL>print("<STR_LIT>".join(lines), file=sys.stderr, flush=True)<EOL>Method <NUM_LIT:2>:<EOL><DEDENT>og.critical(msg)<EOL>ritical("<STR_LIT>", exit_code)<EOL>xit(exit_code)<EOL>
It is not clear that Python guarantees to exit with a non-zero exit code (errorlevel in DOS/Windows) upon an unhandled exception. So this function produces the usual stack trace then dies with the specified exit code. See http://stackoverflow.com/questions/9555133/e-printstacktrace-equivalent-in-python. Test code: .. code-block:: python import logging import sys import traceback logging.basicConfig(level=logging.DEBUG) log = logging.getLogger() def fail(): try: x = 1/0 except Exception as exc: die(exc) Then call .. code-block:: python fail() ... which should exit Python; then from Linux (for example): .. code-block:: bash echo $? # show exit code
f14689:m2
def contains_duplicates(values: Iterable[Any]) -> bool:
for v in Counter(values).values():<EOL><INDENT>if v > <NUM_LIT:1>:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
Does the iterable contain any duplicate values?
f14690:m0
def index_list_for_sort_order(x: List[Any], key: Callable[[Any], Any] = None,<EOL>reverse: bool = False) -> List[int]:
def key_with_user_func(idx_val: Tuple[int, Any]):<EOL><INDENT>return key(idx_val[<NUM_LIT:1>])<EOL><DEDENT>if key:<EOL><INDENT>sort_key = key_with_user_func<EOL><DEDENT>else:<EOL><INDENT>sort_key = itemgetter(<NUM_LIT:1>)<EOL><DEDENT>index_value_list = sorted(enumerate(x), key=sort_key, reverse=reverse)<EOL>return [i for i, _ in index_value_list]<EOL>
Returns a list of indexes of ``x``, IF ``x`` WERE TO BE SORTED. Args: x: data key: function to be applied to the data to generate a sort key; this function is passed as the ``key=`` parameter to :func:`sorted`; the default is ``itemgetter(1)`` reverse: reverse the sort order? Returns: list of integer index values Example: .. code-block:: python z = ["a", "c", "b"] index_list_for_sort_order(z) # [0, 2, 1] index_list_for_sort_order(z, reverse=True) # [1, 2, 0] q = [("a", 9), ("b", 8), ("c", 7)] index_list_for_sort_order(q, key=itemgetter(1))
f14690:m1
def sort_list_by_index_list(x: List[Any], indexes: List[int]) -> None:
x[:] = [x[i] for i in indexes]<EOL>
Re-orders ``x`` by the list of ``indexes`` of ``x``, in place. Example: .. code-block:: python from cardinal_pythonlib.lists import sort_list_by_index_list z = ["a", "b", "c", "d", "e"] sort_list_by_index_list(z, [4, 0, 1, 2, 3]) z # ["e", "a", "b", "c", "d"]
f14690:m2
def flatten_list(x: List[Any]) -> List[Any]:
<EOL>n [item for sublist in x for item in sublist]<EOL>
Converts a list of lists into a flat list. Args: x: list of lists Returns: flat list As per http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python
f14690:m3
def unique_list(seq: Iterable[Any]) -> List[Any]:
<EOL>= set()<EOL>add = seen.add<EOL>n [x for x in seq if not (x in seen or seen_add(x))]<EOL>
Returns a list of all the unique elements in the input list. Args: seq: input list Returns: list of unique elements As per http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-whilst-preserving-order
f14690:m4
def chunks(l: List[Any], n: int) -> Iterable[List[Any]]:
for i in range(<NUM_LIT:0>, len(l), n):<EOL><INDENT>yield l[i:i + n]<EOL><DEDENT>
Yield successive ``n``-sized chunks from ``l``. Args: l: input list n: chunk size Yields: successive chunks of size ``n``
f14690:m5
def count_bool(blist: Iterable[Any]) -> int:
return sum([<NUM_LIT:1> if x else <NUM_LIT:0> for x in blist])<EOL>
Counts the number of "truthy" members of the input list. Args: blist: list of booleans or other truthy/falsy things Returns: number of truthy items
f14690:m6
def atoi(text: str) -> Union[int, str]:
return int(text) if text.isdigit() else text<EOL>
Converts strings to integers if they're composed of digits; otherwise returns the strings unchanged. One way of sorting strings with numbers; it will mean that ``"11"`` is more than ``"2"``.
f14691:m0
def natural_keys(text: str) -> List[Union[int, str]]:
<EOL>n [atoi(c) for c in re.split(r'<STR_LIT>', text)]<EOL>
Sort key function. Returns text split into string/number parts, for natural sorting; as per http://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside Example (as per the source above): .. code-block:: python >>> from cardinal_pythonlib.sort import natural_keys >>> alist=[ ... "something1", ... "something12", ... "something17", ... "something2", ... "something25", ... "something29" ... ] >>> alist.sort(key=natural_keys) >>> alist ['something1', 'something2', 'something12', 'something17', 'something25', 'something29']
f14691:m1
def trunc_if_integer(n: Any) -> Any:
if n == int(n):<EOL><INDENT>return int(n)<EOL><DEDENT>return n<EOL>
Truncates floats that are integers to their integer representation. That is, converts ``1.0`` to ``1``, etc. Otherwise, returns the starting value. Will raise an exception if the input cannot be converted to ``int``.
f14692:m0
def pdb_run(func: Callable, *args: Any, **kwargs: Any) -> None:
<EOL>try:<EOL><INDENT>func(*args, **kwargs)<EOL><DEDENT>except: <EOL><INDENT>type_, value, tb = sys.exc_info()<EOL>traceback.print_exc()<EOL>pdb.post_mortem(tb)<EOL><DEDENT>
Calls ``func(*args, **kwargs)``; if it raises an exception, break into the ``pdb`` debugger.
f14693:m0
def cause_segfault() -> None:
ctypes.string_at(<NUM_LIT:0>)<EOL>
This function will induce a segmentation fault and CRASH the application. Method as per https://docs.python.org/3/library/faulthandler.html
f14693:m1
def get_class_name_from_frame(fr: FrameType) -> Optional[str]:
<EOL>args, _, _, value_dict = inspect.getargvalues(fr)<EOL>if len(args) and args[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>instance = value_dict.get('<STR_LIT>', None)<EOL>if instance:<EOL><INDENT>cls = getattr(instance, '<STR_LIT>', None)<EOL>if cls:<EOL><INDENT>return cls.__name__<EOL><DEDENT>return None<EOL><DEDENT><DEDENT>return None<EOL>
A frame contains information about a specific call in the Python call stack; see https://docs.python.org/3/library/inspect.html. If the call was to a member function of a class, this function attempts to read the class's name. It returns ``None`` otherwise.
f14693:m2
def get_caller_name(back: int = <NUM_LIT:0>) -> str:
<EOL>try:<EOL><INDENT>frame = sys._getframe(back + <NUM_LIT:2>)<EOL><DEDENT>except ValueError:<EOL><INDENT>return '<STR_LIT:?>'<EOL><DEDENT>function_name = frame.f_code.co_name<EOL>class_name = get_class_name_from_frame(frame)<EOL>if class_name:<EOL><INDENT>return "<STR_LIT>".format(class_name, function_name)<EOL><DEDENT>return function_name<EOL>
Return details about the CALLER OF THE CALLER (plus n calls further back) of this function. So, if your function calls :func:`get_caller_name`, it will return the name of the function that called your function! (Or ``back`` calls further back.) Example: .. code-block:: python from cardinal_pythonlib.debugging import get_caller_name def who_am_i(): return get_caller_name() class MyClass(object): def classfunc(self): print("I am: " + who_am_i()) print("I was called by: " + get_caller_name()) print("That was called by: " + get_caller_name(back=1)) def f2(): x = MyClass() x.classfunc() def f1(): f2() f1() will produce: .. code-block:: none I am: MyClass.classfunc I was called by: f2 That was called by: f1
f14693:m3
def get_caller_stack_info(start_back: int = <NUM_LIT:1>) -> List[str]:
<EOL>callers = [] <EOL>frameinfolist = inspect.stack() <EOL>frameinfolist = frameinfolist[start_back:]<EOL>for frameinfo in frameinfolist:<EOL><INDENT>frame = frameinfo.frame<EOL>function_defined_at = "<STR_LIT>".format(<EOL>filename=frame.f_code.co_filename,<EOL>line=frame.f_code.co_firstlineno,<EOL>)<EOL>argvalues = inspect.getargvalues(frame)<EOL>formatted_argvalues = inspect.formatargvalues(*argvalues)<EOL>function_call = "<STR_LIT>".format(<EOL>funcname=frame.f_code.co_name,<EOL>argvals=formatted_argvalues,<EOL>)<EOL>code_context = frameinfo.code_context<EOL>code = "<STR_LIT>".join(code_context) if code_context else "<STR_LIT>"<EOL>onwards = "<STR_LIT>".format(<EOL>line=frame.f_lineno,<EOL>c=code,<EOL>)<EOL>description = "<STR_LIT:\n>".join([function_call, function_defined_at, onwards])<EOL>callers.append(description)<EOL><DEDENT>return list(reversed(callers))<EOL>
r""" Retrieves a textual representation of the call stack. Args: start_back: number of calls back in the frame stack (starting from the frame stack as seen by :func:`get_caller_stack_info`) to begin with Returns: list of descriptions Example: .. code-block:: python from cardinal_pythonlib.debugging import get_caller_stack_info def who_am_i(): return get_caller_name() class MyClass(object): def classfunc(self): print("Stack info:\n" + "\n".join(get_caller_stack_info())) def f2(): x = MyClass() x.classfunc() def f1(): f2() f1() if called from the Python prompt will produce: .. code-block:: none Stack info: <module>() ... defined at <stdin>:1 ... line 1 calls next in stack; code is: f1() ... defined at <stdin>:1 ... line 2 calls next in stack; code is: f2() ... defined at <stdin>:1 ... line 3 calls next in stack; code is: classfunc(self=<__main__.MyClass object at 0x7f86a009c6d8>) ... defined at <stdin>:2 ... line 3 calls next in stack; code is: and if called from a Python file will produce: .. code-block:: none Stack info: <module>() ... defined at /home/rudolf/tmp/stack.py:1 ... line 17 calls next in stack; code is: f1() f1() ... defined at /home/rudolf/tmp/stack.py:14 ... line 15 calls next in stack; code is: f2() f2() ... defined at /home/rudolf/tmp/stack.py:10 ... line 12 calls next in stack; code is: x.classfunc() classfunc(self=<__main__.MyClass object at 0x7fd7a731f358>) ... defined at /home/rudolf/tmp/stack.py:7 ... line 8 calls next in stack; code is: print("Stack info:\n" + "\n".join(get_caller_stack_info()))
f14693:m4
def debug_object(obj, log_level: int = logging.DEBUG) -> None:
msgs = ["<STR_LIT>".format(o=obj)]<EOL>for attrname in dir(obj):<EOL><INDENT>attribute = getattr(obj, attrname)<EOL>msgs.append("<STR_LIT>".format(<EOL>an=attrname, at=attribute, t=type(attribute)))<EOL><DEDENT>log.log(log_level, "<STR_LIT:{}>", "<STR_LIT:\n>".join(msgs))<EOL>
Sends details about a Python to the log, specifically its ``repr()`` representation, and all of its attributes with their name, value, and type. Args: obj: object to debug log_level: log level to use; default is ``logging.DEBUG``
f14693:m5
def produce_csv_output(filehandle: TextIO,<EOL>fields: Sequence[str],<EOL>values: Iterable[str]) -> None:
output_csv(filehandle, fields)<EOL>for row in values:<EOL><INDENT>output_csv(filehandle, row)<EOL><DEDENT>
Produce CSV output, without using ``csv.writer``, so the log can be used for lots of things. - ... eh? What was I talking about? - POOR; DEPRECATED. Args: filehandle: file to write to fields: field names values: values
f14694:m0
def output_csv(filehandle: TextIO, values: Iterable[str]) -> None:
line = "<STR_LIT:U+002C>".join(values)<EOL>filehandle.write(line + "<STR_LIT:\n>")<EOL>
Write a line of CSV. POOR; does not escape things properly. DEPRECATED. Args: filehandle: file to write to values: values
f14694:m1
def get_what_follows_raw(s: str,<EOL>prefix: str,<EOL>onlyatstart: bool = True,<EOL>stripwhitespace: bool = True) -> Tuple[bool, str]:
prefixstart = s.find(prefix)<EOL>if ((prefixstart == <NUM_LIT:0> and onlyatstart) or<EOL>(prefixstart != -<NUM_LIT:1> and not onlyatstart)):<EOL><INDENT>resultstart = prefixstart + len(prefix)<EOL>result = s[resultstart:]<EOL>if stripwhitespace:<EOL><INDENT>result = result.strip()<EOL><DEDENT>return True, result<EOL><DEDENT>return False, "<STR_LIT>"<EOL>
Find the part of ``s`` that is after ``prefix``. Args: s: string to analyse prefix: prefix to find onlyatstart: only accept the prefix if it is right at the start of ``s`` stripwhitespace: remove whitespace from the result Returns: tuple: ``(found, result)``
f14694:m2
def get_what_follows(strings: Sequence[str],<EOL>prefix: str,<EOL>onlyatstart: bool = True,<EOL>stripwhitespace: bool = True,<EOL>precedingline: str = "<STR_LIT>") -> str:
if not precedingline:<EOL><INDENT>for s in strings:<EOL><INDENT>(found, result) = get_what_follows_raw(s, prefix, onlyatstart,<EOL>stripwhitespace)<EOL>if found:<EOL><INDENT>return result<EOL><DEDENT><DEDENT>return "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>for i in range(<NUM_LIT:1>, len(strings)): <EOL><INDENT>if strings[i-<NUM_LIT:1>].find(precedingline) == <NUM_LIT:0>:<EOL><INDENT>(found, result) = get_what_follows_raw(strings[i], prefix,<EOL>onlyatstart,<EOL>stripwhitespace)<EOL>if found:<EOL><INDENT>return result<EOL><DEDENT><DEDENT><DEDENT>return "<STR_LIT>"<EOL><DEDENT>
Find a string in ``strings`` that begins with ``prefix``; return the part that's after ``prefix``. Optionally, require that the preceding string (line) is ``precedingline``. Args: strings: strings to analyse prefix: prefix to find onlyatstart: only accept the prefix if it is right at the start of ``s`` stripwhitespace: remove whitespace from the result precedingline: if truthy, require that the preceding line be as specified here Returns: the line fragment
f14694:m3
def get_string(strings: Sequence[str],<EOL>prefix: str,<EOL>ignoreleadingcolon: bool = False,<EOL>precedingline: str = "<STR_LIT>") -> Optional[str]:
s = get_what_follows(strings, prefix, precedingline=precedingline)<EOL>if ignoreleadingcolon:<EOL><INDENT>f = s.find("<STR_LIT::>")<EOL>if f != -<NUM_LIT:1>:<EOL><INDENT>s = s[f+<NUM_LIT:1>:].strip()<EOL><DEDENT><DEDENT>if len(s) == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>return s<EOL>
Find a string as per :func:`get_what_follows`. Args: strings: see :func:`get_what_follows` prefix: see :func:`get_what_follows` ignoreleadingcolon: if ``True``, restrict the result to what comes after its first colon (and whitespace-strip that) precedingline: see :func:`get_what_follows` Returns: the line fragment
f14694:m4
def get_string_relative(strings: Sequence[str],<EOL>prefix1: str,<EOL>delta: int,<EOL>prefix2: str,<EOL>ignoreleadingcolon: bool = False,<EOL>stripwhitespace: bool = True) -> Optional[str]:
for firstline in range(<NUM_LIT:0>, len(strings)):<EOL><INDENT>if strings[firstline].find(prefix1) == <NUM_LIT:0>: <EOL><INDENT>secondline = firstline + delta<EOL>if secondline < <NUM_LIT:0> or secondline >= len(strings):<EOL><INDENT>continue<EOL><DEDENT>if strings[secondline].find(prefix2) == <NUM_LIT:0>:<EOL><INDENT>s = strings[secondline][len(prefix2):]<EOL>if stripwhitespace:<EOL><INDENT>s = s.strip()<EOL><DEDENT>if ignoreleadingcolon:<EOL><INDENT>f = s.find("<STR_LIT::>")<EOL>if f != -<NUM_LIT:1>:<EOL><INDENT>s = s[f+<NUM_LIT:1>:].strip()<EOL><DEDENT>if stripwhitespace:<EOL><INDENT>s = s.strip()<EOL><DEDENT><DEDENT>if len(s) == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>return s<EOL><DEDENT><DEDENT><DEDENT>return None<EOL>
Finds a line (string) in ``strings`` beginning with ``prefix1``. Moves ``delta`` lines (strings) further. Returns the end of the line that begins with ``prefix2``, if found. Args: strings: as above prefix1: as above delta: as above prefix2: as above ignoreleadingcolon: restrict the result to the part after its first colon? stripwhitespace: strip whitespace from the start/end of the result? Returns: the line fragment
f14694:m5
def get_int(strings: Sequence[str],<EOL>prefix: str,<EOL>ignoreleadingcolon: bool = False,<EOL>precedingline: str = "<STR_LIT>") -> Optional[int]:
return get_int_raw(get_string(strings, prefix,<EOL>ignoreleadingcolon=ignoreleadingcolon,<EOL>precedingline=precedingline))<EOL>
Fetches an integer parameter via :func:`get_string`.
f14694:m6
def get_float(strings: Sequence[str],<EOL>prefix: str,<EOL>ignoreleadingcolon: bool = False,<EOL>precedingline: str = "<STR_LIT>") -> Optional[float]:
return get_float_raw(get_string(strings, prefix,<EOL>ignoreleadingcolon=ignoreleadingcolon,<EOL>precedingline=precedingline))<EOL>
Fetches a float parameter via :func:`get_string`.
f14694:m7
def get_int_raw(s: str) -> Optional[int]:
if s is None:<EOL><INDENT>return None<EOL><DEDENT>return int(s)<EOL>
Converts its input to an int. Args: s: string Returns: ``int(s)``, or ``None`` if ``s`` is ``None`` Raises: ValueError: if it's a bad string
f14694:m8
def get_bool_raw(s: str) -> Optional[bool]:
if s == "<STR_LIT:Y>" or s == "<STR_LIT:y>":<EOL><INDENT>return True<EOL><DEDENT>elif s == "<STR_LIT:N>" or s == "<STR_LIT:n>":<EOL><INDENT>return False<EOL><DEDENT>return None<EOL>
Maps ``"Y"``, ``"y"`` to ``True`` and ``"N"``, ``"n"`` to ``False``.
f14694:m9
def get_float_raw(s: str) -> Optional[float]:
if s is None:<EOL><INDENT>return None<EOL><DEDENT>return float(s)<EOL>
Converts its input to a float. Args: s: string Returns: ``int(s)``, or ``None`` if ``s`` is ``None`` Raises: ValueError: if it's a bad string
f14694:m10
def get_bool(strings: Sequence[str],<EOL>prefix: str,<EOL>ignoreleadingcolon: bool = False,<EOL>precedingline: str = "<STR_LIT>") -> Optional[bool]:
return get_bool_raw(get_string(strings, prefix,<EOL>ignoreleadingcolon=ignoreleadingcolon,<EOL>precedingline=precedingline))<EOL>
Fetches a boolean parameter via :func:`get_string`.
f14694:m11
def get_bool_relative(strings: Sequence[str],<EOL>prefix1: str,<EOL>delta: int,<EOL>prefix2: str,<EOL>ignoreleadingcolon: bool = False) -> Optional[bool]:
return get_bool_raw(get_string_relative(<EOL>strings, prefix1, delta, prefix2,<EOL>ignoreleadingcolon=ignoreleadingcolon))<EOL>
Fetches a boolean parameter via :func:`get_string_relative`.
f14694:m12
def get_float_relative(strings: Sequence[str],<EOL>prefix1: str,<EOL>delta: int,<EOL>prefix2: str,<EOL>ignoreleadingcolon: bool = False) -> Optional[float]:
return get_float_raw(get_string_relative(<EOL>strings, prefix1, delta, prefix2,<EOL>ignoreleadingcolon=ignoreleadingcolon))<EOL>
Fetches a float parameter via :func:`get_string_relative`.
f14694:m13