|
| 1 | +""" |
| 2 | +Compatibility layer for magicattr that works with Python 3.14+ |
| 3 | +
|
| 4 | +This module provides a patched version of magicattr's functionality |
| 5 | +that is compatible with Python 3.14's removal of ast.Num and ast.Str. |
| 6 | +
|
| 7 | +Based on magicattr 0.1.6 by Jairus Martin (MIT License) |
| 8 | +https://github.com/frmdstryr/magicattr |
| 9 | +""" |
| 10 | +import ast |
| 11 | +import sys |
| 12 | +from functools import reduce |
| 13 | + |
| 14 | +_AST_TYPES = (ast.Name, ast.Attribute, ast.Subscript, ast.Call) |
| 15 | +_STRING_TYPE = str |
| 16 | + |
| 17 | + |
| 18 | +def get(obj, attr, **kwargs): |
| 19 | + """A getattr that supports nested lookups on objects, dicts, lists, and |
| 20 | + any combination in between. |
| 21 | + """ |
| 22 | + for chunk in _parse(attr): |
| 23 | + try: |
| 24 | + obj = _lookup(obj, chunk) |
| 25 | + except Exception as ex: |
| 26 | + if "default" in kwargs: |
| 27 | + return kwargs["default"] |
| 28 | + else: |
| 29 | + raise ex |
| 30 | + return obj |
| 31 | + |
| 32 | + |
| 33 | +def set(obj, attr, val): |
| 34 | + """A setattr that supports nested lookups on objects, dicts, lists, and |
| 35 | + any combination in between. |
| 36 | + """ |
| 37 | + obj, attr_or_key, is_subscript = lookup(obj, attr) |
| 38 | + if is_subscript: |
| 39 | + obj[attr_or_key] = val |
| 40 | + else: |
| 41 | + setattr(obj, attr_or_key, val) |
| 42 | + |
| 43 | + |
| 44 | +def delete(obj, attr): |
| 45 | + """A delattr that supports deletion of a nested lookups on objects, |
| 46 | + dicts, lists, and any combination in between. |
| 47 | + """ |
| 48 | + obj, attr_or_key, is_subscript = lookup(obj, attr) |
| 49 | + if is_subscript: |
| 50 | + del obj[attr_or_key] |
| 51 | + else: |
| 52 | + delattr(obj, attr_or_key) |
| 53 | + |
| 54 | + |
| 55 | +def lookup(obj, attr): |
| 56 | + """Like get but instead of returning the final value it returns the |
| 57 | + object and action that will be done. |
| 58 | + """ |
| 59 | + nodes = tuple(_parse(attr)) |
| 60 | + if len(nodes) > 1: |
| 61 | + obj = reduce(_lookup, nodes[:-1], obj) |
| 62 | + node = nodes[-1] |
| 63 | + else: |
| 64 | + node = nodes[0] |
| 65 | + if isinstance(node, ast.Attribute): |
| 66 | + return obj, node.attr, False |
| 67 | + elif isinstance(node, ast.Subscript): |
| 68 | + return obj, _lookup_subscript_value(node.slice), True |
| 69 | + elif isinstance(node, ast.Name): |
| 70 | + return obj, node.id, False |
| 71 | + raise NotImplementedError("Node is not supported: %s" % node) |
| 72 | + |
| 73 | + |
| 74 | +def _parse(attr): |
| 75 | + """Parse and validate an attr string""" |
| 76 | + if not isinstance(attr, _STRING_TYPE): |
| 77 | + raise TypeError("Attribute name must be a string") |
| 78 | + nodes = ast.parse(attr).body |
| 79 | + if not nodes or not isinstance(nodes[0], ast.Expr): |
| 80 | + raise ValueError("Invalid expression: %s" % attr) |
| 81 | + return reversed([n for n in ast.walk(nodes[0]) if isinstance(n, _AST_TYPES)]) |
| 82 | + |
| 83 | + |
| 84 | +def _lookup_subscript_value(node): |
| 85 | + """Lookup the value of ast node on the object. |
| 86 | +
|
| 87 | + Compatible with Python 3.14+ which removed ast.Num and ast.Str |
| 88 | + """ |
| 89 | + if isinstance(node, ast.Index): |
| 90 | + node = node.value |
| 91 | + |
| 92 | + # Python 3.14+ uses ast.Constant for all constants |
| 93 | + if isinstance(node, ast.Constant): |
| 94 | + return node.value |
| 95 | + |
| 96 | + # Fallback for older Python versions |
| 97 | + if sys.version_info < (3, 14): |
| 98 | + # Handle numeric indexes |
| 99 | + if hasattr(ast, "Num") and isinstance(node, ast.Num): |
| 100 | + return node.n |
| 101 | + # Handle string keys |
| 102 | + elif hasattr(ast, "Str") and isinstance(node, ast.Str): |
| 103 | + return node.s |
| 104 | + |
| 105 | + # Handle negative indexes |
| 106 | + if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub): |
| 107 | + operand = node.operand |
| 108 | + if isinstance(operand, ast.Constant): |
| 109 | + return -operand.value |
| 110 | + # Fallback for older Python |
| 111 | + elif sys.version_info < (3, 14) and hasattr(ast, "Num") and isinstance(operand, ast.Num): |
| 112 | + return -operand.n |
| 113 | + |
| 114 | + raise NotImplementedError("Subscript node is not supported: %s" % ast.dump(node)) |
| 115 | + |
| 116 | + |
| 117 | +def _lookup(obj, node): |
| 118 | + """Lookup the given ast node on the object.""" |
| 119 | + if isinstance(node, ast.Attribute): |
| 120 | + return getattr(obj, node.attr) |
| 121 | + elif isinstance(node, ast.Subscript): |
| 122 | + return obj[_lookup_subscript_value(node.slice)] |
| 123 | + elif isinstance(node, ast.Name): |
| 124 | + return getattr(obj, node.id) |
| 125 | + elif isinstance(node, ast.Call): |
| 126 | + raise ValueError("Function calls are not allowed.") |
| 127 | + raise NotImplementedError("Node is not supported: %s" % node) |
0 commit comments