1010"""
1111
1212import builtins
13+ import contextlib
1314import logging
1415import os
1516import sys
1617from typing import Any
1718
1819from dbx_patch .models import PatchResult
19- from dbx_patch .utils .logger import get_logger
2020
2121_PATCH_APPLIED = False
2222_REGISTERED_CHECK : Any = None
2323_ORIGINAL_BUILTINS_IMPORT : Any = None
2424_IMPORT_PATCH_APPLIED = False
25- _CACHED_LOGGER : Any = None
2625
26+ # Module-level cached logger
27+ _logger : Any = None
2728
28- def _get_cached_logger () -> Any :
29- """Get cached logger instance to avoid import loops."""
30- global _CACHED_LOGGER
31- if _CACHED_LOGGER is None :
32- try :
33- _CACHED_LOGGER = get_logger ()
34- except Exception : # noqa: S110
35- pass # Fail silently if logger can't be imported
36- return _CACHED_LOGGER
29+
30+ def _get_logger () -> Any :
31+ """Get module-level cached logger instance."""
32+ global _logger
33+ if _logger is None :
34+ with contextlib .suppress (Exception ):
35+ from dbx_patch .utils .logger import get_logger
36+
37+ _logger = get_logger ()
38+ return _logger
3739
3840
3941def _editable_path_check (fname : str ) -> bool :
@@ -56,13 +58,10 @@ def _editable_path_check(fname: str) -> bool:
5658 result = any (fname .startswith (editable_path ) for editable_path in editable_paths )
5759
5860 # Debug logging
59- logger = _get_cached_logger ()
60- if logger :
61- debug_msg = f"Autoreload check: { fname } -> { result } "
62- if result :
63- matching = [p for p in editable_paths if fname .startswith (p )]
64- debug_msg += f" (matched: { matching [0 ] if matching else 'unknown' } )"
65- logger .debug (debug_msg )
61+ logger = _get_logger ()
62+ if logger and result :
63+ matching = [p for p in editable_paths if fname .startswith (p )]
64+ logger .debug (f"Autoreload check: { fname } -> { result } (matched: { matching [0 ] if matching else 'unknown' } )" )
6665
6766 return result
6867
@@ -80,7 +79,7 @@ def _patched_builtins_import(name: str, *args: Any, **kwargs: Any) -> Any:
8079 Returns:
8180 The imported module
8281 """
83- logger = _get_cached_logger ()
82+ logger = _get_logger ()
8483 if logger :
8584 logger .debug (f"Importing: { name } (args={ args } , kwargs={ kwargs } )" )
8685
@@ -115,18 +114,19 @@ def patch_autoreload_hook(verbose: bool = True) -> PatchResult:
115114 PatchResult with operation details
116115 """
117116 global _PATCH_APPLIED , _REGISTERED_CHECK , _ORIGINAL_BUILTINS_IMPORT , _IMPORT_PATCH_APPLIED
118- logger = get_logger ()
117+ logger = _get_logger ()
119118
120119 # Patch builtins.__import__ for debug logging if in debug mode
121- if logger ._logger .isEnabledFor (logging .DEBUG ) and not _IMPORT_PATCH_APPLIED :
120+ if logger and logger ._logger .isEnabledFor (logging .DEBUG ) and not _IMPORT_PATCH_APPLIED :
122121 logger .info ("Debug logging enabled - patching builtins.__import__ for debug logging..." )
123122 _ORIGINAL_BUILTINS_IMPORT = builtins .__import__
124123 builtins .__import__ = _patched_builtins_import # type: ignore[assignment]
125124 _IMPORT_PATCH_APPLIED = True
126125 logger .info ("builtins.__import__ patched for debug logging" )
127126
128127 if _PATCH_APPLIED :
129- logger .info ("Autoreload hook patch already applied." )
128+ if logger :
129+ logger .info ("Autoreload hook patch already applied." )
130130 from dbx_patch .pth_processor import get_editable_install_paths
131131
132132 editable_paths = get_editable_install_paths ()
@@ -140,54 +140,59 @@ def patch_autoreload_hook(verbose: bool = True) -> PatchResult:
140140
141141 try :
142142 # Import the autoreload module
143- from dbruntime .autoreload .file_module_utils import ( # pyright: ignore[reportMissingImports ]
143+ from dbruntime .autoreload .file_module_utils import ( # ty: ignore[unresolved-import ]
144144 register_autoreload_allowlist_check ,
145145 )
146146
147- logger .info ("Autoreload file_module_utils found, registering editable path check..." )
147+ if logger :
148+ logger .info ("Autoreload file_module_utils found, registering editable path check..." )
148149
149150 from dbx_patch .pth_processor import get_editable_install_paths
150151
151152 editable_paths = get_editable_install_paths ()
152153
153- logger .info (f"Patching autoreload hook to allow { len (editable_paths )} editable install path(s)..." )
154+ if logger :
155+ logger .info (f"Patching autoreload hook to allow { len (editable_paths )} editable install path(s)..." )
154156
155157 # Debug: Log the current allowlist checks
156- try :
157- from dbruntime .autoreload .file_module_utils import ( # pyright: ignore[reportMissingImports]
158- _AUTORELOAD_ALLOWLIST_CHECKS ,
159- )
158+ if logger :
159+ try :
160+ from dbruntime .autoreload .file_module_utils import ( # ty:ignore[unresolved-import]
161+ _AUTORELOAD_ALLOWLIST_CHECKS ,
162+ )
160163
161- logger .info (f"Current allowlist checks before patch: { len (_AUTORELOAD_ALLOWLIST_CHECKS )} " )
162- except Exception as e : # noqa: BLE001
163- logger .debug (f"Could not access allowlist checks: { e } " )
164+ logger .info (f"Current allowlist checks before patch: { len (_AUTORELOAD_ALLOWLIST_CHECKS )} " )
165+ except Exception as e : # noqa: BLE001
166+ logger .debug (f"Could not access allowlist checks: { e } " )
164167
165168 # Register our check function
166169 _REGISTERED_CHECK = _editable_path_check
167170 register_autoreload_allowlist_check (_REGISTERED_CHECK )
168171
169172 # Debug: Log the allowlist checks after registration
170- try :
171- from dbruntime .autoreload .file_module_utils import ( # pyright: ignore[reportMissingImports]
172- _AUTORELOAD_ALLOWLIST_CHECKS ,
173- )
173+ if logger :
174+ try :
175+ from dbruntime .autoreload .file_module_utils import ( # ty:ignore[unresolved-import]
176+ _AUTORELOAD_ALLOWLIST_CHECKS ,
177+ )
174178
175- logger .info (f"Current allowlist checks after patch: { len (_AUTORELOAD_ALLOWLIST_CHECKS )} " )
176- except Exception as e : # noqa: BLE001
177- logger .debug (f"Could not access allowlist checks: { e } " )
179+ logger .info (f"Current allowlist checks after patch: { len (_AUTORELOAD_ALLOWLIST_CHECKS )} " )
180+ except Exception as e : # noqa: BLE001
181+ logger .debug (f"Could not access allowlist checks: { e } " )
178182
179183 _PATCH_APPLIED = True
180184
181- logger .success ("Autoreload hook patched successfully!" )
182- if editable_paths :
183- with logger .indent ():
184- logger .info ("Allowing imports from editable paths:" )
185- for path in sorted (editable_paths ):
186- logger .info (f"- { path } " )
187- else :
188- with logger .indent ():
189- logger .warning ("No editable install paths found yet." )
190- logger .info ("Run 'pip install -e .' first, then reapply patches." )
185+ if logger :
186+ logger .success ("Autoreload hook patched successfully!" )
187+ if editable_paths :
188+ with logger .indent ():
189+ logger .info ("Allowing imports from editable paths:" )
190+ for path in sorted (editable_paths ):
191+ logger .info (f"- { path } " )
192+ else :
193+ with logger .indent ():
194+ logger .warning ("No editable install paths found yet." )
195+ logger .info ("Run 'pip install -e .' first, then reapply patches." )
191196
192197 return PatchResult (
193198 success = True ,
@@ -198,21 +203,23 @@ def patch_autoreload_hook(verbose: bool = True) -> PatchResult:
198203 )
199204
200205 except ImportError as e :
201- logger .warning (f"Could not import autoreload modules: { e } " )
202- with logger .indent ():
203- logger .info ("This is normal if not running in Databricks environment." )
204- logger .info ("The autoreload hook is only present in Databricks runtime." )
206+ if logger :
207+ logger .warning (f"Could not import autoreload modules: { e } " )
208+ with logger .indent ():
209+ logger .info ("This is normal if not running in Databricks environment." )
210+ logger .info ("The autoreload hook is only present in Databricks runtime." )
205211 return PatchResult (
206212 success = False ,
207213 already_patched = False ,
208214 hook_found = False ,
209215 )
210216 except Exception as e :
211- logger .error (f"Error patching autoreload hook: { e } " ) # noqa: TRY400
212- import traceback
217+ if logger :
218+ logger .error (f"Error patching autoreload hook: { e } " ) # noqa: TRY400
219+ import traceback
213220
214- with logger .indent ():
215- logger .info (f"Traceback: { traceback .format_exc ()} " )
221+ with logger .indent ():
222+ logger .info (f"Traceback: { traceback .format_exc ()} " )
216223 return PatchResult (
217224 success = False ,
218225 already_patched = False ,
@@ -230,7 +237,7 @@ def unpatch_autoreload_hook(verbose: bool = True) -> bool:
230237 True if unpatch was successful, False otherwise
231238 """
232239 global _PATCH_APPLIED , _REGISTERED_CHECK , _IMPORT_PATCH_APPLIED , _ORIGINAL_BUILTINS_IMPORT
233- logger = get_logger ()
240+ logger = _get_logger ()
234241
235242 success = True
236243
@@ -247,23 +254,29 @@ def unpatch_autoreload_hook(verbose: bool = True) -> bool:
247254 _REGISTERED_CHECK = None
248255 _PATCH_APPLIED = False
249256
250- logger .success ("Autoreload hook patch removed successfully." )
257+ if logger :
258+ logger .success ("Autoreload hook patch removed successfully." )
251259 else :
252- logger .warning ("Check function not saved, cannot unpatch." )
260+ if logger :
261+ logger .warning ("Check function not saved, cannot unpatch." )
253262 success = False
254263
255264 except Exception as e :
256- logger .error (f"Error removing patch: { e } " ) # noqa: TRY400
265+ if logger :
266+ logger .error (f"Error removing patch: { e } " ) # noqa: TRY400
257267 success = False
258268 else :
259- logger .info ("No allowlist patch to remove." )
269+ if logger :
270+ logger .info ("No allowlist patch to remove." )
260271
261272 # Unpatch builtins.__import__ if it was patched
262273 if _IMPORT_PATCH_APPLIED and _ORIGINAL_BUILTINS_IMPORT is not None :
263- logger .info ("Restoring original builtins.__import__..." )
274+ if logger :
275+ logger .info ("Restoring original builtins.__import__..." )
264276 builtins .__import__ = _ORIGINAL_BUILTINS_IMPORT # type: ignore[assignment]
265277 _IMPORT_PATCH_APPLIED = False
266- logger .success ("builtins.__import__ restored." )
278+ if logger :
279+ logger .success ("builtins.__import__ restored." )
267280
268281 return success
269282
0 commit comments