Skip to content

Commit c44848e

Browse files
committed
feat: infer variable name if name is not provided
1 parent 2de5f28 commit c44848e

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

sentinel.py

+12-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def _sentinel_failing_new(cls: type, *args: Tuple[Any, ...], **kwargs: Dict[str,
3838

3939

4040
def create(
41-
name: str,
41+
name: str = None,
4242
mro: Tuple[type, ...] = _DEFAULT_MRO,
4343
cls_dict: Dict[str, Any] = None,
4444
*args: Tuple[Any, ...],
@@ -75,6 +75,17 @@ def create(
7575
instantiating base classes such as a tuple.
7676
"""
7777

78+
if name is None:
79+
try:
80+
from varname import varname # type: ignore
81+
except ImportError as error:
82+
raise ImportError(
83+
"Cannot infer variable name without varname library; "
84+
"please install the varname PyPI package to enable this feature: "
85+
"pip install sentinel[varname]"
86+
) from error
87+
name = varname()
88+
7889
_cls_dict = {
7990
# make the singleton always belong to the module of its caller.
8091
# If we don't do this, pickling using __reduce__() will fail!

test_sentinel.py

+12
Original file line numberDiff line numberDiff line change
@@ -142,3 +142,15 @@ def test_copy():
142142
assert copied[Copyable][1][0] is Copyable
143143
# Check that the objects are different
144144
assert copied[Copyable][1] is not arbitrary_data_structure[Copyable][1]
145+
146+
147+
def test_varnames():
148+
"""
149+
Test support with Python varnames,
150+
"""
151+
152+
Dark = sentinel.create()
153+
Magicks = sentinel.create()
154+
155+
assert repr(Dark) == "Dark"
156+
assert repr(Magicks) == "Magicks"

0 commit comments

Comments
 (0)