3737
3838if TYPE_CHECKING :
3939 from types import ModuleType
40+ from typing import Any
4041
4142ROOT = pathlib .Path (__file__ ).resolve ().parents [2 ]
4243
4748PACKAGE_NAMES = ['AppType' , 'DCCP' , 'SCTP' , 'TCP' , 'TransportProtocol' , 'UDP' , '__all__' ,
4849 'apptype' , 'dccp' , 'sctp' , 'tcp' , 'udp' ]
4950
51+ #: Whether :obj:`dict` has union, :pep:`584`. Before Python 3.9, a registry has
52+ #: none either (GitHub issue #1694), so the union views run from 3.9 only.
53+ UNION = sys .version_info >= (3 , 9 )
54+
55+
56+ def merge (left : 'Any' , right : 'Any' ) -> 'Any' :
57+ """``left |= right``, as an expression."""
58+ left |= right
59+ return left
60+
61+
62+ #: Each dict union operator, as a function of its two operands.
63+ UNIONS = {'|' : lambda left , right : left | right , '|=' : merge }
64+
65+
66+ def union_error (op : 'str' , left : 'object' , right : 'object' ) -> 'str' :
67+ """The :exc:`TypeError` message for ``left <op> right`` where neither supports it."""
68+ return (f'unsupported operand type(s) for { op } : '
69+ f'{ type (left ).__name__ !r} and { type (right ).__name__ !r} ' )
70+
5071
5172def import_system_names (module : 'ModuleType' ) -> 'list[str]' :
5273 """``dir(module)`` as importing it would leave it, were its body empty.
@@ -188,12 +209,12 @@ def test_registries_never_expose_a_pending_registry(self) -> 'None':
188209 'items': lambda: dict(registries.items()),
189210 'copy': registries.copy,
190211 'copy.copy': lambda: dict(copy.copy(registries)),
191- 'or': lambda: registries | {},
192- 'ror': lambda: {} | registries,
193212 'repr': lambda: registries,
194213 'eq': lambda: registries == populated,
195214 'ne': lambda: registries != populated,
196215 }
216+ if sys.version_info >= (3, 9): # dict union, PEP 584
217+ views.update({'or': lambda: registries | {}, 'ror': lambda: {} | registries})
197218 reprs = {}
198219 for name, view in views.items():
199220 for proto in (TransportProtocol.tcp, TransportProtocol.udp):
@@ -203,6 +224,8 @@ def test_registries_never_expose_a_pending_registry(self) -> 'None':
203224 emit(shape=shape, reprs=reprs, default=registries.get(0, 'fallback'))
204225 ''' )
205226 self .assertEqual (out ['shape' ], [4 , [1 , 2 , 3 , 4 ], True , True , []])
227+ self .assertEqual (len (out ['reprs' ]), 13 if UNION else 11 )
228+ self .assertEqual ({'or' , 'ror' } <= set (out ['reprs' ]), UNION )
206229 for name , text in out ['reprs' ].items ():
207230 with self .subTest (view = name ):
208231 self .assertNotIn ('ModuleDescriptor' , text )
@@ -313,19 +336,53 @@ def test_whole_mapping_reads_resolve_everything(self) -> 'None':
313336 'dict' : lambda registries : dict .__eq__ (dict (registries ), expected ),
314337 'eq' : lambda registries : registries == expected ,
315338 'ne' : lambda registries : (registries != expected ) is False ,
316- 'or' : lambda registries : dict .__eq__ (registries | {}, expected ),
317- 'ror' : lambda registries : dict .__eq__ ({} | registries , expected ),
318339 'repr' : lambda registries : 'ModuleDescriptor' not in repr (registries ),
319340 'pop' : lambda registries : registries .pop (proto .tcp ) is classes [0 ],
320341 'popitem' : lambda registries : registries .popitem () == (proto .dccp , classes [3 ]),
321342 'setdefault' : lambda registries : registries .setdefault (proto .udp ) is classes [1 ],
322343 }
344+ if UNION :
345+ views .update ({
346+ 'or' : lambda registries : dict .__eq__ (registries | {}, expected ),
347+ 'ror' : lambda registries : dict .__eq__ ({} | registries , expected ),
348+ })
323349 for name , view in views .items ():
324350 with self .subTest (view = name ):
325351 self .make ()
326352 self .assertTrue (view (self .registries ))
327353 self .assert_pending ()
328354
355+ def test_union_is_dict_s_on_every_python (self ) -> 'None' :
356+ # NOTE: GitHub issue #1694. Where dict has no union (Python < 3.9), a
357+ # registry raises dict's TypeError, naming its own type, and imports
358+ # nothing; where it does, ``registries |= other`` is dict's in-place
359+ # update, which reads no value and so leaves the registry pending.
360+ proto , expected = self .proto , dict (zip (list (self .proto )[1 :], self .classes ))
361+ for op , side in (('|' , 'left' ), ('|' , 'right' ), ('|=' , 'left' ), ('|=' , 'right' )):
362+ with self .subTest (op = op , side = side ):
363+ self .make ()
364+ operands = (self .registries , {}) if side == 'left' else ({}, self .registries )
365+ if not UNION :
366+ with self .assertRaises (TypeError ) as plain :
367+ UNIONS [op ]({}, {})
368+ with self .assertRaises (TypeError ) as registry :
369+ UNIONS [op ](* operands )
370+ self .assertEqual (str (plain .exception ), union_error (op , {}, {}))
371+ self .assertEqual (str (registry .exception ), union_error (op , * operands ))
372+ self .assert_pending (proto .tcp , proto .udp )
373+ elif (op , side ) == ('|=' , 'left' ):
374+ self .assertIs (UNIONS [op ](* operands ), self .registries )
375+ self .assert_pending (proto .tcp , proto .udp )
376+ self .assertEqual (self .registries , expected )
377+ else :
378+ result = UNIONS [op ](* operands )
379+ self .assertIs (type (result ), dict )
380+ self .assertTrue (dict .__eq__ (result , expected ))
381+ self .assert_pending ()
382+ for name in ('__or__' , '__ror__' ):
383+ self .assertIs (name in vars (type (self .registries )), UNION )
384+ self .assertNotIn ('__ior__' , vars (type (self .registries )))
385+
329386
330387class PackageGetattrTests (unittest .TestCase ):
331388 """The :pep:`562` hooks, called in this process so that coverage sees them."""
0 commit comments