| 1 |
from __future__ import annotations |
| 2 |
import ast |
| 3 |
import builtins |
| 4 |
import contextlib |
| 5 |
import itertools |
| 6 |
import logging |
| 7 |
import os |
| 8 |
import pickle |
| 9 |
import platform |
| 10 |
import sys |
| 11 |
import textwrap |
| 12 |
from types import ModuleType |
| 13 |
from typing import TYPE_CHECKING, Any, NamedTuple, cast |
| 14 |
from collections.abc import Generator, Iterable |
| 15 |
|
| 16 |
from IPython.extensions.deduperreload.deduperreload_patching import ( |
| 17 |
DeduperReloaderPatchingMixin, |
| 18 |
) |
| 19 |
|
| 20 |
if TYPE_CHECKING: |
| 21 |
TDefinitionAst = ( |
| 22 |
ast.FunctionDef |
| 23 |
| ast.AsyncFunctionDef |
| 24 |
| ast.Import |
| 25 |
| ast.ImportFrom |
| 26 |
| ast.Assign |
| 27 |
| ast.AnnAssign |
| 28 |
) |
| 29 |
|
| 30 |
|
| 31 |
def get_module_file_name(module: ModuleType | str) -> str | None: |
| 32 |
"""Returns the module's file path, or the empty string if it's inaccessible""" |
| 33 |
if (mod := sys.modules.get(module) if isinstance(module, str) else module) is None: |
| 34 |
return "" |
| 35 |
return getattr(mod, "__file__", "") or "" |
| 36 |
|
| 37 |
|
| 38 |
def compare_ast(node1: ast.AST | list[ast.AST], node2: ast.AST | list[ast.AST]) -> bool: |
| 39 |
"""Checks if node1 and node2 have identical AST structure/values, apart from some attributes""" |
| 40 |
if type(node1) is not type(node2): |
| 41 |
return False |
| 42 |
|
| 43 |
if isinstance(node1, ast.AST): |
| 44 |
for k, v in node1.__dict__.items(): |
| 45 |
if k in ( |
| 46 |
"lineno", |
| 47 |
"end_lineno", |
| 48 |
"col_offset", |
| 49 |
"end_col_offset", |
| 50 |
"ctx", |
| 51 |
"parent", |
| 52 |
): |
| 53 |
continue |
| 54 |
if not hasattr(node2, k) or not compare_ast(v, getattr(node2, k)): |
| 55 |
return False |
| 56 |
return True |
| 57 |
|
| 58 |
elif isinstance(node1, list) and isinstance( # type:ignore [redundant-expr] |
| 59 |
node2, list |
| 60 |
): |
| 61 |
return len(node1) == len(node2) and all( |
| 62 |
compare_ast(n1, n2) for n1, n2 in zip(node1, node2) |
| 63 |
) |
| 64 |
else: |
| 65 |
return node1 == node2 |
| 66 |
|
| 67 |
|
| 68 |
class DependencyNode(NamedTuple): |
| 69 |
""" |
| 70 |
Each node represents a function. |
| 71 |
qualified_name: string which represents the namespace/name of the function |
| 72 |
abstract_syntax_tree: subtree of the overall module which corresponds to this function |
| 73 |
|
| 74 |
qualified_name is of the structure: (namespace1, namespace2, ..., name) |
| 75 |
|
| 76 |
For example, foo() in the following would be represented as (A, B, foo): |
| 77 |
|
| 78 |
class A: |
| 79 |
class B: |
| 80 |
def foo(): |
| 81 |
pass |
| 82 |
""" |
| 83 |
|
| 84 |
qualified_name: tuple[str, ...] |
| 85 |
abstract_syntax_tree: ast.AST |
| 86 |
|
| 87 |
|
| 88 |
class GatherResult(NamedTuple): |
| 89 |
import_defs: list[tuple[tuple[str, ...], ast.Import | ast.ImportFrom]] = [] |
| 90 |
assign_defs: list[tuple[tuple[str, ...], ast.Assign | ast.AnnAssign]] = [] |
| 91 |
function_defs: list[ |
| 92 |
tuple[tuple[str, ...], ast.FunctionDef | ast.AsyncFunctionDef] |
| 93 |
] = [] |
| 94 |
classes: dict[str, ast.ClassDef] = {} |
| 95 |
unfixable: list[ast.AST] = [] |
| 96 |
|
| 97 |
@classmethod |
| 98 |
def create(cls) -> GatherResult: |
| 99 |
return cls([], [], [], {}, []) |
| 100 |
|
| 101 |
def all_defs(self) -> Iterable[tuple[tuple[str, ...], TDefinitionAst]]: |
| 102 |
return itertools.chain(self.import_defs, self.assign_defs, self.function_defs) |
| 103 |
|
| 104 |
def inplace_merge(self, other: GatherResult) -> None: |
| 105 |
self.import_defs.extend(other.import_defs) |
| 106 |
self.assign_defs.extend(other.assign_defs) |
| 107 |
self.function_defs.extend(other.function_defs) |
| 108 |
self.classes.update(other.classes) |
| 109 |
self.unfixable.extend(other.unfixable) |
| 110 |
|
| 111 |
|
| 112 |
class ConstexprDetector(ast.NodeVisitor): |
| 113 |
def __init__(self) -> None: |
| 114 |
self.is_constexpr = True |
| 115 |
self._allow_builtins_exceptions = True |
| 116 |
|
| 117 |
@contextlib.contextmanager |
| 118 |
def disallow_builtins_exceptions(self) -> Generator[None, None, None]: |
| 119 |
prev_allow = self._allow_builtins_exceptions |
| 120 |
self._allow_builtins_exceptions = False |
| 121 |
try: |
| 122 |
yield |
| 123 |
finally: |
| 124 |
self._allow_builtins_exceptions = prev_allow |
| 125 |
|
| 126 |
def visit_Attribute(self, node: ast.Attribute) -> None: |
| 127 |
with self.disallow_builtins_exceptions(): |
| 128 |
self.visit(node.value) |
| 129 |
|
| 130 |
def visit_Name(self, node: ast.Name) -> None: |
| 131 |
if self._allow_builtins_exceptions and hasattr(builtins, node.id): |
| 132 |
return |
| 133 |
self.is_constexpr = False |
| 134 |
|
| 135 |
def visit(self, node: ast.AST) -> None: |
| 136 |
if not self.is_constexpr: |
| 137 |
# can short-circuit if we've already detected that it's not a constexpr |
| 138 |
return |
| 139 |
super().visit(node) |
| 140 |
|
| 141 |
def __call__(self, node: ast.AST) -> bool: |
| 142 |
self.is_constexpr = True |
| 143 |
self.visit(node) |
| 144 |
return self.is_constexpr |
| 145 |
|
| 146 |
|
| 147 |
class AutoreloadTree: |
| 148 |
""" |
| 149 |
Recursive data structure to keep track of reloadable functions/methods. Each object corresponds to a specific scope level. |
| 150 |
children: classes inside given scope, maps class name to autoreload tree for that class's scope |
| 151 |
funcs_to_autoreload: list of function names that can be autoreloaded in given scope. |
| 152 |
new_nested_classes: Classes getting added in new autoreload cycle |
| 153 |
""" |
| 154 |
|
| 155 |
def __init__(self) -> None: |
| 156 |
self.children: dict[str, AutoreloadTree] = {} |
| 157 |
self.defs_to_reload: list[tuple[tuple[str, ...], ast.AST]] = [] |
| 158 |
self.defs_to_delete: set[str] = set() |
| 159 |
self.new_nested_classes: dict[str, ast.AST] = {} |
| 160 |
|
| 161 |
def traverse_prefixes(self, prefixes: list[str]) -> AutoreloadTree: |
| 162 |
""" |
| 163 |
Return ref to the AutoreloadTree at the namespace specified by prefixes |
| 164 |
""" |
| 165 |
cur = self |
| 166 |
for prefix in prefixes: |
| 167 |
if prefix not in cur.children: |
| 168 |
cur.children[prefix] = AutoreloadTree() |
| 169 |
cur = cur.children[prefix] |
| 170 |
return cur |
| 171 |
|
| 172 |
|
| 173 |
class DeduperReloader(DeduperReloaderPatchingMixin): |
| 174 |
""" |
| 175 |
This version of autoreload detects when we can leverage targeted recompilation of a subset of a module and patching |
| 176 |
existing function/method objects to reflect these changes. |
| 177 |
|
| 178 |
Detects what functions/methods can be reloaded by recursively comparing the old/new AST of module-level classes, |
| 179 |
module-level classes' methods, recursing through nested classes' methods. If other changes are made, original |
| 180 |
autoreload algorithm is called directly. |
| 181 |
""" |
| 182 |
|
| 183 |
def __init__(self) -> None: |
| 184 |
self._to_autoreload: AutoreloadTree = AutoreloadTree() |
| 185 |
self.source_by_modname: dict[str, str] = {} |
| 186 |
self.dependency_graph: dict[tuple[str, ...], list[DependencyNode]] = {} |
| 187 |
self._enabled = True |
| 188 |
|
| 189 |
@property |
| 190 |
def enabled(self) -> bool: |
| 191 |
return self._enabled and platform.python_implementation() == "CPython" |
| 192 |
|
| 193 |
@enabled.setter |
| 194 |
def enabled(self, value: bool) -> None: |
| 195 |
self._enabled = value |
| 196 |
|
| 197 |
def update_sources(self) -> None: |
| 198 |
""" |
| 199 |
Update dictionary source_by_modname with current modules' source codes. |
| 200 |
""" |
| 201 |
if not self.enabled: |
| 202 |
return |
| 203 |
for new_modname in sys.modules.keys() - self.source_by_modname.keys(): |
| 204 |
new_module = sys.modules[new_modname] |
| 205 |
if ( |
| 206 |
(fname := get_module_file_name(new_module)) is None |
| 207 |
or "site-packages" in fname |
| 208 |
or "dist-packages" in fname |
| 209 |
or not os.access(fname, os.R_OK) |
| 210 |
): |
| 211 |
self.source_by_modname[new_modname] = "" |
| 212 |
continue |
| 213 |
# Skip binary files (e.g., .so, .pyd, .pyo) |
| 214 |
if not fname.endswith(".py"): |
| 215 |
self.source_by_modname[new_modname] = "" |
| 216 |
continue |
| 217 |
try: |
| 218 |
with open(fname, "r", encoding="utf8") as f: |
| 219 |
self.source_by_modname[new_modname] = f.read() |
| 220 |
except Exception as e: |
| 221 |
logger = logging.getLogger("autoreload") |
| 222 |
logger.exception( |
| 223 |
f"Failed to read module file '{fname}' for module '{new_modname}': {type(e).__name__}" |
| 224 |
) |
| 225 |
self.source_by_modname[new_modname] = "" |
| 226 |
|
| 227 |
constexpr_detector = ConstexprDetector() |
| 228 |
|
| 229 |
@staticmethod |
| 230 |
def is_enum_subclass(node: ast.Module | ast.ClassDef) -> bool: |
| 231 |
if isinstance(node, ast.Module): |
| 232 |
return False |
| 233 |
for base in node.bases: |
| 234 |
if isinstance(base, ast.Name) and base.id == "Enum": |
| 235 |
return True |
| 236 |
elif ( |
| 237 |
isinstance(base, ast.Attribute) |
| 238 |
and base.attr == "Enum" |
| 239 |
and isinstance(base.value, ast.Name) |
| 240 |
and base.value.id == "enum" |
| 241 |
): |
| 242 |
return True |
| 243 |
return False |
| 244 |
|
| 245 |
@classmethod |
| 246 |
def is_constexpr_assign( |
| 247 |
cls, node: ast.AST, parent_node: ast.Module | ast.ClassDef |
| 248 |
) -> bool: |
| 249 |
if not isinstance(node, (ast.Assign, ast.AnnAssign)) or node.value is None: |
| 250 |
return False |
| 251 |
if cls.is_enum_subclass(parent_node): |
| 252 |
return False |
| 253 |
for target in node.targets if isinstance(node, ast.Assign) else [node.target]: |
| 254 |
if not isinstance(target, ast.Name): |
| 255 |
return False |
| 256 |
return cls.constexpr_detector(node.value) |
| 257 |
|
| 258 |
@classmethod |
| 259 |
def _gather_children( |
| 260 |
cls, body: list[ast.stmt], parent_node: ast.Module | ast.ClassDef |
| 261 |
) -> GatherResult: |
| 262 |
""" |
| 263 |
Given list of ast elements, return: |
| 264 |
1. dict mapping function names to their ASTs. |
| 265 |
2. dict mapping class names to their ASTs. |
| 266 |
3. list of any other ASTs. |
| 267 |
""" |
| 268 |
result = GatherResult.create() |
| 269 |
for ast_node in body: |
| 270 |
ast_elt: ast.expr | ast.stmt = ast_node |
| 271 |
while isinstance(ast_elt, ast.Expr): |
| 272 |
ast_elt = ast_elt.value |
| 273 |
if isinstance(ast_elt, (ast.FunctionDef, ast.AsyncFunctionDef)): |
| 274 |
result.function_defs.append(((ast_elt.name,), ast_elt)) |
| 275 |
elif isinstance(ast_elt, (ast.Import, ast.ImportFrom)): |
| 276 |
result.import_defs.append( |
| 277 |
(tuple(name.asname or name.name for name in ast_elt.names), ast_elt) |
| 278 |
) |
| 279 |
elif isinstance(ast_elt, ast.ClassDef): |
| 280 |
result.classes[ast_elt.name] = ast_elt |
| 281 |
elif isinstance(ast_elt, ast.If): |
| 282 |
result.unfixable.append(ast_elt.test) |
| 283 |
result.inplace_merge(cls._gather_children(ast_elt.body, parent_node)) |
| 284 |
result.inplace_merge(cls._gather_children(ast_elt.orelse, parent_node)) |
| 285 |
elif isinstance(ast_elt, (ast.AsyncWith, ast.With)): |
| 286 |
result.unfixable.extend(ast_elt.items) |
| 287 |
result.inplace_merge(cls._gather_children(ast_elt.body, parent_node)) |
| 288 |
elif isinstance(ast_elt, ast.Try): |
| 289 |
result.inplace_merge(cls._gather_children(ast_elt.body, parent_node)) |
| 290 |
result.inplace_merge(cls._gather_children(ast_elt.orelse, parent_node)) |
| 291 |
result.inplace_merge( |
| 292 |
cls._gather_children(ast_elt.finalbody, parent_node) |
| 293 |
) |
| 294 |
for handler in ast_elt.handlers: |
| 295 |
if handler.type is not None: |
| 296 |
result.unfixable.append(handler.type) |
| 297 |
result.inplace_merge( |
| 298 |
cls._gather_children(handler.body, parent_node) |
| 299 |
) |
| 300 |
elif not isinstance(ast_elt, (ast.Constant, ast.Pass)): |
| 301 |
if cls.is_constexpr_assign(ast_elt, parent_node): |
| 302 |
assert isinstance(ast_elt, (ast.Assign, ast.AnnAssign)) |
| 303 |
targets = ( |
| 304 |
ast_elt.targets |
| 305 |
if isinstance(ast_elt, ast.Assign) |
| 306 |
else [ast_elt.target] |
| 307 |
) |
| 308 |
result.assign_defs.append( |
| 309 |
( |
| 310 |
tuple(cast(ast.Name, target).id for target in targets), |
| 311 |
ast_elt, |
| 312 |
) |
| 313 |
) |
| 314 |
else: |
| 315 |
result.unfixable.append(ast_elt) |
| 316 |
return result |
| 317 |
|
| 318 |
def detect_autoreload( |
| 319 |
self, |
| 320 |
old_node: ast.Module | ast.ClassDef, |
| 321 |
new_node: ast.Module | ast.ClassDef, |
| 322 |
prefixes: list[str] | None = None, |
| 323 |
) -> bool: |
| 324 |
""" |
| 325 |
Returns |
| 326 |
------- |
| 327 |
`True` if we can run our targeted autoreload algorithm safely. |
| 328 |
`False` if we should instead use IPython's original autoreload implementation. |
| 329 |
""" |
| 330 |
if not self.enabled: |
| 331 |
return False |
| 332 |
prefixes = prefixes or [] |
| 333 |
|
| 334 |
old_result = self._gather_children(old_node.body, old_node) |
| 335 |
new_result = self._gather_children(new_node.body, new_node) |
| 336 |
old_defs_by_name: dict[str, ast.AST] = { |
| 337 |
name: ast_def for names, ast_def in old_result.all_defs() for name in names |
| 338 |
} |
| 339 |
new_defs_by_name: dict[str, ast.AST] = { |
| 340 |
name: ast_def for names, ast_def in new_result.all_defs() for name in names |
| 341 |
} |
| 342 |
|
| 343 |
if not compare_ast(old_result.unfixable, new_result.unfixable): |
| 344 |
return False |
| 345 |
|
| 346 |
cur = self._to_autoreload.traverse_prefixes(prefixes) |
| 347 |
for names, new_ast_def in new_result.all_defs(): |
| 348 |
names_to_reload = [] |
| 349 |
for name in names: |
| 350 |
if new_defs_by_name[name] is not new_ast_def: |
| 351 |
continue |
| 352 |
if name not in old_defs_by_name or not compare_ast( |
| 353 |
new_ast_def, old_defs_by_name[name] |
| 354 |
): |
| 355 |
names_to_reload.append(name) |
| 356 |
if names_to_reload: |
| 357 |
cur.defs_to_reload.append((tuple(names), new_ast_def)) |
| 358 |
cur.defs_to_delete |= set(old_defs_by_name.keys()) - set( |
| 359 |
new_defs_by_name.keys() |
| 360 |
) |
| 361 |
for name, new_ast_def_class in new_result.classes.items(): |
| 362 |
if name not in old_result.classes: |
| 363 |
cur.new_nested_classes[name] = new_ast_def_class |
| 364 |
elif not compare_ast( |
| 365 |
new_ast_def_class, old_result.classes[name] |
| 366 |
) and not self.detect_autoreload( |
| 367 |
old_result.classes[name], new_ast_def_class, prefixes + [name] |
| 368 |
): |
| 369 |
return False |
| 370 |
return True |
| 371 |
|
| 372 |
def _check_dependents(self) -> bool: |
| 373 |
""" |
| 374 |
If a decorator function is modified, we should similarly reload the functions which are decorated by this |
| 375 |
decorator. Iterate through the Dependency Graph to find such cases in the given AutoreloadTree. |
| 376 |
""" |
| 377 |
for node in self._check_dependents_inner(): |
| 378 |
self._add_node_to_autoreload_tree(node) |
| 379 |
return True |
| 380 |
|
| 381 |
def _add_node_to_autoreload_tree(self, node: DependencyNode) -> None: |
| 382 |
""" |
| 383 |
Given a node of the dependency graph, add decorator dependencies to the autoreload tree. |
| 384 |
""" |
| 385 |
if len(node.qualified_name) == 0: |
| 386 |
return |
| 387 |
cur = self._to_autoreload.traverse_prefixes(list(node.qualified_name[:-1])) |
| 388 |
if node.abstract_syntax_tree is not None: |
| 389 |
cur.defs_to_reload.append( |
| 390 |
((node.qualified_name[-1],), node.abstract_syntax_tree) |
| 391 |
) |
| 392 |
|
| 393 |
def _check_dependents_inner( |
| 394 |
self, prefixes: list[str] | None = None |
| 395 |
) -> list[DependencyNode]: |
| 396 |
prefixes = prefixes or [] |
| 397 |
cur = self._to_autoreload.traverse_prefixes(prefixes) |
| 398 |
ans = [] |
| 399 |
for (func_name, *_), _ in cur.defs_to_reload: |
| 400 |
node = tuple(prefixes + [func_name]) |
| 401 |
ans.extend(self._gen_dependents(node)) |
| 402 |
for class_name in cur.new_nested_classes: |
| 403 |
ans.extend(self._check_dependents_inner(prefixes + [class_name])) |
| 404 |
return ans |
| 405 |
|
| 406 |
def _gen_dependents(self, qualname: tuple[str, ...]) -> list[DependencyNode]: |
| 407 |
ans = [] |
| 408 |
if qualname not in self.dependency_graph: |
| 409 |
return [] |
| 410 |
for elt in self.dependency_graph[qualname]: |
| 411 |
ans.extend(self._gen_dependents(elt.qualified_name)) |
| 412 |
ans.append(elt) |
| 413 |
return ans |
| 414 |
|
| 415 |
def _patch_namespace_inner( |
| 416 |
self, ns: ModuleType | type, prefixes: list[str] | None = None |
| 417 |
) -> bool: |
| 418 |
""" |
| 419 |
This function patches module functions and methods. Specifically, only objects with their name in |
| 420 |
self.to_autoreload will be considered for patching. If an object has been marked to be autoreloaded, |
| 421 |
new_source_code gets executed in the old version's global environment. Then, replace the old function's |
| 422 |
attributes with the new function's attributes. |
| 423 |
""" |
| 424 |
prefixes = prefixes or [] |
| 425 |
cur = self._to_autoreload.traverse_prefixes(prefixes) |
| 426 |
namespace_to_check = ns |
| 427 |
for prefix in prefixes: |
| 428 |
namespace_to_check = namespace_to_check.__dict__[prefix] |
| 429 |
seen_names: set[str] = set() |
| 430 |
for names, new_ast_def in cur.defs_to_reload: |
| 431 |
if len(names) == 1 and names[0] in seen_names: |
| 432 |
continue |
| 433 |
seen_names.update(names) |
| 434 |
local_env: dict[str, Any] = {} |
| 435 |
if ( |
| 436 |
isinstance(new_ast_def, (ast.FunctionDef, ast.AsyncFunctionDef)) |
| 437 |
and (name := names[0]) in namespace_to_check.__dict__ |
| 438 |
): |
| 439 |
assert len(names) == 1 |
| 440 |
to_patch_to = namespace_to_check.__dict__[name] |
| 441 |
if isinstance(to_patch_to, (staticmethod, classmethod)): |
| 442 |
to_patch_to = to_patch_to.__func__ |
| 443 |
# exec new source code using old function's (obj) globals environment. |
| 444 |
func_code = textwrap.dedent(ast.unparse(new_ast_def)) |
| 445 |
if is_method := (len(prefixes) > 0): |
| 446 |
func_code = "class __autoreload_class__:\n" + textwrap.indent( |
| 447 |
func_code, " " |
| 448 |
) |
| 449 |
global_env = ns.__dict__ |
| 450 |
if not isinstance(global_env, dict): |
| 451 |
global_env = dict(global_env) |
| 452 |
# Compile with correct filename to preserve in traceback |
| 453 |
filename = ( |
| 454 |
getattr(to_patch_to, "__code__", None) |
| 455 |
and to_patch_to.__code__.co_filename |
| 456 |
or "<string>" |
| 457 |
) |
| 458 |
func_asts = [ast.parse(func_code)] |
| 459 |
if len(cast(ast.FunctionDef, func_asts[0].body[0]).decorator_list) > 0: |
| 460 |
without_decorator_list = pickle.loads(pickle.dumps(func_asts[0])) |
| 461 |
cast( |
| 462 |
ast.FunctionDef, without_decorator_list.body[0] |
| 463 |
).decorator_list = [] |
| 464 |
func_asts.insert(0, without_decorator_list) |
| 465 |
for func_ast in func_asts: |
| 466 |
compiled_code = compile( |
| 467 |
func_ast, filename, mode="exec", dont_inherit=True |
| 468 |
) |
| 469 |
exec(compiled_code, global_env, local_env) # type: ignore[arg-type] |
| 470 |
# local_env contains the function exec'd from new version of function |
| 471 |
if is_method: |
| 472 |
to_patch_from = getattr(local_env["__autoreload_class__"], name) |
| 473 |
else: |
| 474 |
to_patch_from = local_env[name] |
| 475 |
if isinstance(to_patch_from, (staticmethod, classmethod)): |
| 476 |
to_patch_from = to_patch_from.__func__ |
| 477 |
if isinstance(to_patch_to, property) and isinstance( |
| 478 |
to_patch_from, property |
| 479 |
): |
| 480 |
for attr in ("fget", "fset", "fdel"): |
| 481 |
if ( |
| 482 |
getattr(to_patch_to, attr) is None |
| 483 |
or getattr(to_patch_from, attr) is None |
| 484 |
): |
| 485 |
self.try_patch_attr(to_patch_to, to_patch_from, attr) |
| 486 |
else: |
| 487 |
self.patch_function( |
| 488 |
getattr(to_patch_to, attr), |
| 489 |
getattr(to_patch_from, attr), |
| 490 |
is_method, |
| 491 |
) |
| 492 |
elif not isinstance(to_patch_to, property) and not isinstance( |
| 493 |
to_patch_from, property |
| 494 |
): |
| 495 |
self.patch_function(to_patch_to, to_patch_from, is_method) |
| 496 |
else: |
| 497 |
raise ValueError( |
| 498 |
"adding or removing property decorations not supported" |
| 499 |
) |
| 500 |
else: |
| 501 |
exec( |
| 502 |
ast.unparse(new_ast_def), |
| 503 |
ns.__dict__ | namespace_to_check.__dict__, |
| 504 |
local_env, |
| 505 |
) |
| 506 |
for name in names: |
| 507 |
setattr(namespace_to_check, name, local_env[name]) |
| 508 |
cur.defs_to_reload.clear() |
| 509 |
for name in cur.defs_to_delete: |
| 510 |
try: |
| 511 |
delattr(namespace_to_check, name) |
| 512 |
except (AttributeError, TypeError, ValueError): |
| 513 |
# give up on deleting the attribute, let the stale one dangle |
| 514 |
pass |
| 515 |
cur.defs_to_delete.clear() |
| 516 |
for class_name, class_ast_node in cur.new_nested_classes.items(): |
| 517 |
local_env_class: dict[str, Any] = {} |
| 518 |
exec( |
| 519 |
ast.unparse(class_ast_node), |
| 520 |
ns.__dict__ | namespace_to_check.__dict__, |
| 521 |
local_env_class, |
| 522 |
) |
| 523 |
setattr(namespace_to_check, class_name, local_env_class[class_name]) |
| 524 |
cur.new_nested_classes.clear() |
| 525 |
for class_name in cur.children.keys(): |
| 526 |
if not self._patch_namespace(ns, prefixes + [class_name]): |
| 527 |
return False |
| 528 |
cur.children.clear() |
| 529 |
return True |
| 530 |
|
| 531 |
def _patch_namespace( |
| 532 |
self, ns: ModuleType | type, prefixes: list[str] | None = None |
| 533 |
) -> bool: |
| 534 |
""" |
| 535 |
Wrapper for patching all elements in a namespace as specified by the to_autoreload member variable. |
| 536 |
Returns `true` if patching was successful, and `false` if unsuccessful. |
| 537 |
""" |
| 538 |
try: |
| 539 |
return self._patch_namespace_inner(ns, prefixes=prefixes) |
| 540 |
except Exception: |
| 541 |
return False |
| 542 |
|
| 543 |
def maybe_reload_module(self, module: ModuleType) -> bool: |
| 544 |
""" |
| 545 |
Uses Deduperreload to try to update a module. |
| 546 |
Returns `true` on success and `false` on failure. |
| 547 |
""" |
| 548 |
if not self.enabled: |
| 549 |
return False |
| 550 |
if not (modname := getattr(module, "__name__", None)): |
| 551 |
return False |
| 552 |
if (fname := get_module_file_name(module)) is None: |
| 553 |
return False |
| 554 |
try: |
| 555 |
with open(fname, "r", encoding="utf8") as f: |
| 556 |
new_source_code = f.read() |
| 557 |
except Exception as e: |
| 558 |
logger = logging.getLogger("autoreload") |
| 559 |
logger.exception( |
| 560 |
f"Failed to read module file '{fname}' for module '{modname}': {type(e).__name__}" |
| 561 |
) |
| 562 |
return False |
| 563 |
patched_flag = False |
| 564 |
if old_source_code := self.source_by_modname.get(modname): |
| 565 |
# get old/new module ast |
| 566 |
try: |
| 567 |
old_module_ast = ast.parse(old_source_code) |
| 568 |
new_module_ast = ast.parse(new_source_code) |
| 569 |
except Exception: |
| 570 |
return False |
| 571 |
# detect if we are able to use our autoreload algorithm |
| 572 |
ctx = contextlib.suppress() |
| 573 |
with ctx: |
| 574 |
self._build_dependency_graph(new_module_ast) |
| 575 |
if ( |
| 576 |
self.detect_autoreload(old_module_ast, new_module_ast) |
| 577 |
and self._check_dependents() |
| 578 |
and self._patch_namespace(module) |
| 579 |
): |
| 580 |
patched_flag = True |
| 581 |
|
| 582 |
self.source_by_modname[modname] = new_source_code |
| 583 |
self._to_autoreload = AutoreloadTree() |
| 584 |
return patched_flag |
| 585 |
|
| 586 |
def _separate_name( |
| 587 |
self, |
| 588 |
decorator: ast.Attribute | ast.Name | ast.Call | ast.expr, |
| 589 |
accept_calls: bool, |
| 590 |
) -> list[str] | None: |
| 591 |
""" |
| 592 |
Generates a qualified name for a given decorator by finding its relative namespace. |
| 593 |
""" |
| 594 |
if isinstance(decorator, ast.Name): |
| 595 |
return [decorator.id] |
| 596 |
elif isinstance(decorator, ast.Call): |
| 597 |
if accept_calls: |
| 598 |
return self._separate_name(decorator.func, False) |
| 599 |
else: |
| 600 |
return None |
| 601 |
if not isinstance(decorator, ast.Attribute): |
| 602 |
return None |
| 603 |
if pref := self._separate_name(decorator.value, False): |
| 604 |
return pref + [decorator.attr] |
| 605 |
else: |
| 606 |
return None |
| 607 |
|
| 608 |
def _gather_dependents( |
| 609 |
self, body: list[ast.stmt], body_prefixes: list[str] | None = None |
| 610 |
) -> bool: |
| 611 |
body_prefixes = body_prefixes or [] |
| 612 |
for ast_node in body: |
| 613 |
ast_elt: ast.expr | ast.stmt = ast_node |
| 614 |
if isinstance(ast_elt, ast.ClassDef): |
| 615 |
self._gather_dependents(ast_elt.body, body_prefixes + [ast_elt.name]) |
| 616 |
continue |
| 617 |
if not isinstance(ast_elt, (ast.FunctionDef, ast.AsyncFunctionDef)): |
| 618 |
continue |
| 619 |
qualified_name = tuple(body_prefixes + [ast_elt.name]) |
| 620 |
cur_dependency_node = DependencyNode(qualified_name, ast_elt) |
| 621 |
for decorator in ast_elt.decorator_list: |
| 622 |
decorator_path = self._separate_name(decorator, True) |
| 623 |
if not decorator_path: |
| 624 |
continue |
| 625 |
decorator_path_tuple = tuple(decorator_path) |
| 626 |
self.dependency_graph.setdefault(decorator_path_tuple, []).append( |
| 627 |
cur_dependency_node |
| 628 |
) |
| 629 |
return True |
| 630 |
|
| 631 |
def _build_dependency_graph(self, new_ast: ast.Module | ast.ClassDef) -> bool: |
| 632 |
""" |
| 633 |
Wrapper function for generating dependency graph given some AST. |
| 634 |
Returns `true` on success. Returns `false` on failure. |
| 635 |
Currently, only returns `true` as we do not block on failure to build this graph. |
| 636 |
""" |
| 637 |
return self._gather_dependents(new_ast.body) |