Skip to content

Commit 165c54a

Browse files
authored
Use sys._getframe instead of inspect.stack for efficiency (#9)
1 parent a0c5d1c commit 165c54a

File tree

2 files changed

+23
-15
lines changed

2 files changed

+23
-15
lines changed

tests/test_varname.py

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import sys
12
import pytest
23
from varname import (varname,
34
VarnameRetrievingWarning,
@@ -10,18 +11,24 @@
1011
_get_node,
1112
nameof)
1213

14+
1315
@pytest.fixture
14-
def monkey_patch():
15-
"""Monkey-patch inspect.stack to get only one frame,
16-
which happens in R package reticulate."""
17-
from varname import inspect
16+
def no_getframe():
17+
"""
18+
Monkey-patch sys._getframe to fail,
19+
simulating environments that don't support varname
20+
"""
1821

19-
orig_stack = inspect.stack
20-
inspect.stack = lambda *args, **kwargs: orig_stack(*args, **kwargs)[:1]
22+
def getframe(_context):
23+
raise ValueError
2124

22-
yield
25+
orig_getframe = sys._getframe
26+
try:
27+
sys._getframe = getframe
28+
yield
29+
finally:
30+
sys._getframe = orig_getframe
2331

24-
inspect.stack = orig_stack
2532

2633
def test_function():
2734

@@ -363,13 +370,14 @@ def get_will():
363370
with pytest.raises(VarnameRetrievingError):
364371
get_will()['a']
365372

366-
def test_frame_fail(monkey_patch):
373+
374+
def test_frame_fail(no_getframe):
367375
"""Test when failed to retrieve the frame"""
368376
# Let's monkey-patch inspect.stack to do this
369377
assert _get_node(1) is None
370378

371-
def test_frame_fail_varname(monkey_patch):
372379

380+
def test_frame_fail_varname(no_getframe):
373381
def func(raise_exc):
374382
return varname(raise_exc=raise_exc)
375383

@@ -380,14 +388,14 @@ def func(raise_exc):
380388
b = func(False)
381389
assert b.startswith('var_')
382390

383-
def test_frame_fail_nameof(monkey_patch):
384391

392+
def test_frame_fail_nameof(no_getframe):
385393
a = 1
386394
with pytest.raises(VarnameRetrievingError):
387395
nameof(a)
388396

389-
def test_frame_fail_will(monkey_patch):
390397

398+
def test_frame_fail_will(no_getframe):
391399
def func(raise_exc):
392400
wil = will(raise_exc=raise_exc)
393401
ret = lambda: None

varname.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Get the variable name that assigned by function/class calls"""
22
import ast
3-
import inspect
3+
import sys
44
import warnings
55
from collections import namedtuple as standard_namedtuple
66
import executing
@@ -28,8 +28,8 @@ def _get_node(caller):
2828
When the node can not be retrieved, try to return the first statement.
2929
"""
3030
try:
31-
frame = inspect.stack()[caller+2].frame
32-
except IndexError:
31+
frame = sys._getframe(caller + 2)
32+
except Exception:
3333
return None
3434
else:
3535
exet = executing.Source.executing(frame)

0 commit comments

Comments
 (0)