@@ -4168,6 +4168,10 @@ class Sentinel:
4168
4168
*module_name* is the module where the sentinel is defined.
4169
4169
Defaults to the current modules ``__name__``.
4170
4170
4171
+ *repr*, if supplied, will be used for the repr of the sentinel object.
4172
+ If not provided, *name* will be used.
4173
+ Only the initial definition of the sentinel can configure *repr*.
4174
+
4171
4175
All sentinels with the same *name* and *module_name* have the same identity.
4172
4176
The ``is`` operator is used to test if an object is a sentinel.
4173
4177
Sentinel identity is preserved across copy and pickle.
@@ -4177,8 +4181,27 @@ def __new__(
4177
4181
cls ,
4178
4182
name : str ,
4179
4183
module_name : typing .Optional [str ] = None ,
4184
+ * ,
4185
+ repr : typing .Optional [str ] = None ,
4180
4186
):
4181
4187
"""Return an object with a consistent identity."""
4188
+ if module_name is not None and repr is None :
4189
+ # 'repr' used to be the 2nd positional argument but is now 'module_name'
4190
+ # Test if 'module_name' is a module or is the old 'repr' argument
4191
+ # Use 'repr=name' to suppress this check
4192
+ try :
4193
+ importlib .import_module (module_name )
4194
+ except Exception :
4195
+ repr = module_name
4196
+ module_name = None
4197
+ warnings .warn (
4198
+ "'repr' as a positional argument could be mistaken for the sentinels"
4199
+ " 'module_name'."
4200
+ f" Use keyword parameter repr={ repr !r} instead." ,
4201
+ category = DeprecationWarning ,
4202
+ stacklevel = 2 ,
4203
+ )
4204
+
4182
4205
if module_name is None :
4183
4206
module_name = _caller (default = "" )
4184
4207
@@ -4198,6 +4221,7 @@ def __new__(
4198
4221
sentinel = super ().__new__ (cls )
4199
4222
sentinel ._name = name
4200
4223
sentinel ._module_name = module_name
4224
+ sentinel ._repr = repr if repr is not None else name
4201
4225
return _sentinel_registry .setdefault (registry_key , sentinel )
4202
4226
4203
4227
@staticmethod
@@ -4214,7 +4238,7 @@ def _import_sentinel(name: str, module_name: str):
4214
4238
return None
4215
4239
4216
4240
def __repr__ (self ) -> str :
4217
- return self ._name
4241
+ return self ._repr
4218
4242
4219
4243
if sys .version_info < (3 , 11 ):
4220
4244
# The presence of this method convinces typing._type_check
@@ -4232,7 +4256,8 @@ def __ror__(self, other):
4232
4256
@classmethod
4233
4257
def _unpickle_fetch_sentinel (cls , name : str , module_name : str ):
4234
4258
"""Unpickle using the sentinels location."""
4235
- return cls (name , module_name )
4259
+ # Explicit repr=name because a saved module_name is known to be valid
4260
+ return cls (name , module_name , repr = name )
4236
4261
4237
4262
def __reduce__ (self ):
4238
4263
"""Record where this sentinel is defined."""
0 commit comments