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

117 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''' Standard classes and class factories. ''' 

22 

23 

24from . import __ 

25from . import decorators as _decorators 

26from . import dynadoc as _dynadoc 

27from . import nomina as _nomina 

28 

29 

30_protocol_cls_set = frozenset( { __.typx.Protocol } ) 

31# Attributes never considered declared protocol members: typing internals, 

32# class-creation machinery, and framework attributes declared in classcore 

33# base class bodies. 

34_protocol_attr_excluded = frozenset( { 

35 '_is_protocol', '_is_runtime_protocol', 

36 '__protocol_attrs__', '__subclasshook__', 

37 '__non_callable_proto_members__', 

38 '_dynadoc_fragments_', 

39 # Injected during class creation by ABC, Generic, and typing machinery. 

40 # '__init__' is '_no_init' on protocol bases; as a structural member it 

41 # is vacuous since every candidate object has an '__init__'. 

42 # '__typing_is_deprecated_inherited_runtime_protocol__' is set by 

43 # CPython 3.15+ typing on protocol classes which inherit runtime 

44 # checkability; as a structural member it is vacuous since it records 

45 # machinery provenance rather than a callable member. 

46 '__abstractmethods__', '__parameters__', '__init__', '__orig_bases__', 

47 '__typing_is_deprecated_inherited_runtime_protocol__', # Python 3.15+ 

48} ) 

49_protocol_attr_prefixes = ( '_classcore_', '_abc_' ) 

50# Standard Python attributes present in every pre-decoration namespace. 

51_python_class_defaults = frozenset( { 

52 '__module__', '__qualname__', '__doc__', '__dict__', '__weakref__', 

53 '__slots__', '__annotations__', 

54 '__firstlineno__', '__static_attributes__', # Python 3.13+ 

55} ) 

56 

57 

58def _snapshot_declared_protocol_attrs( cls: type ) -> None: 

59 ''' Records protocol members declared before framework decoration. 

60 

61 Called in metaclass '__new__' immediately after class creation, 

62 before behavior decorators and dataclass machinery inject their 

63 attributes. The pre-decoration namespace contains exactly the 

64 members declared by the author, so a user-declared dunder (e.g., 

65 '__repr__') is preserved while framework-generated ones are absent. 

66 ''' 

67 # Dataclass slot machinery reproduces classes, copying '__dict__'. 

68 # Retain the original snapshot; the reproduction's namespace already 

69 # contains decorated attributes. 

70 if '_classcore_protocol_declared_' in cls.__dict__: return 

71 declared = ( 

72 set( cls.__dict__ ) 

73 | set( __.inspect.get_annotations( cls ) ) ) 

74 declared -= _python_class_defaults 

75 declared = { 

76 attr for attr in declared 

77 if attr not in _protocol_attr_excluded 

78 and not any( attr.startswith( p ) for p in _protocol_attr_prefixes ) 

79 } 

80 setattr( cls, '_classcore_protocol_declared_', frozenset( declared ) ) 

81 

82_dynadoc_configuration = ( 

83 _dynadoc.produce_dynadoc_configuration( table = __.fragments ) ) 

84_class_factory = __.funct.partial( 

85 _decorators.class_factory, dynadoc_configuration = _dynadoc_configuration ) 

86 

87 

88class ClassFactoryExtraArguments( __.typx.TypedDict, total = False ): 

89 ''' Extra arguments accepted by standard metaclasses. ''' 

90 

91 class_mutables: _nomina.BehaviorExclusionVerifiersOmni 

92 class_visibles: _nomina.BehaviorExclusionVerifiersOmni 

93 dynadoc_configuration: _nomina.DynadocConfiguration 

94 instances_assigner_core: _nomina.AssignerCore 

95 instances_deleter_core: _nomina.DeleterCore 

96 instances_surveyor_core: _nomina.SurveyorCore 

97 instances_ignore_init_arguments: bool 

98 instances_mutables: _nomina.BehaviorExclusionVerifiersOmni 

99 instances_visibles: _nomina.BehaviorExclusionVerifiersOmni 

100 

101 

102@_class_factory( ) 

103class Class( type ): 

104 ''' Metaclass for standard classes. ''' 

105 

106 _dynadoc_fragments_ = ( 

107 'cfc class conceal', 'cfc class protect', 'cfc dynadoc', 

108 'cfc instance conceal', 'cfc instance protect' ) 

109 

110 def __new__( # Typechecker stub. 

111 clscls: type[ __.T ], 

112 name: str, 

113 bases: tuple[ type, ... ], 

114 namespace: dict[ str, __.typx.Any ], *, 

115 decorators: _nomina.Decorators[ __.T ] = ( ), 

116 **arguments: __.typx.Unpack[ ClassFactoryExtraArguments ], 

117 ) -> __.T: 

118 return super( ).__new__( clscls, name, bases, namespace ) 

119 

120 

121@_class_factory( ) 

122class AbstractClass( Class, __.abc.ABCMeta ): 

123 ''' Metaclass for abstract classes with standard behaviors. 

124 

125 Combines the standard behaviors of `Class` with the machinery of 

126 `abc.ABCMeta` (abstract method enforcement, virtual subclass 

127 registration) via a diamond hierarchy. `Class` itself remains 

128 backed by plain `type`, so ABC machinery applies only where this 

129 metaclass is used. 

130 

131 Contributes the stdlib ABC and typing machinery names as internal 

132 for the classes it builds, mirroring the class_mutables exemption 

133 scoping. 

134 ''' 

135 

136 _dynadoc_fragments_ = ( 

137 'cfc class conceal', 'cfc class protect', 'cfc dynadoc', 

138 'cfc instance conceal', 'cfc instance protect' ) 

139 

140 def __new__( # Typechecker stub. 

141 clscls: type[ __.T ], 

142 name: str, 

143 bases: tuple[ type, ... ], 

144 namespace: dict[ str, __.typx.Any ], *, 

145 decorators: _nomina.Decorators[ __.T ] = ( ), 

146 **arguments: __.typx.Unpack[ ClassFactoryExtraArguments ], 

147 ) -> __.T: 

148 return super( ).__new__( clscls, name, bases, namespace ) 

149 

150 

151@_class_factory( ) 

152@__.typx.dataclass_transform( frozen_default = True, kw_only_default = True ) 

153class Dataclass( Class ): 

154 ''' Metaclass for standard dataclasses. ''' 

155 

156 _dynadoc_fragments_ = ( 

157 'cfc produce dataclass', 

158 'cfc class conceal', 'cfc class protect', 'cfc dynadoc', 

159 'cfc instance conceal', 'cfc instance protect' ) 

160 

161 def __new__( # Typechecker stub. 

162 clscls: type[ __.T ], 

163 name: str, 

164 bases: tuple[ type, ... ], 

165 namespace: dict[ str, __.typx.Any ], *, 

166 decorators: _nomina.Decorators[ __.T ] = ( ), 

167 **arguments: __.typx.Unpack[ ClassFactoryExtraArguments ], 

168 ) -> __.T: 

169 return super( ).__new__( clscls, name, bases, namespace ) 

170 

171 

172@_class_factory( ) 

173@__.typx.dataclass_transform( kw_only_default = True ) 

174class DataclassMutable( Dataclass ): 

175 ''' Metaclass for dataclasses with mutable instance attributes. ''' 

176 

177 _dynadoc_fragments_ = ( 

178 'cfc produce dataclass', 

179 'cfc class conceal', 'cfc class protect', 'cfc dynadoc', 

180 'cfc instance conceal' ) 

181 

182 def __new__( # Typechecker stub. 

183 clscls: type[ __.T ], 

184 name: str, 

185 bases: tuple[ type, ... ], 

186 namespace: dict[ str, __.typx.Any ], *, 

187 decorators: _nomina.Decorators[ __.T ] = ( ), 

188 **arguments: __.typx.Unpack[ ClassFactoryExtraArguments ], 

189 ) -> __.T: 

190 return super( ).__new__( clscls, name, bases, namespace ) 

191 

192 

193@_class_factory( ) 

194class ProtocolClass( AbstractClass, type( __.typx.Protocol ) ): 

195 ''' Metaclass for standard protocol classes. ''' 

196 

197 _dynadoc_fragments_ = ( 

198 'cfc produce protocol class', 

199 'cfc class conceal', 'cfc class protect', 'cfc dynadoc', 

200 'cfc instance conceal', 'cfc instance protect' ) 

201 

202 def __new__( # Typechecker stub. 

203 clscls: type[ __.T ], 

204 name: str, 

205 bases: tuple[ type, ... ], 

206 namespace: dict[ str, __.typx.Any ], *, 

207 decorators: _nomina.Decorators[ __.T ] = ( ), 

208 **arguments: __.typx.Unpack[ ClassFactoryExtraArguments ], 

209 ) -> __.T: 

210 cls = super( ).__new__( clscls, name, bases, namespace ) 

211 # typing_extensions.Protocol.__init_subclass__ uses identity comparison 

212 # (b is Protocol) to set _is_protocol on subclasses. Classcore protocol 

213 # base classes are not typing.Protocol, so subclasses incorrectly get 

214 # _is_protocol = False. Detect protocol base classes structurally and 

215 # fix _is_protocol before decorators are applied 

216 # (e.g., runtime_checkable). 

217 if not cls.__dict__.get( '_is_protocol', False ): 

218 for base in cls.__bases__: 

219 if ( base.__dict__.get( '_is_protocol', False ) 

220 and bool( _protocol_cls_set & set( base.__bases__ ) ) ): 

221 setattr( cls, '_is_protocol', True ) 

222 break 

223 if cls.__dict__.get( '_is_protocol', False ): 

224 _snapshot_declared_protocol_attrs( cls ) 

225 return cls 

226 

227 def __init__( 

228 cls, 

229 name: str, 

230 bases: tuple[ type, ... ], 

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

232 **kwargs: __.typx.Any, 

233 ) -> None: 

234 super( ).__init__( name, bases, namespace, **kwargs ) 

235 # Replace _ProtocolMeta's scan of the decorated namespace with the 

236 # pre-decoration snapshot, so isinstance() only checks declared 

237 # protocol members. Snapshot persists because metaclass __init__ can 

238 # run more than once when dataclass machinery reproduces classes. 

239 if getattr( cls, '_is_protocol', False ): 

240 declared: frozenset[ str ] = cls.__dict__.get( 

241 '_classcore_protocol_declared_', frozenset( ) ) 

242 inherited: set[ str ] = set( ) 

243 for base in cls.__mro__[ 1: ]: 

244 if not isinstance( base, ProtocolClass ): continue 

245 inherited.update( base.__dict__.get( 

246 '__protocol_attrs__', ( ) ) ) 

247 attrs = { 

248 attr for attr in declared | inherited 

249 if attr not in _protocol_attr_excluded 

250 and not any( 

251 attr.startswith( p ) for p in _protocol_attr_prefixes ) 

252 } 

253 setattr( cls, '__protocol_attrs__', attrs ) 

254 

255 

256@_class_factory( ) 

257@__.typx.dataclass_transform( frozen_default = True, kw_only_default = True ) 

258class ProtocolDataclass( ProtocolClass ): 

259 ''' Metaclass for standard protocol dataclasses. ''' 

260 

261 _dynadoc_fragments_ = ( 

262 'cfc produce protocol class', 'cfc produce dataclass', 

263 'cfc class conceal', 'cfc class protect', 'cfc dynadoc', 

264 'cfc instance conceal', 'cfc instance protect' ) 

265 

266 def __new__( # Typechecker stub. 

267 clscls: type[ __.T ], 

268 name: str, 

269 bases: tuple[ type, ... ], 

270 namespace: dict[ str, __.typx.Any ], *, 

271 decorators: _nomina.Decorators[ __.T ] = ( ), 

272 **arguments: __.typx.Unpack[ ClassFactoryExtraArguments ], 

273 ) -> __.T: 

274 return super( ).__new__( clscls, name, bases, namespace ) 

275 

276 

277@_class_factory( ) 

278@__.typx.dataclass_transform( kw_only_default = True ) 

279class ProtocolDataclassMutable( ProtocolDataclass ): 

280 ''' Metaclass for protocol dataclasses with mutable instance attributes. 

281 ''' 

282 

283 _dynadoc_fragments_ = ( 

284 'cfc produce protocol class', 'cfc produce dataclass', 

285 'cfc class conceal', 'cfc class protect', 'cfc dynadoc', 

286 'cfc instance conceal' ) 

287 

288 def __new__( # Typechecker stub. 

289 clscls: type[ __.T ], 

290 name: str, 

291 bases: tuple[ type, ... ], 

292 namespace: dict[ str, __.typx.Any ], *, 

293 decorators: _nomina.Decorators[ __.T ] = ( ), 

294 **arguments: __.typx.Unpack[ ClassFactoryExtraArguments ], 

295 ) -> __.T: 

296 return super( ).__new__( clscls, name, bases, namespace ) 

297 

298 

299class Object( metaclass = Class ): 

300 ''' Standard base class. ''' 

301 

302 _dynadoc_fragments_ = ( 

303 'class concealment', 'class protection', 'class dynadoc', 

304 'class instance conceal', 'class instance protect' ) 

305 

306 

307class ObjectMutable( metaclass = Class, instances_mutables = '*' ): 

308 ''' Base class with mutable instance attributes. ''' 

309 

310 _dynadoc_fragments_ = ( 

311 'class concealment', 'class protection', 'class dynadoc', 

312 'class instance conceal' ) 

313 

314 

315class AbstractObject( 

316 metaclass = AbstractClass, 

317 class_mutables = __.abc_class_mutables, 

318): 

319 ''' Base class for abstract classes with standard behaviors. 

320 

321 Supports abstract method enforcement and virtual subclass 

322 registration, and mixes with external classes whose metaclass is 

323 `abc.ABCMeta`. 

324 ''' 

325 

326 _dynadoc_fragments_ = ( 

327 'class concealment', 'class protection', 'class dynadoc', 

328 'class instance conceal', 'class instance protect' ) 

329 

330 

331class DataclassObject( metaclass = Dataclass ): 

332 ''' Standard base dataclass. ''' 

333 

334 _dynadoc_fragments_ = ( 

335 'dataclass', 

336 'class concealment', 'class protection', 'class dynadoc', 

337 'class instance conceal', 'class instance protect' ) 

338 

339 

340class DataclassObjectMutable( metaclass = DataclassMutable ): 

341 ''' Base dataclass with mutable instance attributes. ''' 

342 

343 _dynadoc_fragments_ = ( 

344 'dataclass', 

345 'class concealment', 'class protection', 'class dynadoc', 

346 'class instance conceal' ) 

347 

348 

349class Protocol( 

350 __.typx.Protocol, 

351 metaclass = ProtocolClass, 

352 class_mutables = ( 

353 *__.abc_class_mutables, *__.typing_class_mutables ), 

354): 

355 ''' Standard base protocol class. ''' 

356 

357 _dynadoc_fragments_ = ( 

358 'protocol class', 

359 'class concealment', 'class protection', 'class dynadoc', 

360 'class instance conceal', 'class instance protect' ) 

361 

362 

363class ProtocolMutable( 

364 __.typx.Protocol, 

365 metaclass = ProtocolClass, 

366 class_mutables = ( 

367 *__.abc_class_mutables, *__.typing_class_mutables ), 

368 instances_mutables = '*', 

369): 

370 ''' Base protocol class with mutable instance attributes. ''' 

371 

372 _dynadoc_fragments_ = ( 

373 'protocol class', 

374 'class concealment', 'class protection', 'class dynadoc', 

375 'class instance conceal' ) 

376 

377 

378class DataclassProtocol( 

379 __.typx.Protocol, 

380 metaclass = ProtocolDataclass, 

381 class_mutables = ( 

382 *__.abc_class_mutables, *__.typing_class_mutables ), 

383): 

384 ''' Standard base protocol dataclass. ''' 

385 

386 _dynadoc_fragments_ = ( 

387 'dataclass', 'protocol class', 

388 'class concealment', 'class protection', 'class dynadoc', 

389 'class instance conceal', 'class instance protect' ) 

390 

391 

392class DataclassProtocolMutable( 

393 __.typx.Protocol, 

394 metaclass = ProtocolDataclassMutable, 

395 class_mutables = ( 

396 *__.abc_class_mutables, *__.typing_class_mutables ), 

397): 

398 ''' Base protocol dataclass with mutable instance attributes. ''' 

399 

400 _dynadoc_fragments_ = ( 

401 'dataclass', 'protocol class', 

402 'class concealment', 'class protection', 'class dynadoc', 

403 'class instance conceal' ) 

404 

405 

406# =========================================================================== # 

407# Type checker canaries. Private declarations, excluded from the public API 

408# and the test suite. They exist so that Pyright (and other type checkers) 

409# evaluates the structures declared above; regressions in checker support 

410# surface as diagnostics on these declarations during routine linting. 

411# =========================================================================== # 

412 

413 

414class _CanaryAbstractObject( AbstractObject ): 

415 ''' Canary for abstract base classes. ''' 

416 

417 def provide( self ) -> int: 

418 return 42 

419 

420 

421class _CanaryProtocolUse( Protocol ): 

422 ''' Canary for protocol definitions. ''' 

423 

424 value: int 

425 

426 def greet( self ) -> str: ... 

427 

428 

429class _CanaryProtocolImpl( _CanaryProtocolUse ): 

430 ''' Canary for concrete protocol implementations. ''' 

431 

432 def __init__( self ) -> None: 

433 self.value = 7 

434 

435 def greet( self ) -> str: 

436 return 'canary' 

437 

438 

439_canary_abstract: int = _CanaryAbstractObject( ).provide( ) 

440_canary_protocol_iface: _CanaryProtocolUse = _CanaryProtocolImpl( ) 

441_canary_greeting: str = _canary_protocol_iface.greet( ) 

442 

443 

444def _is_stdlib_machinery_name( name: str ) -> bool: 

445 return ( 

446 name in __.abc_class_mutables 

447 or name in __.typing_class_mutables ) 

448 

449 

450__.augment_internal_names( AbstractClass, _is_stdlib_machinery_name )