File tree Expand file tree Collapse file tree 2 files changed +18
-3
lines changed Expand file tree Collapse file tree 2 files changed +18
-3
lines changed Original file line number Diff line number Diff line change @@ -321,7 +321,8 @@ def variable(
321
321
322
322
# Track where this variable was declared in code.
323
323
filename , lineno , code_context = inspect_tools .get_caller_source_location (
324
- stacklevel = _stacklevel + 1
324
+ stacklevel = _stacklevel + 1 ,
325
+ truncate_stacklevel = True ,
325
326
)
326
327
self ._variable_declarations [self ._variable_index_counter ] = (
327
328
filename ,
@@ -429,7 +430,8 @@ def subject_to(
429
430
# Track where this constraint was declared in code.
430
431
n_cons = np .length (constraint )
431
432
filename , lineno , code_context = inspect_tools .get_caller_source_location (
432
- stacklevel = _stacklevel + 1
433
+ stacklevel = _stacklevel + 1 ,
434
+ truncate_stacklevel = True ,
433
435
)
434
436
self ._constraint_declarations [self ._constraint_index_counter ] = (
435
437
filename ,
Original file line number Diff line number Diff line change 7
7
8
8
def get_caller_source_location (
9
9
stacklevel : int = 1 ,
10
+ truncate_stacklevel : bool = False ,
10
11
) -> (Path , int , str ):
11
12
"""
12
13
Gets the file location where this function itself (`get_caller_source_location()`) is called.
@@ -37,6 +38,9 @@ def get_caller_source_location(
37
38
you higher (i.e., more end-user-facing) in the stack. Same behaviour as the `stacklevel` argument in
38
39
warnings.warn().
39
40
41
+ truncate_stacklevel: If True, will truncate the stacklevel to the maximum possible value. This is useful if you
42
+
43
+
40
44
Returns: A tuple of:
41
45
(filename, lineno, code_context)
42
46
@@ -51,7 +55,16 @@ def get_caller_source_location(
51
55
### Go up `stacklevel` frames from the current one to get to the caller frame.
52
56
frame = inspect .currentframe ()
53
57
for _ in range (stacklevel ):
54
- frame = frame .f_back
58
+ if frame .f_back is None :
59
+ if truncate_stacklevel :
60
+ break
61
+ else :
62
+ raise ValueError (
63
+ f"Argument `{ stacklevel = } ` results in popping off the top of the traceback.\n "
64
+ f"Use a lower value, or set `truncate_stacklevel=True` to suppress this error."
65
+ )
66
+ else :
67
+ frame = frame .f_back
55
68
56
69
### Extract the frame info (an `inspect.Traceback` type) from the caller frame
57
70
frame_info : inspect .Traceback = inspect .getframeinfo (frame )
You can’t perform that action at this time.
0 commit comments