I’ll inspect the recent package-entry changes and trace the IPython initialization paths across the related modules before suggesting focused improvements.
$ git --no-pager status --short && git --no-pager diff -- mezcla/__init__.py mezcla/__main__.py mezcla/debug.py mezcla/system.py mezcla?? mezcla/qt6_clipboard_button.py
<shellId: 0 completed with exit code 0>/tpo/misc/programs/python/mezcla-devel-clone/mezcla/__init__.py#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Package initialization for mezcla.
#
## UPDATE 2026-09-23: adds SKIP_COMMON_EXPORT and omits FYI if not debugging proper
#
"""
Mezcla is Spanish for mixture, and this repository contains a variety of Python scripts.
Miscellaneous Python scripts developed over the course of several independent consulting projects. This also includes some code samples I adapted from publicly available source. (The code is not proprietary in nature. For example, it was not "borrowed" from proprietary source files, nor based on proprietary processes.)
Spoiler alter: this is not "Pythonic python": I'm more into R&D than production programming. Nonetheless, there's a some useful scripts here, so I made the repository available. It is public in the spirit of open source software.
This repository is licensed under the GNU Lesser General Public Version 3 (LGPLv3). See LICENSE.txt.
Adhoc usage:
from mezcla import *
debug.trace(TL.DEFAULT, "Hey")
debug.trace(TL.DETAILED, "Joe")
Tom O'Hara
Feb 2022
"""
version = "1.4.0.8"
__VERSION__ = version
__version__ = __VERSION__
# Standard module(s)
import os
import sys
import builtins
## DEBUG: sys.stderr.write(f"{__file__=}\n")
# Note: requires python 3 or higher
# TODO2: upgrade checks to cover 3.6 (mandatory) and 3.8+ (practical)
PYTHON3_PLUS = (sys.version_info[0] >= 3)
assert PYTHON3_PLUS, "Python 3 or higher: ¡por favor!"
# Local modules
# Define most common imports for causual usage
# Note: avoids syntax error is debug and system import directly
## TODO
## debug = None
## mezcla = None
## system = None
## if PYTHON3_PLUS:
## ## TODO: get relative imports to work
## ## from . import debug
## ## from .mezcla import debug
## import mezcla
## from mezcla import debug
## from mezcla import system
## TL = debug.TL
## ## DEBUG: debug.trace_expr(TL.DEFAULT, debug, mezcla, system, TL)
## else:
## TL = None
# Optional helpers for import context
def _in_ipython() -> bool:
"""Whether running under an active IPython/Jupyter session"""
get_ipython = getattr(builtins, "get_ipython", None)
if callable(get_ipython):
return bool(get_ipython())
return (("ipykernel" in sys.modules) or ("IPython" in sys.modules))
# Set convenience exports based on runtime mode.
# note: Skips import to avoid overhead and debugging complications due to packages
# in different repos. See debug.detect_shadowed_package.
__all__ = ["__VERSION__"]
skip_common_export = os.environ.get("SKIP_COMMON_EXPORT")
if _in_ipython and not skip_common_export:
# Shows FYI to make import source explicit in interactive sessions.
try:
debug_level = int(os.environ["DEBUG_LEVEL"], 0)
if (debug_level >= 4):
print("FYI: mezcla using ipython_utils imports: debug, system, etc.; disable via SKIP_COMMON_EXPORT")
from mezcla.ipython_utils import debug, gh, my_re, system, TL # pylint: disable=ungrouped-imports
__all__ += ["debug", "gh", "my_re", "system", "TL"]
except:
# Swallows the exception unless production
if __debug__:
sys.stderr.write(f"Exception importing __init__: {sys.exc_info()}\n")
else:
raise
## PREVIOUS:
## NOTE: See __main__.py
## debug.trace(TL.DETAILED, f"mezcla version: {__VERSION__}")
/tpo/misc/programs/python/mezcla-devel-clone/mezcla/__main__.py#! /usr/bin/env python3
#
# Shows version, etc. in support of mezcla CLI script.
#
# Note: Test for working around ":double import" issue. See
# https://stackoverflow.com/questions/43393764/python-3-6-project-structure-leads-to-runtimewarning
# Also see
# https://stackoverflow.com/questions/4042905/what-is-main-py
#
## UPDATE 2026-09-23: clarifies invocation
## UPDATE 29 Aug 26: adds client arg to main
#
"""Entry point for mezcla"""
# Standard module(s)
## TODO: import logging
# Installed modules
import mezcla
from mezcla import debug
from mezcla import glue_helpers as gh
from mezcla.my_regex import my_re
from mezcla import system
# Contants
TL = debug.TL
def main(omit_warnings=None, client=None):
"""Entry point: shows version info if debugging otherwise a warning.
note: This will OMIT_WARNINGS unless a CLIENT like mezcla CLI script.
"""
if omit_warnings is None:
omit_warnings = client
if not omit_warnings:
system.print_error(f"Warning: {__file__} is not intended as standalone.")
file_path = system.real_path(gh.dirname(__file__))
level = (TL.USUAL if not client else TL.ALWAYS)
debug.trace(level, f"Version: {mezcla.__VERSION__}")
debug.trace(level, f"Install path: {file_path}")
# Derive module name
# example: /home/tomohara/python/Mezcla/mezcla/__main__.py => "mezcla"
module = "<module>"
sep = my_re.escape(system.path_separator())
match = my_re.search(fr"([^{sep}]*){sep}[^{sep}]*$", __file__)
if match:
module = match.group(1)
if not omit_warnings:
system.print_error(f"Likewise for the package (e.g., via 'python -m {module}')\n")
if __name__ == '__main__':
main()
/tpo/misc/programs/python/mezcla-devel-clone/mezcla.ipynb_checkpoints
.mypy_cache
.pytest_cache
TAGS
TODO.md
__init__.py
__init__.py.23Sep26
__main__.py
__pycache__
__pycache__.20260902
_bad-_run-together.log
_copy_glue_helpers.py
_cut.05aug26.run.1.log
_doctest-_fix_indent-05sep26.2.log
_doctest-_fix_indent-05sep26.3.log
_doctest-_fix_indent-05sep26.4.log
_doctest-_fix_indent-05sep26.5.log
_doctest-_fix_indent-05sep26.6.log
_doctest-common_module-05sep26.1.log
_doctest-common_module-05sep26.7.log
_doctest-common_module-05sep26.8.log
_doctest-common_module-05sep26.9.log
_doctest-misc_utils-05sep26.log
_evaluate_example_tests.05sep26.run.5.log
_evaluate_example_tests.05sep26.run.5.out
_evaluate_example_tests.05sep26.run.6.log
_evaluate_example_tests.05sep26.run.6.out
_evaluate_example_tests.05sep26.run.7.log
_evaluate_example_tests.05sep26.run.7.out
_evaluate_example_tests.05sep26.run.8.log
_evaluate_example_tests.05sep26.run.8.out
_gemini-project-mark-examples.html
_gemini-radar-reflectivity.html
_gemini-radar-reflectivity.pdf
_gemini_test_selenium.py
_git-trash
_glue_helpers_run.py
_master_test_run.py
_model_a-debug.py.txt
_model_b-debug.py.txt
_multi_template.py
_pylint
_rulez.2.selenium.pdf
_run-ex-tests.05sep26.1.all.log
_run-ex-tests.05sep26.1.all.out
_run-ex-tests.05sep26.1.log
_run-ex-tests.05sep26.1.temp.log
_run-ex-tests.05sep26.1.temp.out
_run-individually.log
_run-together.log
_test-comment-examples-05sep26.log
_test_conversion_mezcla_to_standard.py
_word-wrap.1.selenium.pdf
_word-wrap.1.selenium.pdf.log
_word-wrap.html
adaptive_log_filter.py
adhoc
archive
audio.py
backup
bash_ast.py
bing_search.py
check_html_javascript.py
chromedriver_verbose.log
clipboard_button.py
compute_tfidf.py
convert_emoticons.py
convert_plasma_config.py
cut.py
data_utils.py
debug.py
docs
downloads
evaluate_example_tests.py
examples
extract_document_text.py
file_utils.py
filter_random.py
flagged
format_profile.py
gensim_test.py
glue_helpers.py
google_word2vec.py
gpu_utils.py
html_converter.py
html_utils.py
introspection.py
ipython_utils.py
kenlm_example.py
keras_param_search.py
llm_desktop_search.py
log-files
main.py
master_test.py
merge_files.py
merge_notes.py
mezcla
mezcla_to_standard.py
mezcla_to_standard.py.07Sep26
misc_utils.py
my_regex.py
ngram_tfidf.py
nohup.out.23Sep26
old
os_utils.py
output-files
pandas_sklearn.py
plot_utils.py
poe_client.py
python_ast.py
qt6_clipboard_button.py
randomize_lines.py
rgb_color_name.py
rulez.1.selenium.pdf.log
rulez.2.selenium.pdf.log
samples
show_dependency_chain.py
simple_main_example.py
spacy_nlp.py
spell.py
summarize_pytest.py
system.py
template.py
tests
text_categorizer.py
text_processing.py
text_utils.py
tfidf
tpo_common.py
train_language_model.py
train_text_categorizer.py
transpose_data.py
unittest_wrapper.py
usage.list
validate_arguments.py
validate_arguments_types.py
xml_utils.py$ git --no-pager log --oneline -8 -- mezcla/__init__.py mezcla/__main__.py mezcla/mezcla mezcla/debug.py mezcla/system.py && git --no-pager show --stat --oneline -1 -- mezcla/__init__.py3f0c9231 clarifies support for mezcla CLI script
e07c190c adds SKIP_COMMON_EXPORT and omits FYI if not debugging proper
147db4f7 fixes relative_intersection to normalize on unique item len
6fac04c1 comments out in trace of unique_items to avoid problems with generators
13c29e18 traces unique_items in/out lengths
46163c3a adds TL.NONE as more intuitive name for TL.ALWAYS
8c97c4c2 adds coerce to trace_values and fleshes out docstring
49435742 uses new client arg to mezcla_main
e07c190c adds SKIP_COMMON_EXPORT and omits FYI if not debugging proper
mezcla/__init__.py | 32 +++++++++++++++++++++++++-------
1 file changed, 25 insertions(+), 7 deletions(-)
<shellId: 1 completed with exit code 0>/tpo/misc/programs/python/mezcla-devel-clone/mezcla/ipython_utils.py#! /usr/bin/env python3
#
# Miscellanous utilities for ipython usage
#
# Note:
# - This is idiosyncractic code based on Tom O'Hara's ipython startup file
# (~/.ipython/profile_default/startup/25-quarter.py).
# - To faciliate importing functions and variables for testing purposes (e.g., EX tests),
# use import_module_globals as illustrated in second example below.
# - Use `jupyter console` to invoke a CLI verson of Jupyter (i.e., not ipython).
#
"""
Adhoc stuff for ipython (or Jupyter notebooks)
Simple usage:
from mezcla.ipython_utils import *
Advanced usage:
# Make sure import-globals utility active
import mezcla.ipython_utils
reload(mezcla.ipython_utils)
import_module_globals = mezcla.ipython_utils.import_module_globals
# Run over misc_utils.py
import_module_globals("mezcla.misc_utils", globals_dict=builtins.globals())
#
# note: ipython chokes over the following when preceding comment included:
# >>> (TYPICAL_EPSILON, VALUE_EPSILON)
# (1e-06, 0.001)
Misc. usage:
set_xterm_title("ipython: " + os.getcwd())
"""
# Note: most imports are done for the sake of ipython usage
#
# pylint: disable=unused-import
# Standard modules
import builtins
from collections import defaultdict, namedtuple
import json
import math
import os
import random
import re
import sys
from importlib import reload
# Installed modules
try:
import nltk
import numpy as np
import pandas as pd
import sklearn
except:
nltk = np = pd = sklearn = None
sys.stderr.write(f"Exception during installed imports: {sys.exc_info()}")
# Local local modules
import mezcla
from mezcla import debug
from mezcla import html_utils
from mezcla.main import Main
from mezcla import system
from mezcla.my_regex import my_re
from mezcla import glue_helpers as gh
from mezcla import tpo_common as tpo
try:
from mezcla import data_utils as du
from mezcla.unittest_wrapper import TestWrapper
except:
du = TestWrapper = None
system.print_exception_info("loading local modules with dependencies")
# Constants
TL = debug.TL
# Environment options
HOME = gh.HOME_DIR
USER = system.USER
#-------------------------------------------------------------------------------
# Global Variables
#
# Note:
# - intended to faciliate experimentation in ipython
# - crytic names for historical reasons (and since hash and list reserved words)
#
h = {'a': 1, 'b': 2, 'c': 3}
l = [1, 2, 3]
t = "some text"
text = t
test_it = TestWrapper()
try:
english_stopwords = nltk.corpus.stopwords.words('english')
spanish_stopwords = nltk.corpus.stopwords.words('spanish')
except:
system.print_exception_info("loading resources like NLTK")
#-------------------------------------------------------------------------------
# Helper functions
def grep_obj_methods(obj, pattern, flags=None):
"""Return methods for OBJ matching PATTERN (with optional re.search FLAGS)
Note: in practice, all object members are grepped"""
## TODO3: rename as grep_obj_attributes
# EX: grep_obj_methods(str, "strip") => ["lstrip", "strip", "rstrip"]
if flags is None:
flags = re.IGNORECASE
return list(m for m in dir(obj) if re.search(pattern, m, flags))
def import_module_globals(module_name, include_private=False, include_dunder=False, globals_dict=None, ignore_errors=None):
"""Import MODULE_NAME optionally with INCLUDE_PRIVATE and INCLUDE_DUNDER and setting GLOBALS_DICT"""
debug.trace_expr(5, module_name, include_private, include_dunder, globals_dict, ignore_errors,
prefix="in import_module_globals: ")
# note: intended to support reloading modules imported in ipython via 'from module import *'
# TODO3: find a cleaner way of doing this (e.g., via import support)
# EX: import_module_globals("mezcla.misc_utils", globals_dict=builtins.globals()); VALUE_EPSILON => 1e-3
# pylint: disable=eval-used, exec-used
if globals_dict is None:
globals_dict = builtins.globals()
if ignore_errors is None:
ignore_errors = False
# Ensure module_name is a string
if not isinstance(module_name, str):
if not ignore_errors:
system.print_error(f"Error: module_name must be a string, got {type(module_name)}")
debug.trace(5, f"module_name is not a string: {type(module_name)}")
return
# Get list of modules attributes (e.g., variables)
module = None
module_attrs = []
try:
debug.trace(7, "in try")
loaded = False
# Check if module already exists in sys.modules
module_exists = module_name in sys.modules
if module_exists:
try:
debug.trace(6, "Module exists - trying reload")
# First import it into the namespace if not already there
import_command = f"import {module_name}"
exec(import_command, globals_dict)
module = eval(module_name, globals_dict)
module = reload(module)
loaded = True
except:
debug.trace_exception_info(7, "existing reload")
if not loaded:
try:
debug.trace(5, "Trying import")
import_command = f"import {module_name}"
exec(import_command, globals_dict)
module = eval(module_name, globals_dict)
loaded = True
except:
debug.trace_exception_info(4, f"{module_name} import")
if loaded:
module_attrs = dir(module)
elif not ignore_errors:
system.print_error(f"Error: unable to import or reload {module_name}")
except:
if not ignore_errors:
system.print_exception_info("import_module_globals")
else:
debug.trace_exception_info(6, "import_module_globals")
debug.trace_expr(5, module)
# Import each individually
num_ok = 0
num_ignored = 0
for var in module_attrs:
debug.trace_expr(6, var)
# Optionally, include "dunder" attributes like __name__ or private ones like _name
include = True
if var.startswith("__"):
if not include_dunder:
include = False
debug.trace(7, f"excluding dunder attribute {var!r}")
elif (var.startswith("_") and not include_private):
include = False
debug.trace(7, f"excluding private attribute {var!r}")
# Import the value
if include:
import_desc = (f"import[ing] {var} from {module_name}")
try:
debug.trace(5, import_desc)
globals_dict[var] = getattr(module, var)
num_ok += 1
except:
debug.trace_exception_info(4, import_desc)
else:
num_ignored += 1
debug.trace(5, f"{num_ok} of {len(module_attrs)} attributes loaded OK; {num_ignored=}")
return
def pr_dir(obj):
"""Print dir listing for OBJ"""
print(dir(obj))
def set_xterm_title(title=None):
"""Set xterm TITLE via set_xterm_title.bash
Note:
- Uses set_xterm_title.bash from https://github.com/tomasohara/shell-scripts.
- The TITLE can use environment variables (e.g., "ipython [$CONDA_PREFIX]").
"""
# Sample result: "ipython: /home/tomohara/mezcla: Py3.10(base)"
if title is None:
title = "ipython $PWD"
gh.issue(f'set_xterm_title.bash "{title}"')
#-------------------------------------------------------------------------------
# Helper class
class Fubar():
"""Dummy class used for cut-n-paste of method code (e.g., under ipython)
Example:
# setup
debug.assertion("Fubar" in str(self))
self.dummy_arg = True
# cut-n-pasted code (see template.py_
debug.trace_object(1, self, label=f"{self.__class__.__name__} instance")
Output:
Fubar instance: {
dummy_arg: True
}
"""
pass
#-------------------------------------------------------------------------------
# Initialization
# note: self and dummy_main are for interactive usage
self = Fubar()
dummy_main = Main([])
#-------------------------------------------------------------------------------
def main() -> None:
"""Entry point"""
debug.trace(TL.DETAILED, f"main(): script={system.real_path(__file__)}")
system.print_stderr(f"Warning: {__file__} is not intended to be run standalone\n")
_main_app = Main(description=__doc__.format(script=gh.basename(__file__)))
if __name__ == '__main__':
debug.trace_current_context(level=TL.QUITE_VERBOSE)
debug.trace(5, f"module __doc__: {__doc__}")
main()
"ipython|IPython|get_ipython|SKIP_COMMON_EXPORT|common export|double import|detect_shadowed_package" in *.py (mezcla)[grep content: 51 matches across 11 file(s) under /tpo/misc/programs/python/mezcla-devel-clone/mezcla]
__init__.py (12 match(es)):
6: ## UPDATE 2026-09-23: adds SKIP_COMMON_EXPORT and omits FYI if not debugging proper
62: def _in_ipython() -> bool:
63: """Whether running under an active IPython/Jupyter session"""
64: get_ipython = getattr(builtins, "get_ipython", None)
65: if callable(get_ipython):
66: return bool(get_ipython())
67: return (("ipykernel" in sys.modules) or ("IPython" in sys.modules))
71: # in different repos. See debug.detect_shadowed_package.
73: skip_common_export = os.environ.get("SKIP_COMMON_EXPORT")
74: if _in_ipython and not skip_common_export:
79: print("FYI: mezcla using ipython_utils imports: debug, system, etc.; disable via SKIP_COMMON_EXPORT")
80: from mezcla.ipython_utils import debug, gh, my_re, system, TL # pylint: disable=ungrouped-imports
ipython_utils.py (18 match(es)):
3: # Miscellanous utilities for ipython usage
6: # - This is idiosyncractic code based on Tom O'Hara's ipython startup file
7: # (~/.ipython/profile_default/startup/25-quarter.py).
10: # - Use `jupyter console` to invoke a CLI verson of Jupyter (i.e., not ipython).
14: Adhoc stuff for ipython (or Jupyter notebooks)
17: from mezcla.ipython_utils import *
21: import mezcla.ipython_utils
22: reload(mezcla.ipython_utils)
23: import_module_globals = mezcla.ipython_utils.import_module_globals
28: # note: ipython chokes over the following when preceding comment included:
33: set_xterm_title("ipython: " + os.getcwd())
36: # Note: most imports are done for the sake of ipython usage
88: # - intended to faciliate experimentation in ipython
120: # note: intended to support reloading modules imported in ipython via 'from module import *'
219: - The TITLE can use environment variables (e.g., "ipython [$CONDA_PREFIX]").
221: # Sample result: "ipython: /home/tomohara/mezcla: Py3.10(base)"
223: title = "ipython $PWD"
230: """Dummy class used for cut-n-paste of method code (e.g., under ipython)
__main__.py:5: # Note: Test for working around ":double import" issue. See
debug.py (4 match(es)):
180: def detect_shadowed_package() -> Tuple[bool, Dict[str, Any]]:
768: # note: Short-circuits processing to avoid errors about known problems (e.g., under ipython)
996: # note: Short-circuits processing to avoid extraneous warnings (e.g., trace_expr under ipython)
1185: is_shadowed, shadow_details = detect_shadowed_package()
audio.py:56: # TODO3: format code example using IPython example syntax (i.e., '>>>')
text_categorizer.py:182: # Note: intended for comparing results here against tutorial (e.g., in ipython shell)
examples/youtube_transcript.py (2 match(es)):
130: " ipython <<END\n" +
145: debug.trace(3, f"Try via ipython:\n{debug_snippet}")
introspection.py:55: # - pytest can wreck havoc with introspection (e.g., OK with ipython)
archive/show_bert_representation.py:97: # get the individual work vectors and manually combine vectors (e.g., ipython)
tests/test_debug.py (5 match(es)):
125: def test_detect_shadowed_package(self):
126: """Ensure detect_shadowed_package catches higher-priority package paths"""
127: debug.trace(4, f"test_detect_shadowed_package(): self={self}")
139: is_shadowed, shadow_details = THE_MODULE.detect_shadowed_package()
434: ## ex: Assertion failed: gpu=None\n (at <ipython-input-14-e3c30214f890>:1)
tests/test_ipython_utils.py (5 match(es)):
3: # Test(s) for ../ipython_utils.py
9: # $ PYTHONPATH=".:$PYTHONPATH" python ./mezcla/tests/test_ipython_utils.py
12: """Tests for ipython_utils module"""
26: import mezcla.ipython_utils as THE_MODULE
48: # Import this module (i.e., "mezcla.ipython_utils")"def path_separator|path_separator\s*=|def print_error|def real_path|class TL" in {debug,system}.py (mezcla)/tpo/misc/programs/python/mezcla-devel-clone/mezcla/system.py:430:def print_error(text: str) -> None:
/tpo/misc/programs/python/mezcla-devel-clone/mezcla/system.py:1136:def path_separator(sysname: Optional[str] = None) -> str:
/tpo/misc/programs/python/mezcla-devel-clone/mezcla/system.py:1314:def real_path(path: str) -> str:The new hook currently runs on every import because the predicate function is referenced rather than called; I’m now checking the intended CLI/package invocation paths and the existing shadow-import safeguards to distinguish that regression from the broader design improvements.
$ git --no-pager show --format=fuller --find-renames e07c190c -- mezcla/__init__.py && printf '\n--- __main__ follow-up ---\n' && git --no-pager show --format=fuller --find-renames 3f0c9231 -- mezcla/__main__.pycommit e07c190c7d6323643226599c4dcf274f1c7e2853
Author: Tom O'Hara <tohara@tohara.com>
AuthorDate: Wed Sep 23 17:40:48 2026 -0400
Commit: Tom O'Hara <tohara@tohara.com>
CommitDate: Wed Sep 23 17:40:48 2026 -0400
adds SKIP_COMMON_EXPORT and omits FYI if not debugging proper
diff --git a/mezcla/__init__.py b/mezcla/__init__.py
index 082c363c..f83f038d 100755
--- a/mezcla/__init__.py
+++ b/mezcla/__init__.py
@@ -1,5 +1,11 @@
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
+#
+# Package initialization for mezcla.
+#
+## UPDATE 2026-09-23: adds SKIP_COMMON_EXPORT and omits FYI if not debugging proper
+#
+
"""
Mezcla is Spanish for mixture, and this repository contains a variety of Python scripts.
@@ -23,6 +29,7 @@ __VERSION__ = version
__version__ = __VERSION__
# Standard module(s)
+import os
import sys
import builtins
## DEBUG: sys.stderr.write(f"{__file__=}\n")
@@ -60,13 +67,24 @@ def _in_ipython() -> bool:
return (("ipykernel" in sys.modules) or ("IPython" in sys.modules))
# Set convenience exports based on runtime mode.
-if _in_ipython():
- # FYI to make import source explicit in interactive sessions.
- print("FYI: mezcla using ipython_utils imports: debug, gh, my_re, system, TL")
- from mezcla.ipython_utils import debug, gh, my_re, system, TL # pylint: disable=ungrouped-imports
- __all__ = ["debug", "gh", "my_re", "system", "TL", "__VERSION__"]
-else:
- __all__ = ["__VERSION__"]
+# note: Skips import to avoid overhead and debugging complications due to packages
+# in different repos. See debug.detect_shadowed_package.
+__all__ = ["__VERSION__"]
+skip_common_export = os.environ.get("SKIP_COMMON_EXPORT")
+if _in_ipython and not skip_common_export:
+ # Shows FYI to make import source explicit in interactive sessions.
+ try:
+ debug_level = int(os.environ["DEBUG_LEVEL"], 0)
+ if (debug_level >= 4):
+ print("FYI: mezcla using ipython_utils imports: debug, system, etc.; disable via SKIP_COMMON_EXPORT")
+ from mezcla.ipython_utils import debug, gh, my_re, system, TL # pylint: disable=ungrouped-imports
+ __all__ += ["debug", "gh", "my_re", "system", "TL"]
+ except:
+ # Swallows the exception unless production
+ if __debug__:
+ sys.stderr.write(f"Exception importing __init__: {sys.exc_info()}\n")
+ else:
+ raise
## PREVIOUS:
## NOTE: See __main__.py
--- __main__ follow-up ---
commit 3f0c9231229d4c9e65dab167f9ea89b1dd78684b
Author: Tom O'Hara <tohara@tohara.com>
AuthorDate: Wed Sep 23 17:50:43 2026 -0400
Commit: Tom O'Hara <tohara@tohara.com>
CommitDate: Wed Sep 23 17:50:43 2026 -0400
clarifies support for mezcla CLI script
diff --git a/mezcla/__main__.py b/mezcla/__main__.py
index f9543b77..d56ec661 100755
--- a/mezcla/__main__.py
+++ b/mezcla/__main__.py
@@ -1,10 +1,13 @@
#! /usr/bin/env python3
#
+# Shows version, etc. in support of mezcla CLI script.
+#
# Note: Test for working around ":double import" issue. See
-# See https://stackoverflow.com/questions/43393764/python-3-6-project-structure-leads-to-runtimewarning
+# https://stackoverflow.com/questions/43393764/python-3-6-project-structure-leads-to-runtimewarning
# Also see
# https://stackoverflow.com/questions/4042905/what-is-main-py
#
+## UPDATE 2026-09-23: clarifies invocation
## UPDATE 29 Aug 26: adds client arg to main
#
@@ -24,7 +27,9 @@ from mezcla import system
TL = debug.TL
def main(omit_warnings=None, client=None):
- """Entry point: shows version info if debugging otherwise a warning"""
+ """Entry point: shows version info if debugging otherwise a warning.
+ note: This will OMIT_WARNINGS unless a CLIENT like mezcla CLI script.
+ """
if omit_warnings is None:
omit_warnings = client
if not omit_warnings:
<shellId: 2 completed with exit code 0>/tpo/misc/programs/python/mezcla-devel-clone/mezcla/debug.py (lines 145-225)#...............................................................................
# Utility functions
def _print_exception_info(task: str) -> None:
"""Output exception information to stderr regarding TASK (e.g., function)"""
# Note: non-tracing version of system's print_exception_info
sys.stderr.write("Error during {t}: {exc}\n".
format(t=task, exc=sys.exc_info()))
return
def docstring_parameter(**kwargs):
"""Decorator to reformat docstring using specified KWARGS"""
# Note: Docstrings should not contain extraneous braces (e.g., "avoid {}'s")
# based on https://stackoverflow.com/questions/10307696/how-to-put-a-variable-into-python-docstring/71377925#71377925
# example: @docstring_parameter(max_len=max_trace_value_len)
# def trace_it() ... """Print it to stderr up to the maximum length ({max_len})"""
def decorator(obj):
new_doc = obj.__doc__
try:
# Update if defined (n.b., not available with python -OO)
if obj.__doc__:
new_doc = obj.__doc__.format(**kwargs)
except:
_print_exception_info("docstring_parameter")
obj.__doc__ = new_doc
return obj
return decorator
def _same_path(path1: Path, path2: Path) -> bool:
"""Heuristic path equality, including symlink-aware checks."""
try:
return os.path.samefile(path1, path2)
except:
return (path1.resolve() == path2.resolve())
def detect_shadowed_package() -> Tuple[bool, Dict[str, Any]]:
"""Heuristic indicating whether another version of this package is ahead of this one in sys.path?
Returns tuple with shadow status flag and details hash.
"""
# Resolve current module and script metadata.
mod = sys.modules[__name__]
mod_file = getattr(mod, "__file__", None)
if not mod_file:
return False, {"shadowed": False, "reason": "no __file__"}
current_module_file = Path(mod_file).resolve()
script_path = (Path(sys.argv[0]).resolve() if (sys.argv and sys.argv[0]) else None)
package_name = (__package__ or getattr(mod, "__package__", "") or "")
pkg_dir = None
pkg_name = None
# Infer package directory from module metadata when available.
if package_name:
pkg_name = package_name.split(".")[0]
pkg_dir = current_module_file.parent
depth = max(len(package_name.split(".")) - 1, 0)
for _ in range(depth):
pkg_dir = pkg_dir.parent
# Otherwise, use script-mode heuristics (e.g., running ./debug.py).
elif (current_module_file.parent / "__init__.py").is_file():
pkg_dir = current_module_file.parent
pkg_name = pkg_dir.name
elif script_path and (script_path.parent / "__init__.py").is_file():
pkg_dir = script_path.parent
pkg_name = pkg_dir.name
else:
return False, {"shadowed": False, "reason": "not in a package"}
assert pkg_dir is not None
assert pkg_name is not None
pkg_dir = pkg_dir.resolve()
trace_expr(5, pkg_dir, pkg_name, script_path)
# Scan python path entries in import precedence order.
first_hit = None
current_index = None
for i, entry in enumerate(sys.path):
base = Path(entry or os.getcwd()).resolve()
candidate = (base / pkg_name)
trace_expr(5, i, entry, candidate)
if not candidate.is_dir():
continue/tpo/misc/programs/python/mezcla-devel-clone/mezcla/debug.py (lines 1150-1210) global time_start
if (time_start > 0 and not force):
## TODO3: track down source of re-init
self.trace(DETAILED, f"debug_init early exit: {time_start=} {force=}")
self.trace_stack(VERBOSE)
return
self.trace(DETAILED, f"in debug_init(force={force}); DEBUG_LEVEL={trace_level}; {timestamp()}")
self.trace(VERBOSE, f"{time_start=}")
time_start = time.time()
## NOTE: Useful for tracking down multiple invocations (e.g., due to imports or __init__.py),
## which is complicated by python path conflicts (see shadow detection below).
## DEBUG: self.trace_stack(VERBOSE)
# note: shows command invocation unless invoked via "python -c ..."
command_line = " ".join(sys.argv)
if (command_line and (command_line != "-c") and (command_line != "-m")):
# TODO2: simplify misc. trace suppression options (n.b., check shellscript repo)
if _getenv_bool("TRACE_INVOCATION", False):
if not (_getenv_bool("QUIET_MODE", False) or _getenv_bool("DURING_ALIAS", False)):
self.trace(USUAL, command_line)
self.trace_expr(DETAILED, sys.argv)
self.open_debug_file()
# Determine whether tracing include time and date
# note: Useful for adhoc profiling
global output_timestamps
output_timestamps = _getenv_bool("OUTPUT_DEBUG_TIMESTAMPS", False)
# Show startup time and tracing info
self.trace_fmtd(DETAILED, "[{f}] loaded at {t}", f=module_file, t=timestamp())
self.trace_fmtd(DETAILED, "trace_level={l}; output_timestamps={ots}", l=trace_level, ots=output_timestamps)
self.trace_expr(QUITE_DETAILED, __file__)
self.trace_values(VERBOSE, sys.path, "sys.path")
# note: also show python path if under Unix (TODO3: generalize)
if (os.name == "posix"):
self.code(VERBOSE, lambda: os.system("(echo -n 'Python: '; which python) 1>&2"))
is_shadowed, shadow_details = detect_shadowed_package()
self.trace_expr(DETAILED, shadow_details)
if is_shadowed:
self.trace(USUAL, f"Warning: package likely shadowed: {shadow_details}")
# Determine other debug-only environment options
global para_mode_tracing
para_mode_tracing = _getenv_bool("PARA_MODE_TRACING", para_mode_tracing)
global max_trace_value_len
max_trace_value_len = _getenv_int("MAX_TRACE_VALUE_LEN", max_trace_value_len)
global use_logging
use_logging = _getenv_bool("USE_LOGGING", use_logging)
enable_logging = _getenv_bool("ENABLE_LOGGING", use_logging)
if enable_logging:
init_logging()
global include_trace_diagnostics
include_trace_diagnostics = _getenv_bool("TRACE_DIAGNOSTICS", trace_level >= QUITE_DETAILED)
global monitor_functions
monitor_functions = _getenv_bool("MONITOR_FUNCTIONS", False)
if monitor_functions:
sys.setprofile(profile_function)
## TODO1: (all output_caller_info env. init; also add to trace_expr below)
## global output_caller_info
## output_caller_info = _getenv_bool("OUTPUT_CALLER_INFO", output_caller_info)
self.trace_expr(VERBOSE, para_mode_tracing, max_trace_value_len, use_logging, enable_logging, monitor_functions)
global use_old_introspection/tpo/misc/programs/python/mezcla-devel-clone/mezcla/system.py (lines 1-120)#! /usr/bin/env python3
#
# Functions for system related access, such as running command or
# getting environment values.
#
# TODO:
# - * Add support for checking for getenv_xyz-style parameters not used!
# - Finish python 2/3 special case handling via six package (e.g., in order
# to remove stupud pylint warnings).
# - Rename as system_utils so clear that non-standard package.
# - Add support for maintaining table of environment variables with optional descriptions.
# - Add safe_int from tpo_common, as includes support for base (e.g., 16 for hex).
# - Reconcile against functions in tpo_common.py (e.g., to make sure functionality covered and similar tracing supported).
# - Make sure format-based function tracing is well formed:
# ex: "is_dir{p}" => "is_dir({p})".
# - ** Define generic function for creating simple wrappers:
# ex: def fu(): r = sys.fu(); trace(N, f"fub() returned {r}"); return r
# => fu = define_wrapper(trace_level=N, sys.fu)
#
# TODO2:
# - convert additional open() calls to open_file()
# - drop python 2 support
#
"""System-related functions"""
# Standard packages
from collections import defaultdict, OrderedDict
## UPDATE: 06/20/2026: Integrates alternative model's type hints.
from collections.abc import Iterator
import datetime
## OLD: import importlib_metadata
import inspect
import os
import pickle
import re
import sys
import time
from typing import (
Any, IO, Optional, Union, overload, List,
Tuple, Callable, Dict, Set
)
from io import TextIOWrapper
## DEBUG: sys.stderr.write(f"{__file__=}\n")
# Installed packages
import six
# Local packages
from mezcla import debug
from mezcla.debug import UTF8, TraceLevel
## TODO3: debug.trace_expr(6, __file__)
## DEBUG: sys.stderr.write(f"{__file__=}\n")
from mezcla.validate_arguments_types import (
FileDescriptorOrPath, OptExcInfo, StrOrBytesPath,
)
# Types
ListOrSet = Union[List[Any], Set[Any]] # stable
# Constants
STRING_TYPES = six.string_types
MAX_SIZE = six.MAXSIZE
MAX_INT = MAX_SIZE
TEMP_DIR = None
ENCODING = "encoding"
USER = None
## TODO: debug.assertion(python_maj_min_version() >= 3.8, "Require Python 3.8+ for function def's with '/' or '*'")
## See https://stackoverflow.com/questions/9079036/how-do-i-detect-the-python-version-at-runtime
debug.assertion(sys.version_info >= (3, 8), "Require Python 3.8+ for function def's with '/' or '*'")
#-------------------------------------------------------------------------------
# Support for needless python changes
def maxint() -> int:
"""Maximum size for an integer"""
# Note: this is just a sanity check
debug.assertion(MAX_INT == MAX_SIZE)
return MAX_INT
#-------------------------------------------------------------------------------
# Support for environment variable access
# TODO: Put in separate module
env_options: Dict[str, str] = {}
env_defaults: Dict[str, Any] = {}
env_diagnostic_level = 6
#
def set_env_diagnostic_level(level: debug.IntOrTraceLevel) -> None:
"""Set trace LEVEL at which getenv_xyz-related diagnostics occur"""
global env_diagnostic_level
env_diagnostic_level = level
#
def register_env_option(var: str, description: str, default: Any) -> None:
"""Register environment VAR as option with DESCRIPTION and DEFAULT"""
# Note: The default value is typically the default value passes into the
# getenv_xyz call, not the current value from the environment.
debug.trace_fmt(7, "register_env_option({v}, {dsc!r}, {dft!r})",
v=var, dsc=description, dft=default)
global env_options
global env_defaults
ok = True
old_description = env_options.get(var)
if (old_description is not None) and (old_description != description):
debug.trace(4, f"Warning: redefining env option description for {var}: {old_description=} {description=}")
ok = False
old_default = env_defaults.get(var)
if (old_default is not None) and (old_default != default):
debug.trace(4, f"Warning: redefining env option default for {var}: {old_default=} {default=}")
ok = False
if not ok:
debug.trace_stack(env_diagnostic_level)
env_options[var] = description
env_defaults[var] = default
return
def get_registered_env_options() -> List[str]:
"""Returns list of environment options registered via register_env_option""""**/mezcla"/tpo/misc/programs/python/mezcla-devel-clone/mezcla/mezcla/tpo/misc/programs/python/mezcla-devel-clone/mezcla/tests/test_ipython_utils.py#! /usr/bin/env python3
#
# Test(s) for ../ipython_utils.py
#
# Notes:
# - For debugging the tested script, the ALLOW_SUBCOMMAND_TRACING environment
# option shows tracing output normally suppressed by unittest_wrapper.py.
# - This can be run as follows:
# $ PYTHONPATH=".:$PYTHONPATH" python ./mezcla/tests/test_ipython_utils.py
#
"""Tests for ipython_utils module"""
# Standard packages
import sys
## TODO: from typing import Optional
# Installed packages
import pytest
# Local packages
from mezcla.unittest_wrapper import TestWrapper, invoke_tests
from mezcla import debug
from mezcla import glue_helpers as gh
from mezcla import system
import mezcla.ipython_utils as THE_MODULE
#------------------------------------------------------------------------
class TestIt(TestWrapper):
"""Class for command-line based testcase definition"""
script_module = TestWrapper.get_testing_module_name(__file__, THE_MODULE)
def test_grep_obj_methods(self):
"""Test (module) object grepping"""
debug.trace(4, f"TestIt.test_grep_obj_methods(); self={self}")
import_functions = THE_MODULE.grep_obj_methods(THE_MODULE, "import_*")
assert ("import_module_globals" in import_functions)
leading_space_names = THE_MODULE.grep_obj_methods(THE_MODULE, "^ +")
assert (not leading_space_names)
return
@pytest.mark.xfail # TODO: remove xfail
def test_import_module_globals(self):
"""Test module globals import"""
debug.trace(4, f"TestIt.test_import_module_globals(); self={self}")
#
# Import this module (i.e., "mezcla.ipython_utils")
globals_dict = {}
THE_MODULE.import_module_globals(self.script_module, globals_dict=globals_dict)
assert ("TL" in globals_dict)
assert ("import_module_globals" in globals_dict)
#
# note: following fails because the module argument needs to be text (as above)
globals_dict = {}
THE_MODULE.import_module_globals(THE_MODULE, globals_dict=globals_dict, ignore_errors=True)
assert (not globals_dict)
return
@pytest.mark.xfail # TODO: remove xfail
def test_import_reload(self):
"""Test reload via import_module_globals"""
debug.trace(4, f"TestIt.test_import_module_globals(); self={self}")
# Make sure temp dir is current for sake of module loading
globals_dict = {}
temp_dir = self.get_temp_dir()
module_name = "_test_import_reload"
temp_file = gh.form_path(temp_dir, f"_{module_name}.py")
## BAD: system.set_current_directory(temp_dir)
## debug.assertion(temp_dir in sys.path)
self.monkeypatch.setattr(sys, "path", [temp_dir] + sys.path)
debug.assertion(temp_dir in sys.path)
# Test version 1 of module _test_import_reload
system.write_file(temp_file, "a=1")
THE_MODULE.import_module_globals(module_name, globals_dict=globals_dict)
assert ("a" in globals_dict)
assert ("b" not in globals_dict)
# Test version 2 of module _test_import_reload
gh.rename_file(temp_file, temp_file + ".old")
system.write_file(temp_file, "a=1\nb=1")
THE_MODULE.import_module_globals(module_name, globals_dict=globals_dict)
assert ("b" in globals_dict)
@pytest.mark.xfail # TODO: remove xfail
def test_pr_dir(self):
"""Makes sure object directory printed"""
# Sample output:
# In [67]: pr_dir(Dummy())
# ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'dummy_member']
#
class Dummy():
"""Dummy class for testing pr_dir"""
dummy_member = True
#
dummy_instance = Dummy()
THE_MODULE.pr_dir(dummy_instance)
stdout = self.get_stdout()
assert "dummy_member" in stdout
assert "'__class__'" in stdout
#------------------------------------------------------------------------
if __name__ == '__main__':
debug.trace_current_context()
invoke_tests(__file__)
/tpo/misc/programs/python/mezcla-devel-clone/mezcla/mezcla#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Command line interface (CLI) for version info, etc.
#
# Note:
# - Based on wrapper scripts from Anaconda (e.g., ~/anaconda3/envs/nlp-py-3-9/bin/python/pytest).
# - This is currently just used to trace out path and version info.
# - A warning is shown if invoked in non-debug mode.
#
## UPDATE 29 Aug 26: uses new client arg to mezcla_main
#
"""Wrapper for mezcla module info display"""
import re
import sys
from pathlib import Path
if __name__ == '__main__':
# Ensure this checkout of mezcla is used (not another installed copy).
repo_root = str(Path(__file__).resolve().parent.parent)
sys.path.insert(0, repo_root)
# Invoke the package entry point in mezcla.__main__.
# note: applies standard workaround for Windows invocation quirks
from mezcla import debug
from mezcla.__main__ import main as mezcla_main
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
##
## OLD:
## skip_warnings = debug.debugging()
## sys.exit(mezcla_main(omit_warnings=skip_warnings))
##
sys.exit(mezcla_main(client=True))
"^from mezcla import system|^import mezcla\.system|^from mezcla import debug|^import mezcla\.debug|system\.|importlib" (mezcla/debug.py)/tpo/misc/programs/python/mezcla-devel-clone/mezcla/debug.py:10:# imports standard packages. In particular, system.py is not imported,
/tpo/misc/programs/python/mezcla-devel-clone/mezcla/debug.py:284: # Note: version like one from system.py to avoid circular dependency
/tpo/misc/programs/python/mezcla-devel-clone/mezcla/debug.py:1553: """Version of system.getenv_bool w/o tracing"""
/tpo/misc/programs/python/mezcla-devel-clone/mezcla/debug.py:1562: """Version of system.getenv_int w/o tracing""""getenv_bool\(|def getenv_bool|def getenv_text|DEBUG_LEVEL" (mezcla/system.py)/tpo/misc/programs/python/mezcla-devel-clone/mezcla/system.py:229:def getenv_text(
/tpo/misc/programs/python/mezcla-devel-clone/mezcla/system.py:325:def getenv_bool(
/tpo/misc/programs/python/mezcla-devel-clone/mezcla/system.py:341: # EX: getenv_bool("bad env var", None) => False
/tpo/misc/programs/python/mezcla-devel-clone/mezcla/system.py:342: # EX: getenv_bool("bad env var", None, allow_none=True) is None
/tpo/misc/programs/python/mezcla-devel-clone/mezcla/system.py:355: debug.trace_fmtd(5, "getenv_bool({v}, {d}) => {r}",
/tpo/misc/programs/python/mezcla-devel-clone/mezcla/system.py:1677: ## TODO: # Register DEBUG_LEVEL for sake of new users
/tpo/misc/programs/python/mezcla-devel-clone/mezcla/system.py:1678: ## test_debug_level = getenv_integer("DEBUG_LEVEL", debug.get_level(),$ PYTHONPATH=. python -c 'import mezcla; print("EXPORTS", mezcla.__all__); print("DEBUG", hasattr(mezcla, "debug"))' 2>&1 | head -80; printf '\n--- skip ---\n'; SKIP_COMMON_EXPORT=1 PYTHONPATH=. python -c 'import mezcla; print("EXPORTS", mezcla.__all__); print("DEBUG", hasattr(mezcla, "debug"))' 2>&1 | head -40; printf '\n--- module CLI ---\n'; PYTHONPATH=. DEBUG_LEVEL=4 python -m mezcla 2>&1 | head -60; printf '\n--- script CLI ---\n'; PYTHONPATH=. DEBUG_LEVEL=4 mezcla/mezcla 2>&1 | head -60EXPORTS ['__VERSION__', 'debug', 'gh', 'my_re', 'system', 'TL']
DEBUG True
--- skip ---
EXPORTS ['__VERSION__']
DEBUG False
--- module CLI ---
in debug_init(force=False); DEBUG_LEVEL=4; 2026-09-23 20:23:28.251069
sys.argv=['-m'];
[/tpo/misc/programs/python/mezcla-devel-clone/mezcla/debug.py] loaded at 2026-09-23 20:23:28.352299
trace_level=4; output_timestamps=False
shadow_details={'shadowed': False, 'package': 'mezcla', 'current_pkg_dir': '/tpo/misc/programs/python/mezcla-devel-clone/mezcla', 'current_index': 0, 'ahead_index': 0, 'ahead_pkg_dir': '/tpo/misc/programs/python/mezcla-devel-clone/mezcla', 'script_path': '/tpo/misc/programs/python/mezcla-devel-clone/-m'};
skip_atexit=False
getenv_text('ROUNDING_PRECISION', '3') => '3'
getenv_number(ROUNDING_PRECISION, 3) => 3
starting tpo_common.py at 2026-09-23 20:23:28.623228: debug_level=4; args=['-m']
getenv_text('SKIP_FORMAT_WARNING', 'False') => 'False'
getenv_boolean(SKIP_FORMAT_WARNING, False) => False
my_regex.__init__(): self=<mezcla.my_regex.regex_wrapper object at 0x709a1d355510>
Main.__init__(): self=<mezcla.main.Main object at 0x709a1d39df10>
version_text: '2.3.3'
remaining version_text: 3.3
Component 1: '2'
new_version_text: '2.'
remaining version_text: 3
Component 2: '0003'
new_version_text: '2.0003'
remaining version_text:
Component 3: '0003'
new_version_text: '2.00030003'
version_to_number(2.3.3) => 2.00030003
version_text: '1.3.0'
remaining version_text: 3.0
Component 1: '1'
new_version_text: '1.'
remaining version_text: 0
Component 2: '0003'
new_version_text: '1.0003'
remaining version_text:
Component 3: '0000'
new_version_text: '1.00030000'
version_to_number(1.3.0) => 1.0003
unittest_wrapper.init_temp_settings()
os.environ.get(PRESERVE_TEMP_FILE_LABEL)='1'
os.environ.get(PRESERVE_TEMP_FILE_LABEL)='1'
Main.__init__(): self=<mezcla.main.Main object at 0x709a1cc16f10>
Warning: /tpo/misc/programs/python/mezcla-devel-clone/mezcla/__main__.py is not intended as standalone.
Version: 1.4.0.8
Install path: /tpo/misc/programs/python/mezcla-devel-clone/mezcla
Likewise for the package (e.g., via 'python -m mezcla')
[/tpo/misc/programs/python/mezcla-devel-clone/mezcla/debug.py] unloaded at 2026-09-23 20:23:28.812834; elapsed=0.562s
FYI: mezcla using ipython_utils imports: debug, system, etc.; disable via SKIP_COMMON_EXPORT
--- script CLI ---
in debug_init(force=False); DEBUG_LEVEL=4; 2026-09-23 20:23:29.880749
mezcla/mezcla
sys.argv=['mezcla/mezcla'];
[/tpo/misc/programs/python/mezcla-devel-clone/mezcla/debug.py] loaded at 2026-09-23 20:23:29.977760
trace_level=4; output_timestamps=False
shadow_details={'shadowed': False, 'package': 'mezcla', 'current_pkg_dir': '/tpo/misc/programs/python/mezcla-devel-clone/mezcla', 'current_index': 0, 'ahead_index': 0, 'ahead_pkg_dir': '/tpo/misc/programs/python/mezcla-devel-clone/mezcla', 'script_path': '/tpo/misc/programs/python/mezcla-devel-clone/mezcla/mezcla'};
skip_atexit=False
getenv_text('ROUNDING_PRECISION', '3') => '3'
getenv_number(ROUNDING_PRECISION, 3) => 3
starting tpo_common.py at 2026-09-23 20:23:30.228132: debug_level=4; args=['mezcla/mezcla']
getenv_text('SKIP_FORMAT_WARNING', 'False') => 'False'
getenv_boolean(SKIP_FORMAT_WARNING, False) => False
my_regex.__init__(): self=<mezcla.my_regex.regex_wrapper object at 0x763daea10410>
Main.__init__(): self=<mezcla.main.Main object at 0x763dae85ce90>
version_text: '2.3.3'
remaining version_text: 3.3
Component 1: '2'
new_version_text: '2.'
remaining version_text: 3
Component 2: '0003'
new_version_text: '2.0003'
remaining version_text:
Component 3: '0003'
new_version_text: '2.00030003'
version_to_number(2.3.3) => 2.00030003
version_text: '1.3.0'
remaining version_text: 3.0
Component 1: '1'
new_version_text: '1.'
remaining version_text: 0
Component 2: '0003'
new_version_text: '1.0003'
remaining version_text:
Component 3: '0000'
new_version_text: '1.00030000'
version_to_number(1.3.0) => 1.0003
unittest_wrapper.init_temp_settings()
os.environ.get(PRESERVE_TEMP_FILE_LABEL)='1'
os.environ.get(PRESERVE_TEMP_FILE_LABEL)='1'
Main.__init__(): self=<mezcla.main.Main object at 0x763dae0aa9d0>
Version: 1.4.0.8
Install path: /tpo/misc/programs/python/mezcla-devel-clone/mezcla
FYI: mezcla using ipython_utils imports: debug, system, etc.; disable via SKIP_COMMON_EXPORT
[/tpo/misc/programs/python/mezcla-devel-clone/mezcla/debug.py] unloaded at 2026-09-23 20:23:30.427909; elapsed=0.547s
<shellId: 3 completed with exit code 0>/tpo/misc/programs/python/mezcla-devel-clone/mezcla/debug.py (lines 1-28)#! /usr/bin/env python3
#
# Functions for debugging, such as console tracing. This is for intended
# for verbose tracing not suitable for the logging facility.
#
# Notes:
# - These are no-op's unless __debug__ is True.
# - Running python with the -O (optimized) option ensures that __debug__ is False.
# - So that other local packages can use tracing freely, this only
# imports standard packages. In particular, system.py is not imported,
# so functionality must be reproduced here (e.g., _to_utf8).
# - Gotta hate Pythonista's who prevailed in Python3 breaking lots of Python2
# code just for the sake of simplicity, a la manera moronista (i.e., only one moronic way to do things)!
# - A few functions from system are re-implemented here without tracing to
# avoid circular dependencies (e.g., _to_utf8).
# - For f-string syntax, see following:
# https://docs.python.org/3/tutorial/inputoutput.html
# https://www.python.org/dev/peps/pep-0498
#
# Usage examples:
#
# - casual usage (quick-n-dirty debugging)
#
# from mezcla import debug
# debug.trace_expr(4, dir())
#
# - long-term usuage (e.g., symbolic constants for consistency across scripts)
#/tpo/misc/programs/python/mezcla-devel-clone/mezcla/debug.py (lines 268-295) module_file = __file__ # file name for module script
use_old_introspection = True # use old-style introspection (temp enabled until debug_init)
#
try:
trace_level_text = os.environ.get(DEBUG_LEVEL_LABEL, "")
if trace_level_text.strip():
trace_level = int(trace_level_text)
except:
## sys.stderr.write("Warning: Unable to set tracing level from {v}: {exc}\n".
## format(v=DEBUG_LEVEL_LABEL, exc=sys.exc_info()))
pass
def _to_utf8(text: str) -> str:
"""Convert TEXT to UTF-8 (e.g., for I/O)"""
# Note: version like one from system.py to avoid circular dependency
result = text
##
## TODO?:
## if not isinstance(result, str):
## if debugging(7):
## sys.stderr.write(f"Warning: _to_utf8 called with non-string: {result!r}")
## result = str(result)
##
## NOTE: python 2 is deprecated and to avoid errors with mypy, python 2 code was removed
## if ((sys.version_info.major < 3) and (isinstance(text, unicode))): # pylint: disable=undefined-variable
## result = result.encode("UTF-8", 'ignore')/tpo/misc/programs/python/mezcla-devel-clone/mezcla/debug.py (lines 1540-1575) return result
def detailed_debugging() -> bool:
"""Whether debugging with trace level DETAILED (4) or higher"""
return (get_level() >= DETAILED)
def verbose_debugging() -> bool:
"""Whether debugging with trace level VERBOSE (5) or higher"""
return (get_level() >= VERBOSE)
def _getenv_bool(name: str, default_value: bool) -> bool:
"""Version of system.getenv_bool w/o tracing"""
## EX: os.setenv("FU", "1"); _getenv_bool("FU", False)) => True
result = default_value
if (str(os.environ.get(name) or default_value).upper() in ["1", "TRUE"]):
result = True
return result
def _getenv_int(name: str, default_value: int) -> int:
"""Version of system.getenv_int w/o tracing"""
result = default_value
try:
env_value = os.environ.get(name)
if env_value is not None:
result = int(env_value)
except:
_print_exception_info("_getenv_int")
return result
@docstring_parameter(max_len=max_trace_value_len)
def format_value(value: Any, max_len: Optional[int] = None,
strict: Optional[bool] = None, skip_sanity_checks: Optional[bool] = None) -> str:
"""Format arbitrary VALUE for output with trace_values, etc.: truncates if too long and encodes newlines/tpo/misc/programs/python/mezcla-devel-clone/mezcla/system.py (lines 220-365) debug.trace_fmtd(5, "setenv({v}, {val})", v=var, val=value)
debug.assertion(value is not None)
if normalize:
## OLD: var = var.replace("-", "_").upper()
var = normalize_env_var(var)
os.environ[var] = str(value)
return
def getenv_text(
var: str,
default: Optional[str] = None,
description: str = "",
desc: str = "",
helper: bool = False,
update: Optional[bool] = None,
skip_register: Optional[bool] = None,
normalize: Optional[bool] = None,
) -> str:
"""Returns textual value for environment variable VAR (or DEFAULT value, excluding None).
Notes:
- Use getenv_value if default can be None, as result is always a string.
- HELPER indicates that this call is in support of another getenv-type function (e.g., getenv_bool), so that tracing is only shown at higher verbosity level (e.g., 6 not 5).
- DESCRIPTION used for get_environment_option_descriptions.
- If UPDATE, then the environment is modified with value (e.g., based on default).
- If SKIP_REGISTER, the variable info is not recorded (see env_options global).
- If NORMALIZE, then lookup falls back to variable uppercased and with underscores for dashes.
"""
# Note: default is empty string to ensure result is string (not NoneType)
## TODO: add way to block registration
if not skip_register:
register_env_option(var, description or desc, default)
if default is None:
debug.trace(4, f"Warning: getenv_text treats default None as ''; consider using getenv_value for '{var}' instead")
default = ""
# Get value, falling back to underscores instead of dashes
in_var = var
value = os.getenv(var)
if (value is None):
if normalize and re.search("[a-z-]", var):
var = var.replace("-", "_").upper()
value = os.getenv(var, default)
level = 5 if value else 7
debug.trace(level, f"FYI: Normalized env.var {in_var!r} to {var!r}")
if (value is None):
value = default
## TODO?: if ((not helper and (text_value is None)) or (not text_value)):
text_value = value
if (text_value is None):
debug.trace_fmtd(6, "getenv_text: no value for var {v}", v=var)
text_value = default
# Optionally, update the environment (n.b., always normalizes)
if update:
setenv(var, text_value, normalize=True)
trace_level = 6 if helper else 5
## DEBUG: sys.stderr.write("debug.trace_fmtd({trace_level} \"getenv_text('{v}', [def={dft}], [desc={desc}], [helper={hlpr}]) => {r}\"".format(trace_level=trace_level, v=var, dft=default, desc=description, hlpr=helper, r=text_value))
debug.trace_fmtd(trace_level, "getenv_text('{v}', [def={dft}], [desc={desc}], [helper={hlpr}]) => {r}",
v=in_var, dft=default, desc=description, hlpr=helper, r=text_value)
return (text_value)
## OLD: default: Optional[Any] = None (redundant: Any already subsumes None)
def getenv_value(
var: str,
default: Any = None,
description: str = "",
desc: str = "",
update: Optional[bool] = None,
skip_register: Optional[bool] = None,
normalize: Optional[bool] = None,
) -> Any:
"""Returns environment value for VAR as string or DEFAULT (can be None), with optional DESCRIPTION and env. UPDATE. (See getenv_text for option details.)
Note: If NORMALIZE, then lookup falls back to variable uppercased and with underscores for dashes.
"""
# EX: getenv_value("bad env var") is None
# TODO2: reconcile with getenv_value (e.g., via common helper); add way to set normalization as default
if not skip_register:
register_env_option(var, description or desc, default)
# Get value, falling back to underscores instead of dashes
in_var = var
value = os.getenv(var)
if (value is None):
if normalize and re.search("[a-z-]", var):
var = var.replace("-", "_").upper()
value = os.getenv(var, default)
level = 5 if value else 7
debug.trace(level, f"FYI: Normalized env.var {in_var!r} to {var!r}")
if (value is None):
value = default
# Optionally, update the environment (n.b., always normalizes)
if update:
setenv(var, value, normalize=True)
# note: uses !r for repr()
debug.trace_fmtd(5, "getenv_value({v!r}, [def={dft!r}], [desc={dsc!r}]]) => {val!r}",
v=var, dft=default, dsc=(description or desc), val=value)
return (value)
DEFAULT_GETENV_BOOL = False
#
def getenv_bool(
var: str,
default: bool = DEFAULT_GETENV_BOOL,
description: str = "",
desc: str = "",
allow_none: Optional[bool] = False,
update: Optional[bool] = None,
skip_register: Optional[bool] = None,
**kwargs
) -> bool:
"""Returns boolean flag based on environment VAR (or DEFAULT value), with optional DESCRIPTION and env. UPDATE
Note:
- "0" or "False" is interpreted as False, and any other explicit value as True (e.g., None => None)
- In general, it is best to use False as default instead of True, because getenv_bool is meant for environment overrides, not defaults.
- TODO2: Return is a bool unless ALLOW_NONE; defaults to False.
"""
# EX: getenv_bool("bad env var", None) => False
# EX: getenv_bool("bad env var", None, allow_none=True) is None
# TODO: * Add debugging sanity checks for type of default to help diagnose when incorrect getenv_xyz variant used (e.g., getenv_int("USE_FUBAR", False) => ... getenv_bool)!
bool_value = default
value_text = getenv_value(var, description=description, desc=desc, default=default, update=update, skip_register=skip_register, **kwargs)
if (isinstance(value_text, str) and value_text.strip()):
bool_value = to_bool(value_text)
if not isinstance(bool_value, bool):
if (bool_value is None):
bool_value = False if (not allow_none) else None
else:
## OLD: debug.assertion(bool_value != default, f"Check {var!r} default {default!r}")
bool_value = to_bool(bool_value)
debug.assertion(isinstance(bool_value, bool) or allow_none)
debug.trace_fmtd(5, "getenv_bool({v}, {d}) => {r}",
v=var, d=default, r=bool_value)
return (bool_value)
#
getenv_boolean = getenv_bool
def getenv_number(
var: str,
default: float = -1.0,
description: str = "",$ PYTHONPATH=. python -c 'import mezcla; print("ipython_utils loaded:", "mezcla.ipython_utils" in __import__("sys").modules)' && SKIP_COMMON_EXPORT=0 PYTHONPATH=. python -c 'import mezcla; print("exports:", mezcla.__all__)' && SKIP_COMMON_EXPORT=false PYTHONPATH=. python -c 'import mezcla; print("exports:", mezcla.__all__)'ipython_utils loaded: True
exports: ['__VERSION__']
exports: ['__VERSION__']
<shellId: 4 completed with exit code 0>Primary regression: mezcla/__init__.py:74 tests the function object instead of invoking it:
if _in_ipython and not skip_common_export:This is always truthy when SKIP_COMMON_EXPORT is unset. Consequently, a plain import mezcla imports ipython_utils, including optional scientific packages, Main, and its interactive initialization. I confirmed that mezcla.ipython_utils is loaded outside IPython. Change this to _in_ipython() and add a subprocess regression test for a normal Python interpreter.
Other focused improvements:
Make the hook explicit rather than implicit.
ipython_utilsis a large interactive bootstrap, so importing it from package initialization makesimport mezclacontext-dependent and opaque. Prefer keeping__init__.pymetadata-only and having the IPython startup explicitly run an opt-in function, e.g.mezcla.enable_ipython_exports(), or requireMEZCLA_IPYTHON_EXPORTS=1. If automatic behavior is retained, expose a clear state such asmezcla.IPYTHON_EXPORTS_ENABLEDand write the diagnostic tostderr.Use a light, shared stdlib-only import helper. The duplication in
debug.pyandsystem.pyis justified becausesystemimportsdebug, whiledebugintentionally avoids it (debug.py:8-16). Do not solve the hook by importing either module from__init__. Instead, extract only dependency-free primitives—active-IPython detection and environment-boolean parsing—into a tiny stdlib-only module. Bothdebugand__init__can safely import that helper without forming thedebug ↔ systemcycle.Avoid broad, inverted exception behavior.
__init__.py:82-87catches every exception, leaves a partially initialized package, and only re-raises underpython -O. The comment says it “swallows the exception unless production,” but normal execution is the swallowing case. Catch expected dependency/import exceptions specifically, retain the original exception as diagnostic context, and either fail clearly or deliberately disable the optional feature with a deterministic warning.Parse
SKIP_COMMON_EXPORTas a boolean. The currentos.environ.get()treats"0"and"false"as enabled skip values. That differs fromsystem.getenv_bool()’s documented semantics. A stdlib-only local parser or the proposed shared helper should recognize at least1/true/yes/onand0/false/no/off, rejecting invalid values visibly.Tighten active-IPython detection.
_in_ipython()falls back to"IPython" in sys.modules, which can be true merely because a library imported IPython—not because the code runs in an interactive shell. Prefer a successful callableget_ipython()result, optionally checking that its shell object is non-None; do not use module presence as an “active session” proxy.Align the two entry points.
python -m mezclacallsmain()withoutclient=True, so it emits “not intended as standalone” even thoughmezcla/__main__.pyis specifically the package entry point. Themezclascript does passclient=True. Replace the ambiguousclient/omit_warningscoupling with explicit parameters such asshow_warningandalways_show_version, and have both entry points use the same intended mode. Also,mezcla/mezcla:20importsdebugonly for commented-out legacy code; removing that import would make the wrapper’s dependency path clearer.
Useful regression coverage would verify: normal imports do not load ipython_utils; a simulated active IPython session follows the documented opt-in policy; boolean environment values behave consistently; and python -m mezcla and mezcla/mezcla have intentionally matching output/exit behavior.