Coverage for sources/classcore/standard/behaviors.py: 100%

199 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-10-16 06:16 +0000

1# vim: set filetype=python fileencoding=utf-8: 

2# -*- coding: utf-8 -*- 

3 

4#============================================================================# 

5# # 

6# Licensed under the Apache License, Version 2.0 (the "License"); # 

7# you may not use this file except in compliance with the License. # 

8# You may obtain a copy of the License at # 

9# # 

10# http://www.apache.org/licenses/LICENSE-2.0 # 

11# # 

12# Unless required by applicable law or agreed to in writing, software # 

13# distributed under the License is distributed on an "AS IS" BASIS, # 

14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # 

15# See the License for the specific language governing permissions and # 

16# limitations under the License. # 

17# # 

18#============================================================================# 

19 

20 

21''' Implementations for standard behaviors. ''' 

22# TODO? Support introspection of PEP 593 annotations for behavior exclusions. 

23# Maybe enum for mutability and visibility. 

24 

25 

26from .. import utilities as _utilities 

27from . import __ 

28from . import nomina as _nomina 

29 

30 

31def access_core_function( # noqa: PLR0913 

32 cls: type, /, *, 

33 attributes_namer: _nomina.AttributesNamer, 

34 arguments: __.cabc.Mapping[ str, __.typx.Any ], 

35 level: str, 

36 name: str, 

37 default: __.cabc.Callable[ ..., __.typx.Any ], 

38) -> __.cabc.Callable[ ..., __.typx.Any ]: 

39 ''' Accesses core behavior function. 

40 

41 First checks for override argument, then checks for heritable 

42 attribute. Finally, falls back to provided default. 

43 ''' 

44 argument_name = f"{level}_{name}_core" 

45 attribute_name = attributes_namer( level, f"{name}_core" ) 

46 return ( 

47 arguments.get( argument_name ) 

48 or getattr( cls, attribute_name, default ) ) 

49 

50 

51def assign_attribute_if_mutable( # noqa: PLR0913 

52 obj: object, /, *, 

53 ligation: _nomina.AssignerLigation, 

54 attributes_namer: _nomina.AttributesNamer, 

55 error_class_provider: _nomina.ErrorClassProvider, 

56 level: str, 

57 name: str, 

58 value: __.typx.Any, 

59) -> None: 

60 ''' Assigns attribute if it is mutable, else raises error. ''' 

61 behaviors = survey_active_behaviors( 

62 obj, attributes_namer = attributes_namer, level = level ) 

63 if _nomina.immutability_label not in behaviors: 

64 ligation( name, value ) 

65 return 

66 rule = provide_permitter_if_applicable( 

67 obj, attributes_namer = attributes_namer, 

68 level = level, basename = 'mutables', name = name ) 

69 if rule is not None: 

70 ligation( name, value ) 

71 return 

72 target = _utilities.describe_object( obj ) 

73 raise error_class_provider( 'AttributeImmutability' )( name, target ) 

74 

75 

76def delete_attribute_if_mutable( # noqa: PLR0913 

77 obj: object, /, *, 

78 ligation: _nomina.DeleterLigation, 

79 attributes_namer: _nomina.AttributesNamer, 

80 error_class_provider: _nomina.ErrorClassProvider, 

81 level: str, 

82 name: str, 

83) -> None: 

84 ''' Deletes attribute if it is mutable, else raises error. ''' 

85 behaviors = survey_active_behaviors( 

86 obj, attributes_namer = attributes_namer, level = level ) 

87 if _nomina.immutability_label not in behaviors: 

88 ligation( name ) 

89 return 

90 rule = provide_permitter_if_applicable( 

91 obj, attributes_namer = attributes_namer, 

92 level = level, basename = 'mutables', name = name ) 

93 if rule is not None: 

94 ligation( name ) 

95 return 

96 target = _utilities.describe_object( obj ) 

97 raise error_class_provider( 'AttributeImmutability' )( name, target ) 

98 

99 

100def determine_relevant_permitters( 

101 objct: object, /, *, 

102 attributes_namer: _nomina.AttributesNamer, 

103 level: str, 

104 basename: str, 

105 name: str, 

106) -> tuple[ tuple[ str, __.typx.Any ], ... ]: 

107 ''' Returns exclusion rules matching name, in evaluation order. 

108 

109 A names match short-circuits, matching the survey core's 

110 historical control flow: predicates and regexes are not evaluated 

111 for a name found in the exclusion names. Otherwise a name may 

112 match any number of predicates and any number of regexes. The 

113 wildcard is not considered here; callers handle its 

114 short-circuit separately. 

115 

116 Rules pair a kind ('names', 'predicate', 'regex') with the raw 

117 matched verifier (name, predicate, or regex). Matching never 

118 renders diagnostic text: enforcement and survey consult kind 

119 and presence only, so exotic callables cannot disrupt them. 

120 Render verifiers with 'render_verifier_text' at the record 

121 layer when producing explanation records. 

122 ''' 

123 names_name = attributes_namer( level, f"{basename}_names" ) 

124 names: _nomina.BehaviorExclusionNamesOmni = ( 

125 getattr( objct, names_name, frozenset( ) ) ) 

126 if name in names: return ( ( 'names', name ), ) 

127 predicates_name = attributes_namer( level, f"{basename}_predicates" ) 

128 predicates: _nomina.BehaviorExclusionPredicates = ( 

129 getattr( objct, predicates_name, ( ) ) ) 

130 matched: list[ tuple[ str, __.typx.Any ] ] = [ 

131 ( 'predicate', predicate ) 

132 for predicate in predicates if predicate( name ) ] 

133 regexes_name = attributes_namer( level, f"{basename}_regexes" ) 

134 regexes: _nomina.BehaviorExclusionRegexes = ( 

135 getattr( objct, regexes_name, ( ) ) ) 

136 matched.extend( 

137 ( 'regex', regex ) 

138 for regex in regexes if regex.fullmatch( name ) ) 

139 return tuple( matched ) 

140 

141 

142def provide_permitter_if_applicable( 

143 objct: object, /, *, 

144 attributes_namer: _nomina.AttributesNamer, 

145 level: str, 

146 basename: str, 

147 name: str, 

148) -> __.typx.Optional[ tuple[ str, __.typx.Any ] ]: 

149 ''' Returns first exclusion rule permitting operation, else None. 

150 

151 Rules apply by precedence: omni or names membership, then 

152 the first matching predicate, then the first matching regex. 

153 Each rule pairs a kind ('omni', 'names', 'predicate', 'regex') 

154 with the raw matched verifier. Matching never renders 

155 diagnostic text: enforcement consults kind and presence only, 

156 so exotic callables cannot disrupt it. Render the verifier 

157 with 'render_verifier_text' at the record layer when producing 

158 explanation records. 

159 ''' 

160 names_name = attributes_namer( level, f"{basename}_names" ) 

161 names: _nomina.BehaviorExclusionNamesOmni = ( 

162 getattr( objct, names_name, frozenset( ) ) ) 

163 if names == '*': return ( 'omni', '*' ) 

164 if name in names: return ( 'names', name ) 

165 predicates_name = attributes_namer( level, f"{basename}_predicates" ) 

166 predicates: _nomina.BehaviorExclusionPredicates = ( 

167 getattr( objct, predicates_name, ( ) ) ) 

168 for predicate in predicates: 

169 if predicate( name ): 

170 return ( 'predicate', predicate ) 

171 regexes_name = attributes_namer( level, f"{basename}_regexes" ) 

172 regexes: _nomina.BehaviorExclusionRegexes = ( 

173 getattr( objct, regexes_name, ( ) ) ) 

174 for regex in regexes: 

175 if regex.fullmatch( name ): 

176 return ( 'regex', regex ) 

177 return None 

178 

179 

180def render_verifier_text( verifier: __.typx.Any, / ) -> str: 

181 ''' Returns stable detail text for an exclusion verifier. 

182 

183 Regexes render as pattern text; predicates render as 

184 fully-qualified name, with an anonymous fallback when no 

185 qualified name is available. Strings do not reach this 

186 function; they are classified as names before rendering. A 

187 non-string 'pattern' attribute is not trusted as text; such 

188 verifiers fall through to qualified-name rendering, where a 

189 non-string qualified name falls back to '<anonymous>' while 

190 a non-string module name preserves the qualified name. 

191 Hostile metadata (raising descriptors, custom 

192 '__getattribute__') yields '<unrenderable>' rather than 

193 raising, so diagnostic rendering never disrupts its callers. 

194 The broad 'except Exception' is deliberate: rendering is 

195 diagnostics, and diagnostics must never break enforcement 

196 or survey paths. 

197 

198 Note: the inspect utilities were considered and rejected here; 

199 they resolve modules to objects and provide no qualified-name 

200 rendering with an anonymous fallback, while this getattr chain 

201 stays defensive for exotic callables (e.g., partials). 

202 ''' 

203 try: 

204 text = _render_verifier_text( verifier ) 

205 except Exception: 

206 text = '<unrenderable>' 

207 return text 

208 

209 

210def survey_active_behaviors( 

211 objct: object, /, *, 

212 attributes_namer: _nomina.AttributesNamer, 

213 level: str, 

214) -> __.cabc.Set[ str ]: 

215 ''' Returns active behaviors set for object at level. 

216 

217 This is the shared entry point of the behavior decision cascade: 

218 every core first determines whether the governing behavior is 

219 active before consulting exclusion configuration. 

220 ''' 

221 leveli = 'instance' if level == 'instances' else level 

222 behaviors_name = attributes_namer( leveli, 'behaviors' ) 

223 behaviors: __.cabc.Set[ str ] = ( 

224 _utilities.getattr0( objct, behaviors_name, frozenset( ) ) ) 

225 return behaviors 

226 

227 

228def survey_visible_attributes( 

229 obj: object, /, *, 

230 ligation: _nomina.SurveyorLigation, 

231 attributes_namer: _nomina.AttributesNamer, 

232 level: str, 

233) -> __.cabc.Iterable[ str ]: 

234 ''' Returns sequence of visible attributes. ''' 

235 names_base = ligation( ) 

236 behaviors = survey_active_behaviors( 

237 obj, attributes_namer = attributes_namer, level = level ) 

238 if _nomina.concealment_label not in behaviors: return names_base 

239 names_name = attributes_namer( level, 'visibles_names' ) 

240 names: _nomina.BehaviorExclusionNamesOmni = ( 

241 getattr( obj, names_name, frozenset( ) ) ) 

242 if names == '*': return names_base # pragma: no branch 

243 names_: list[ str ] = [ ] 

244 for name in names_base: 

245 matched = determine_relevant_permitters( 

246 obj, attributes_namer = attributes_namer, 

247 level = level, basename = 'visibles', name = name ) 

248 # Current behavior: one append per matched rule, so a name 

249 # matching several rules is yielded several times. Preserved 

250 # deliberately; normalization is a separate repair. 

251 names_.extend( name for rule in matched ) 

252 return names_ 

253 

254 

255def augment_class_attributes_allocations( 

256 attributes_namer: _nomina.AttributesNamer, 

257 namespace: dict[ str, __.typx.Any ], 

258) -> None: 

259 ''' Adds necessary slots for record-keeping attributes. ''' 

260 behaviors_name = attributes_namer( 'instance', 'behaviors' ) 

261 slots: __.typx.Union[ 

262 __.cabc.Mapping[ str, __.typx.Any ], 

263 __.cabc.Sequence[ str ], 

264 None 

265 ] = namespace.get( '__slots__' ) 

266 if slots and behaviors_name in slots: return 

267 if isinstance( slots, __.cabc.Mapping ): 

268 slots_ = dict( slots ) 

269 slots_[ behaviors_name ] = 'Active behaviors.' 

270 slots_ = __.types.MappingProxyType( slots_ ) 

271 elif isinstance( slots, __.cabc.Sequence ): 

272 slots_ = list( slots ) 

273 slots_.append( behaviors_name ) 

274 slots_ = tuple( slots_ ) 

275 else: return # pragma: no cover 

276 namespace[ '__slots__' ] = slots_ 

277 

278 

279def classify_behavior_exclusion_verifiers( 

280 verifiers: _nomina.BehaviorExclusionVerifiers 

281) -> tuple[ 

282 _nomina.BehaviorExclusionNames, 

283 _nomina.BehaviorExclusionRegexes, 

284 _nomina.BehaviorExclusionPredicates, 

285]: 

286 ''' Threshes sequence of behavior exclusion verifiers into bins. ''' 

287 names: set[ str ] = set( ) 

288 regexes: list[ __.re.Pattern[ str ] ] = [ ] 

289 predicates: list[ __.cabc.Callable[ ..., bool ] ] = [ ] 

290 for verifier in verifiers: 

291 if isinstance( verifier, str ): 

292 names.add( verifier ) 

293 elif isinstance( verifier, __.re.Pattern ): 

294 regexes.append( verifier ) 

295 elif callable( verifier ): 

296 predicates.append( verifier ) 

297 else: 

298 from ..exceptions import BehaviorExclusionInvalidity 

299 raise BehaviorExclusionInvalidity( verifier ) 

300 return frozenset( names ), tuple( regexes ), tuple( predicates ) 

301 

302 

303def produce_class_construction_preprocessor( 

304 attributes_namer: _nomina.AttributesNamer 

305) -> _nomina.ClassConstructionPreprocessor[ __.U ]: 

306 ''' Produces construction processor which handles metaclass arguments. ''' 

307 

308 def preprocess( # noqa: PLR0913, PLR0917 

309 clscls: type, 

310 name: str, 

311 bases: list[ type ], 

312 namespace: dict[ str, __.typx.Any ], 

313 arguments: dict[ str, __.typx.Any ], 

314 decorators: _nomina.DecoratorsMutable[ __.U ], 

315 ) -> None: 

316 record_class_construction_arguments( 

317 attributes_namer, namespace, arguments ) 

318 if '__slots__' in namespace: 

319 augment_class_attributes_allocations( attributes_namer, namespace ) 

320 

321 return preprocess 

322 

323 

324def produce_class_construction_postprocessor( 

325 attributes_namer: _nomina.AttributesNamer, 

326 error_class_provider: _nomina.ErrorClassProvider, 

327) -> _nomina.ClassConstructionPostprocessor[ __.U ]: 

328 ''' Produces construction processor which determines class decorators. ''' 

329 arguments_name = attributes_namer( 'class', 'construction_arguments' ) 

330 cores_default = dict( 

331 assigner = assign_attribute_if_mutable, 

332 deleter = delete_attribute_if_mutable, 

333 surveyor = survey_visible_attributes ) 

334 

335 def postprocess( 

336 cls: type, decorators: _nomina.DecoratorsMutable[ __.U ] 

337 ) -> None: 

338 arguments = getattr( cls, arguments_name, { } ) 

339 clscls = type( cls ) 

340 dcls_spec = getattr( cls, '__dataclass_transform__', None ) 

341 if not dcls_spec: # either base class or metaclass may be marked 

342 dcls_spec = getattr( clscls, '__dataclass_transform__', None ) 

343 cores = { } 

344 for core_name in ( 'assigner', 'deleter', 'surveyor' ): 

345 core_function = access_core_function( 

346 cls, 

347 attributes_namer = attributes_namer, 

348 arguments = arguments, 

349 level = 'instances', name = core_name, 

350 default = cores_default[ core_name ] ) 

351 cores[ core_name ] = core_function 

352 instances_mutables = arguments.get( 

353 'instances_mutables', __.mutables_default ) 

354 instances_visibles = arguments.get( 

355 'instances_visibles', __.visibles_default ) 

356 instances_ignore_init_arguments = arguments.get( 

357 'instances_ignore_init_arguments', False ) 

358 if dcls_spec and dcls_spec.get( 'kw_only_default', False ): 

359 from .decorators import dataclass_with_standard_behaviors 

360 decorator_factory = dataclass_with_standard_behaviors 

361 if not dcls_spec.get( 'frozen_default', True ): 

362 instances_mutables = instances_mutables or '*' 

363 else: 

364 from .decorators import with_standard_behaviors 

365 decorator_factory = with_standard_behaviors 

366 decorator: _nomina.Decorator[ __.U ] = decorator_factory( 

367 attributes_namer = attributes_namer, 

368 error_class_provider = error_class_provider, 

369 assigner_core = __.typx.cast( 

370 _nomina.AssignerCore, cores[ 'assigner' ] ), 

371 deleter_core = __.typx.cast( 

372 _nomina.DeleterCore, cores[ 'deleter' ] ), 

373 surveyor_core = __.typx.cast( 

374 _nomina.SurveyorCore, cores[ 'surveyor' ] ), 

375 ignore_init_arguments = instances_ignore_init_arguments, 

376 mutables = instances_mutables, 

377 visibles = instances_visibles ) 

378 decorators.append( decorator ) 

379 # Dynadoc tracks objects in weakset. 

380 # Must decorate after any potential class replacements. 

381 dynadoc_cfg = arguments.get( 'dynadoc_configuration', { } ) 

382 if not dynadoc_cfg: # either metaclass argument or attribute 

383 dynadoc_cfg_name = ( 

384 attributes_namer( 'classes', 'dynadoc_configuration' ) ) 

385 dynadoc_cfg = getattr( clscls, dynadoc_cfg_name, { } ) 

386 decorators.append( __.ddoc.with_docstring( **dynadoc_cfg ) ) 

387 

388 return postprocess 

389 

390 

391def produce_class_initialization_completer( 

392 attributes_namer: _nomina.AttributesNamer 

393) -> _nomina.ClassInitializationCompleter: 

394 ''' Produces initialization completer which finalizes class behaviors. ''' 

395 arguments_name = attributes_namer( 'class', 'construction_arguments' ) 

396 

397 def complete( cls: type ) -> None: 

398 arguments: __.typx.Optional[ dict[ str, __.typx.Any ] ] = ( 

399 getattr( cls, arguments_name, None ) ) 

400 if arguments is not None: delattr( cls, arguments_name ) 

401 arguments = arguments or { } 

402 mutables = arguments.get( 'class_mutables', __.mutables_default ) 

403 visibles = arguments.get( 'class_visibles', __.visibles_default ) 

404 behaviors: set[ str ] = set( ) 

405 record_behavior( 

406 cls, attributes_namer = attributes_namer, 

407 level = 'class', basename = 'mutables', 

408 label = _nomina.immutability_label, behaviors = behaviors, 

409 verifiers = mutables ) 

410 record_behavior( 

411 cls, attributes_namer = attributes_namer, 

412 level = 'class', basename = 'visibles', 

413 label = _nomina.concealment_label, behaviors = behaviors, 

414 verifiers = visibles ) 

415 # Set behaviors attribute last since it enables enforcement. 

416 behaviors_name = attributes_namer( 'class', 'behaviors' ) 

417 _utilities.setattr0( cls, behaviors_name, frozenset( behaviors ) ) 

418 

419 return complete 

420 

421 

422def record_behavior( # noqa: PLR0913 

423 cls: type, /, *, 

424 attributes_namer: _nomina.AttributesNamer, 

425 level: str, 

426 basename: str, 

427 label: str, 

428 behaviors: set[ str ], 

429 verifiers: _nomina.BehaviorExclusionVerifiersOmni, 

430) -> None: 

431 ''' Records details of particular class behavior, such as immutability. ''' 

432 names_name = attributes_namer( level, f"{basename}_names" ) 

433 if verifiers == '*': 

434 setattr( cls, names_name, '*' ) 

435 return 

436 names_omni: _nomina.BehaviorExclusionNamesOmni = ( 

437 getattr( cls, names_name, frozenset( ) ) ) 

438 if names_omni == '*': return 

439 names, regexes, predicates = ( 

440 classify_behavior_exclusion_verifiers( verifiers ) ) 

441 regexes_name = attributes_namer( level, f"{basename}_regexes" ) 

442 predicates_name = attributes_namer( level, f"{basename}_predicates" ) 

443 names_: _nomina.BehaviorExclusionNames = ( 

444 frozenset( { *names, *names_omni } ) ) 

445 regexes_: _nomina.BehaviorExclusionRegexes = ( 

446 _deduplicate_merge_sequences( 

447 regexes, getattr( cls, regexes_name, ( ) ) ) ) 

448 predicates_: _nomina.BehaviorExclusionPredicates = ( 

449 _deduplicate_merge_sequences( 

450 predicates, getattr( cls, predicates_name, ( ) ) ) ) 

451 setattr( cls, names_name, names_ ) 

452 setattr( cls, regexes_name, regexes_ ) 

453 setattr( cls, predicates_name, predicates_ ) 

454 # TODO? Add regexes match cache. 

455 # TODO? Add predicates match cache. 

456 behaviors.add( label ) 

457 

458 

459def record_class_construction_arguments( 

460 attributes_namer: _nomina.AttributesNamer, 

461 namespace: dict[ str, __.typx.Any ], 

462 arguments: dict[ str, __.typx.Any ], 

463) -> None: 

464 ''' Captures metaclass arguments as class attribute for later use. ''' 

465 arguments_name = attributes_namer( 'class', 'construction_arguments' ) 

466 arguments_ = namespace.get( arguments_name, { } ) 

467 # Decorators, which replace classes, will cause construction of the 

468 # replacements without arguments. If we had previously recorded them in 

469 # the class namespace, then we do not want to clobber them. 

470 if arguments_: return 

471 arguments_ = { } 

472 for name in ( 

473 'class_mutables', 'class_visibles', 

474 'dynadoc_configuration', 

475 'instances_assigner_core', 

476 'instances_deleter_core', 

477 'instances_surveyor_core', 

478 'instances_ignore_init_arguments', 

479 'instances_mutables', 'instances_visibles', 

480 ): 

481 if name not in arguments: continue 

482 arguments_[ name ] = arguments.pop( name ) 

483 namespace[ arguments_name ] = arguments_ 

484 

485 

486def _deduplicate_merge_sequences( 

487 addends: __.cabc.Sequence[ __.typx.Any ], 

488 augends: __.cabc.Sequence[ __.typx.Any ], 

489) -> __.cabc.Sequence[ __.typx.Any ]: 

490 result = list( augends ) 

491 augends_ = set( augends ) 

492 for addend in addends: 

493 if addend in augends_: continue 

494 result.append( addend ) 

495 return tuple( result ) 

496 

497 

498def _render_verifier_text( verifier: __.typx.Any, / ) -> str: 

499 ''' Returns detail text for an exclusion verifier, possibly raising. 

500 

501 Total rendering lives in 'render_verifier_text', which maps 

502 hostile-metadata failures to the documented fallback. This 

503 partial function holds the getattr chain so the wrapper has 

504 no returns inside its guarded block. 

505 ''' 

506 pattern = getattr( verifier, 'pattern', None ) 

507 if isinstance( pattern, str ): return pattern 

508 qualname = getattr( verifier, '__qualname__', None ) 

509 if not isinstance( qualname, str ): return '<anonymous>' 

510 module = getattr( verifier, '__module__', None ) 

511 if not isinstance( module, str ) or '<locals>' in qualname: 

512 return qualname 

513 return f"{module}.{qualname}"