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

199 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-10-15 02:08 +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. Hostile 

189 metadata (raising descriptors, custom '__getattribute__') 

190 yields '<unrenderable>' rather than raising, so diagnostic 

191 rendering never disrupts its callers. 

192 

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

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

195 rendering with an anonymous fallback, while this getattr chain 

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

197 ''' 

198 try: 

199 text = _render_verifier_text( verifier ) 

200 except Exception: 

201 text = '<unrenderable>' 

202 return text 

203 

204 

205def survey_active_behaviors( 

206 objct: object, /, *, 

207 attributes_namer: _nomina.AttributesNamer, 

208 level: str, 

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

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

211 

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

213 every core first determines whether the governing behavior is 

214 active before consulting exclusion configuration. 

215 ''' 

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

217 behaviors_name = attributes_namer( leveli, 'behaviors' ) 

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

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

220 return behaviors 

221 

222 

223def survey_visible_attributes( 

224 obj: object, /, *, 

225 ligation: _nomina.SurveyorLigation, 

226 attributes_namer: _nomina.AttributesNamer, 

227 level: str, 

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

229 ''' Returns sequence of visible attributes. ''' 

230 names_base = ligation( ) 

231 behaviors = survey_active_behaviors( 

232 obj, attributes_namer = attributes_namer, level = level ) 

233 if _nomina.concealment_label not in behaviors: return names_base 

234 names_name = attributes_namer( level, 'visibles_names' ) 

235 names: _nomina.BehaviorExclusionNamesOmni = ( 

236 getattr( obj, names_name, frozenset( ) ) ) 

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

238 names_: list[ str ] = [ ] 

239 for name in names_base: 

240 matched = determine_relevant_permitters( 

241 obj, attributes_namer = attributes_namer, 

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

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

244 # matching several rules is yielded several times. Preserved 

245 # deliberately; normalization is a separate repair. 

246 names_.extend( name for rule in matched ) 

247 return names_ 

248 

249 

250def augment_class_attributes_allocations( 

251 attributes_namer: _nomina.AttributesNamer, 

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

253) -> None: 

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

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

256 slots: __.typx.Union[ 

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

258 __.cabc.Sequence[ str ], 

259 None 

260 ] = namespace.get( '__slots__' ) 

261 if slots and behaviors_name in slots: return 

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

263 slots_ = dict( slots ) 

264 slots_[ behaviors_name ] = 'Active behaviors.' 

265 slots_ = __.types.MappingProxyType( slots_ ) 

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

267 slots_ = list( slots ) 

268 slots_.append( behaviors_name ) 

269 slots_ = tuple( slots_ ) 

270 else: return # pragma: no cover 

271 namespace[ '__slots__' ] = slots_ 

272 

273 

274def classify_behavior_exclusion_verifiers( 

275 verifiers: _nomina.BehaviorExclusionVerifiers 

276) -> tuple[ 

277 _nomina.BehaviorExclusionNames, 

278 _nomina.BehaviorExclusionRegexes, 

279 _nomina.BehaviorExclusionPredicates, 

280]: 

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

282 names: set[ str ] = set( ) 

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

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

285 for verifier in verifiers: 

286 if isinstance( verifier, str ): 

287 names.add( verifier ) 

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

289 regexes.append( verifier ) 

290 elif callable( verifier ): 

291 predicates.append( verifier ) 

292 else: 

293 from ..exceptions import BehaviorExclusionInvalidity 

294 raise BehaviorExclusionInvalidity( verifier ) 

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

296 

297 

298def produce_class_construction_preprocessor( 

299 attributes_namer: _nomina.AttributesNamer 

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

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

302 

303 def preprocess( # noqa: PLR0913, PLR0917 

304 clscls: type, 

305 name: str, 

306 bases: list[ type ], 

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

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

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

310 ) -> None: 

311 record_class_construction_arguments( 

312 attributes_namer, namespace, arguments ) 

313 if '__slots__' in namespace: 

314 augment_class_attributes_allocations( attributes_namer, namespace ) 

315 

316 return preprocess 

317 

318 

319def produce_class_construction_postprocessor( 

320 attributes_namer: _nomina.AttributesNamer, 

321 error_class_provider: _nomina.ErrorClassProvider, 

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

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

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

325 cores_default = dict( 

326 assigner = assign_attribute_if_mutable, 

327 deleter = delete_attribute_if_mutable, 

328 surveyor = survey_visible_attributes ) 

329 

330 def postprocess( 

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

332 ) -> None: 

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

334 clscls = type( cls ) 

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

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

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

338 cores = { } 

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

340 core_function = access_core_function( 

341 cls, 

342 attributes_namer = attributes_namer, 

343 arguments = arguments, 

344 level = 'instances', name = core_name, 

345 default = cores_default[ core_name ] ) 

346 cores[ core_name ] = core_function 

347 instances_mutables = arguments.get( 

348 'instances_mutables', __.mutables_default ) 

349 instances_visibles = arguments.get( 

350 'instances_visibles', __.visibles_default ) 

351 instances_ignore_init_arguments = arguments.get( 

352 'instances_ignore_init_arguments', False ) 

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

354 from .decorators import dataclass_with_standard_behaviors 

355 decorator_factory = dataclass_with_standard_behaviors 

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

357 instances_mutables = instances_mutables or '*' 

358 else: 

359 from .decorators import with_standard_behaviors 

360 decorator_factory = with_standard_behaviors 

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

362 attributes_namer = attributes_namer, 

363 error_class_provider = error_class_provider, 

364 assigner_core = __.typx.cast( 

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

366 deleter_core = __.typx.cast( 

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

368 surveyor_core = __.typx.cast( 

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

370 ignore_init_arguments = instances_ignore_init_arguments, 

371 mutables = instances_mutables, 

372 visibles = instances_visibles ) 

373 decorators.append( decorator ) 

374 # Dynadoc tracks objects in weakset. 

375 # Must decorate after any potential class replacements. 

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

377 if not dynadoc_cfg: # either metaclass argument or attribute 

378 dynadoc_cfg_name = ( 

379 attributes_namer( 'classes', 'dynadoc_configuration' ) ) 

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

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

382 

383 return postprocess 

384 

385 

386def produce_class_initialization_completer( 

387 attributes_namer: _nomina.AttributesNamer 

388) -> _nomina.ClassInitializationCompleter: 

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

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

391 

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

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

394 getattr( cls, arguments_name, None ) ) 

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

396 arguments = arguments or { } 

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

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

399 behaviors: set[ str ] = set( ) 

400 record_behavior( 

401 cls, attributes_namer = attributes_namer, 

402 level = 'class', basename = 'mutables', 

403 label = _nomina.immutability_label, behaviors = behaviors, 

404 verifiers = mutables ) 

405 record_behavior( 

406 cls, attributes_namer = attributes_namer, 

407 level = 'class', basename = 'visibles', 

408 label = _nomina.concealment_label, behaviors = behaviors, 

409 verifiers = visibles ) 

410 # Set behaviors attribute last since it enables enforcement. 

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

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

413 

414 return complete 

415 

416 

417def record_behavior( # noqa: PLR0913 

418 cls: type, /, *, 

419 attributes_namer: _nomina.AttributesNamer, 

420 level: str, 

421 basename: str, 

422 label: str, 

423 behaviors: set[ str ], 

424 verifiers: _nomina.BehaviorExclusionVerifiersOmni, 

425) -> None: 

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

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

428 if verifiers == '*': 

429 setattr( cls, names_name, '*' ) 

430 return 

431 names_omni: _nomina.BehaviorExclusionNamesOmni = ( 

432 getattr( cls, names_name, frozenset( ) ) ) 

433 if names_omni == '*': return 

434 names, regexes, predicates = ( 

435 classify_behavior_exclusion_verifiers( verifiers ) ) 

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

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

438 names_: _nomina.BehaviorExclusionNames = ( 

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

440 regexes_: _nomina.BehaviorExclusionRegexes = ( 

441 _deduplicate_merge_sequences( 

442 regexes, getattr( cls, regexes_name, ( ) ) ) ) 

443 predicates_: _nomina.BehaviorExclusionPredicates = ( 

444 _deduplicate_merge_sequences( 

445 predicates, getattr( cls, predicates_name, ( ) ) ) ) 

446 setattr( cls, names_name, names_ ) 

447 setattr( cls, regexes_name, regexes_ ) 

448 setattr( cls, predicates_name, predicates_ ) 

449 # TODO? Add regexes match cache. 

450 # TODO? Add predicates match cache. 

451 behaviors.add( label ) 

452 

453 

454def record_class_construction_arguments( 

455 attributes_namer: _nomina.AttributesNamer, 

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

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

458) -> None: 

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

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

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

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

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

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

465 if arguments_: return 

466 arguments_ = { } 

467 for name in ( 

468 'class_mutables', 'class_visibles', 

469 'dynadoc_configuration', 

470 'instances_assigner_core', 

471 'instances_deleter_core', 

472 'instances_surveyor_core', 

473 'instances_ignore_init_arguments', 

474 'instances_mutables', 'instances_visibles', 

475 ): 

476 if name not in arguments: continue 

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

478 namespace[ arguments_name ] = arguments_ 

479 

480 

481def _deduplicate_merge_sequences( 

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

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

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

485 result = list( augends ) 

486 augends_ = set( augends ) 

487 for addend in addends: 

488 if addend in augends_: continue 

489 result.append( addend ) 

490 return tuple( result ) 

491 

492 

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

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

495 

496 Total rendering lives in 'render_verifier_text', which maps 

497 hostile-metadata failures to the documented fallback. This 

498 partial function holds the getattr chain so the wrapper has 

499 no returns inside its guarded block. 

500 ''' 

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

502 if isinstance( pattern, str ): return pattern 

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

504 if qualname is None: return '<anonymous>' 

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

506 if module is None or '<locals>' in qualname: 

507 return qualname 

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