-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclasses.py
969 lines (836 loc) · 39.9 KB
/
classes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
#usr/bin/python
"""
Module libencapsulation.classes
Implements the full functionality of the library in two classes to be imported
by the other modules: distinction between the 'public' and 'protected'
attributes (to which the access is denied), C++ static like class attributes,
fixed data structure of the classes and their instances, and introspection
methods.
Classes:
ProtectedAttributes
FixedAttributes
The class ProtectedAttributes introduces the following modifications to the data
model:
* C++ like static fields based on the class attributes
* Protected class and instance attributes
* Support of the descriptors on the class and instance level
* Class, static and instance methods and properties cannot be deleted or
assigned to from a class object without instantiation
* Class, static and instance methods cannot be deleted or assigned to from
an instance of a class
* Properties can be assigned to from an instance of a class if the property
has __set__ descriptor
* Properties can be deleted from an instance of a class if the property has
__delete__ descriptor
The class FixedAttributes also adds the contant data structure of an object
during its lifetime, i.e.:
* Neither class nor instance data attributes can be deleted or created
during the lifetime of the object
Both classes implement singleton behaviour, i.e. their sub-classes cannot be
instantiated unless they re-define the protected method _onInit() without the
@abc.abstract decorator. This method is the only place inside the class'
definition, where the protected instance attributes can be defined using the
dot notation. It is supposed that all instance attributes are to be created
inside this _onInit() method. Do not modify the initialization magic method
__init__()!
"""
__version__ = "1.0.0.0"
__date__ = "15-11-2019"
__status__ = "Production"
#imports
import sys
import os
import abc
import types
#+ my libraries
ROOT_FOLDER = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if not (ROOT_FOLDER) in sys.path:
sys.path.append(ROOT_FOLDER)
from libexceptions import PrivateAttributeAccess, NotExistingAttribute
from libexceptions import CustomAttributeError, ConstantAttributeAssignment
#classes
#+ metaclasses
class ProtectedMeta(abc.ABCMeta):
"""
Metaclass for the classes implementing the modified attributes access scheme
* C++ like static fields based on the class attributes
* Protected class and instance attributes
* Support of the descriptors on the class and instance level
* Class, static and instance methods and properties cannot be deleted
or assigned to from a class object without instantiation
* Class, static and instance methods cannot be deleted or assigned to
from an instance of a class
* Properties can be assigned to from an instance of a class if the
property has __set__ descriptor
* Properties can be deleted from an instance of a class if the property
has __delete__ descriptor
Version 1.0.0.0
"""
#magic methods to hook attributes access on the class level
def __getattribute__(objCaller, strAttrName):
"""
Special magic method hooking the read access to an attribute on the
class level using a class object (without instantiation). Does not allow
access to the attributes with the names starting with a single
underscore, excepting those starting with the '_abc_' string or more
than one undescore.
Signature:
class A, str -> type A
Args:
objCaller: class A, the class object, to which this method is
applied
strAttrName: str, name of an attribute to access
Returns:
type A: the value of the attribute
Raises:
libexceptions.PrivateAttributeAccess: denied access to a protected
attribute
libexceptions.NotExistingAttribute: non-existing attribute is
accessed
Version 1.0.0.0
"""
bCond1 = strAttrName.startswith('_')
bCond2 = not strAttrName.startswith('__')
bCond3 = not strAttrName.startswith('_abc_')
if bCond1 and bCond2 and bCond3:
raise PrivateAttributeAccess(strAttrName, objCaller, iSkipFrames= 1)
try:
gResult = type.__getattribute__(objCaller, strAttrName)
except AttributeError:
raise NotExistingAttribute(strAttrName, objCaller, iSkipFrames= 1)
return gResult
def __setattr__(objCaller, strAttrName, gValue):
"""
Special magic method hooking the modification of an attribute access on
the class level using a class object (without instantiation). Does not
allow modification of the attributes with the names starting with a
single underscore, excepting those starting with the '_abc_' string or
more than one undescore.
Signature:
class A, str, type A -> None
Args:
objCaller: class A, the class object, to which this method is
applied
strAttrName: str, name of an attribute to modify
gValue: type A, the value to assign
Raises:
libexceptions.PrivateAttributeAccess: denied access to a protected
attribute
libexceptions.CustomAttributeError: an existing attribute cannot be
modified, e.g. method, property or an instance of a class with
__set__ descriptor preventing modification
Version 1.0.0.0
"""
bCond1 = strAttrName.startswith('_')
bCond2 = not strAttrName.startswith('__')
bCond3 = not strAttrName.startswith('_abc_')
if bCond1 and bCond2 and bCond3:
raise PrivateAttributeAccess(strAttrName, objCaller, iSkipFrames= 1)
bModified = False
for objParent in objCaller.__mro__:
if strAttrName in objParent.__dict__.keys():
gAttrValue = objParent.__dict__[strAttrName]
bCond1 = hasattr(gAttrValue, '__set__')
bCond2 = isinstance(gAttrValue, (classmethod, staticmethod,
types.FunctionType))
bCond4 = isinstance(gAttrValue, property)
if bCond1:
try:
gAttrValue.__set__(objParent, gValue)
except Exception as err:
if isinstance(err, ConstantAttributeAssignment):
raise ConstantAttributeAssignment(strAttrName,
objCaller, iSkipFrames = 1)
else:
raise CustomAttributeError(strAttrName, objCaller,
iSkipFrames= 1)
elif (bCond4 and not bCond1) or (bCond2 and not bCond4):
raise CustomAttributeError(strAttrName, objCaller,
iSkipFrames= 1)
else:
type.__setattr__(objParent, strAttrName, gValue)
bModified = True
break
if not bModified:
type.__setattr__(objCaller, strAttrName, gValue)
def __delattr__(objCaller, strAttrName):
"""
Special magic method hooking the deletion of an attribute on the class
level using a class object (without instantiation). Does not allow
deletion of the attributes with the names starting with a single
underscore, excepting those starting with the '_abc_' string or more
than one undescore.
Signature:
class A, str -> None
Args:
objCaller: class A, the class object, to which this method is
applied
strAttrName: str, name of an attribute to delete
Raises:
libexceptions.PrivateAttributeAccess: denied deletion of a protected
attribute
libexceptions.CustomAttributeError: denied deletion of a public or
magic attribute, e.g. method, property or an instance of a class
with __delete__ descriptor preventing deletion
libexceptions.NotExistingAttribute: denied deletion of a
non-existing attribute
Version 1.0.0.0
"""
bCond1 = strAttrName.startswith('_')
bCond2 = not strAttrName.startswith('__')
bCond3 = not strAttrName.startswith('_abc_')
if bCond1 and bCond2 and bCond3:
raise PrivateAttributeAccess(strAttrName, objCaller, iSkipFrames= 1)
if strAttrName in objCaller.__dict__.keys():
gAttrValue = objCaller.__dict__[strAttrName]
bCond1 = hasattr(gAttrValue, '__delete__')
bCond2 = isinstance(gAttrValue, (classmethod, staticmethod,
types.FunctionType, types.MethodType))
bCond4 = isinstance(gAttrValue, property)
if bCond1:
try:
gAttrValue.__delete__(objCaller)
except Exception as err:
if isinstance(err, ConstantAttributeAssignment):
raise ConstantAttributeAssignment(strAttrName,
objCaller, iSkipFrames = 1)
else:
raise CustomAttributeError(strAttrName, objCaller,
iSkipFrames= 1)
type.__setattr__(objCaller, strAttrName, None)
elif (bCond4 and not bCond1) or (bCond2 and not bCond4):
raise CustomAttributeError(strAttrName, objCaller,
iSkipFrames = 1)
type.__delattr__(objCaller, strAttrName)
del gAttrValue
elif hasattr(objCaller, strAttrName):
raise CustomAttributeError(strAttrName, objCaller, iSkipFrames = 1)
else:
raise NotExistingAttribute(strAttrName, objCaller, iSkipFrames = 1)
def __new__(cls, strName, lstBases, dictAttributes):
"""
Special 'constructor' magic method hooking the creation of the new
classes based on this metaclass. Note, that the constructor of the class
abc.ABCMeta is called instead of the type class. Due to the limitation
implied by the access modification the list of the abstract methods of
the class is reconstructed manually.
Signature:
type class A, str, list(class B), dict(str -> type A) -> class A
Args:
cls: type class A, factory for the class to be created, basically,
this metclass itself
strName: str, name of the class to be created
lstBases: list(class B), list of the super classes
dictAttributes: dict(str -> type A), dictionary of the class'
attributes
Returns:
class A: a new class object
Version 1.0.0.0
"""
objResult = abc.ABCMeta.__new__(cls, strName, lstBases, dictAttributes)
#walk around to preserve the virtuality of the inherited protected
#+ abstract method without copying them into the class dictionary, in
#+ short - recreate the list of the abstract methods manually
lstAbstractMethods = []
lstAllMethods = []
objlstMRO = [objResult]
objlstMRO.extend(objResult.__mro__)
for objParent in objlstMRO:
for strAttr, gAttr in objParent.__dict__.items():
if type(gAttr) == types.FunctionType:
bAbstract= gAttr.__dict__.get('__isabstractmethod__', False)
bCond1 = not (strAttr in lstAbstractMethods)
bCond2 = not (strAttr in lstAllMethods)
if bAbstract and bCond1 and bCond2:
lstAbstractMethods.append(strAttr)
if not (strAttr in lstAllMethods):
lstAllMethods.append(strAttr)
type.__setattr__(objResult, '__abstractmethods__',
frozenset(lstAbstractMethods))
return objResult
def __del__(cls):
"""
Special magic method hooking the destruction of a class. Ensures the
deletion of all class attributes, especially the 'protected' ones.
Signature:
class A -> None
Args:
cls: class A, the class object to be destructed
Version 1.0.0.0
"""
strAttributes = cls.__dict__.keys()
for strAttr in strAttributes:
gAttrValue = cls.__dict__[strAttr]
if hasattr(gAttrValue, '__delete__'):
try:
gAttrValue.__delete__(cls)
type.__setattr__(cls, strAttr, None)
except:
pass
try:
type.__delattr__(cls, strAttr)
del gAttrValue
except:
pass
class FixedMeta(ProtectedMeta):
"""
Metaclass for the classes implementing the modified attributes access scheme
* C++ like static fields based on the class attributes
* Protected class and instance attributes
* Support of the descriptors on the class and instance level
* Class, static and instance methods and properties cannot be deleted
or assigned to from a class object without instantiation
* Class, static and instance methods cannot be deleted or assigned to
from an instance of a class
* Properties can be assigned to from an instance of a class if the
property has __set__ descriptor
* Properties can be deleted from an instance of a class if the property
has __delete__ descriptor
* Neither class nor instance data attributes can be deleted or created
during the lifetime of the object
Sub-classes ProtectedMeta.
Version 1.0.0.0
"""
#magic methods to hook attributes access on the class level
def __delattr__(objCaller, strAttrName):
"""
Special magic method hooking the deletion of an attribute on the class
level using a class object (without instantiation). Does not allow
deletion of any attribute.
Signature:
class A, str -> None
Args:
objCaller: class A, the class object, to which this method is
applied
strAttrName: str, name of an attribute to delete
Raises:
libexceptions.PrivateAttributeAccess: denied deletion of a protected
attribute
libexceptions.CustomAttributeError: denied deletion of a public or
magic attribute
libexceptions.NotExistingAttribute: denied deletion of a
non-existing attribute
Version 1.0.0.0
"""
bCond1 = strAttrName.startswith('_')
bCond2 = not strAttrName.startswith('__')
bCond3 = not strAttrName.startswith('_abc_')
if bCond1 and bCond2 and bCond3:
raise PrivateAttributeAccess(strAttrName, objCaller, iSkipFrames= 1)
if hasattr(objCaller, strAttrName):
raise CustomAttributeError(strAttrName, objCaller, iSkipFrames = 1)
else:
raise NotExistingAttribute(strAttrName, objCaller, iSkipFrames = 1)
def __setattr__(objCaller, strAttrName, gValue):
"""
Special magic method hooking the modification of an attribute access on
the class level using a class object (without instantiation). Does not
allow modification of the attributes with the names starting with a
single underscore, excepting those starting with the '_abc_' string or
more than one undescore.
Signature:
class A, str, type A -> None
Args:
objCaller: class A, the class object, to which this method is
applied
strAttrName: str, name of an attribute to modify
gValue: type A, the value to assign
Raises:
libexceptions.PrivateAttributeAccess: denied access to a protected
attribute
libexceptions.CustomAttributeError: an existing attribute cannot be
modified, or such argument does not exist
libexceptions.NotExistingAttribute: the attribute does not exist
Version 1.0.0.0
"""
bCond1 = strAttrName.startswith('_')
bCond2 = not strAttrName.startswith('__')
bCond3 = not strAttrName.startswith('_abc_')
if bCond1 and bCond2 and bCond3:
raise PrivateAttributeAccess(strAttrName, objCaller, iSkipFrames= 1)
bModified = False
for objParent in objCaller.__mro__:
if strAttrName in objParent.__dict__.keys():
gAttrValue = objParent.__dict__[strAttrName]
bCond1 = hasattr(gAttrValue, '__set__')
bCond2 = isinstance(gAttrValue, (classmethod, staticmethod,
types.FunctionType))
bCond4 = isinstance(gAttrValue, property)
if bCond1:
try:
gAttrValue.__set__(objParent, gValue)
except Exception as err:
if isinstance(err, ConstantAttributeAssignment):
raise ConstantAttributeAssignment(strAttrName,
objCaller, iSkipFrames = 1)
else:
raise CustomAttributeError(strAttrName, objCaller,
iSkipFrames= 1)
elif (bCond4 and not bCond1) or (bCond2 and not bCond4):
raise CustomAttributeError(strAttrName, objCaller,
iSkipFrames = 1)
else:
type.__setattr__(objParent, strAttrName, gValue)
bModified = True
break
if not bModified:
raise NotExistingAttribute(strAttrName, objCaller, iSkipFrames = 1)
#+ classes to be used
class ProtectedAttributes(object):
"""
Abstract base class implementing the modified attributes access scheme
* C++ like static fields based on the class attributes
* Protected class and instance attributes
* Support of the descriptors on the class and instance level
* Class, static and instance methods and properties cannot be deleted
or assigned to from a class object without instantiation
* Class, static and instance methods cannot be deleted or assigned to
from an instance of a class
* Properties can be assigned to from an instance of a class if the
property has __set__ descriptor
* Properties can be deleted from an instance of a class if the property
has __delete__ descriptor
Sub-classes should re-define as not abstract the protected instance method
_onInit(), there the instance attributes are supposed to be created. Do not
change the __init__() method! If the _onInit() method is not re-defined the
sub-class cannot be instantiated and will act as a singleton.
Class methods:
getClassFields():
None -> list(str)
getClassMethods():
None -> list(str)
getInstanceMethods():
None -> list(str)
getProperties():
None -> list(str)
Methods:
getInstanceFields():
None -> list(str)
Version 1.0.0.0
"""
__metaclass__ = ProtectedMeta
#protected class methods
@abc.abstractmethod
def _onInit(self, *args, **kwargs):
"""
Virtual / abstract method to set the instance attributes. The
sub-classes designed to be used as singletons should not re-define this
method. Other sub-classes must re-define this method without the
decorator, and to create the instance attributes there, not in the
__init__() method.
Note that the signature of the re-defined version of this method will
define the signature of the class instantiation.
Signature:
/type A/, type B/, ...// -> None
Version 1.0.0.0
"""
pass
#magic instance methods
def __init__(self, *args, **kwargs):
"""
Special magic method to create and initialize the instance attributes
and to trigger the modification of the attributes resolution scheme.
The sub-classes should not modify this method. Instead, the protected
instance method _onInit() should be redefined without the decorator
@abc.abstractmethod. The instance attributes - public and protected -
should be defined their using dot notation as is usually done within
the __init__(). All positional and keyword arguments passed into the
__init__() method will be passed into _onInit(). The signature of the
re-defined _onInit() method will define the signature of the class'
instantiation.
Signature:
/type A/, type B/, ...// -> None
Args:
args: type A, any number of any positional arguments
kwargs: type B, any number of any keyword arguments
Raises:
TypeError: the abstract instance method _onInit() is not re-defined
as not abstract, and the class cannot be instantiated
Version 1.0.0.0
"""
self._onInit(*args, **kwargs)
self._bLocked = True
def __getattribute__(self, strAttrName):
"""
Special magic method hooking the read access to an attribute on the
class instance level. Does not allow access to the attributes with the
names starting with a single underscore, excepting those starting with
more than one undescore.
Signature:
str -> type A
Args:
strAttrName: str, name of an attribute to access
Returns:
type A: the value of the attribute
Raises:
libexceptions.PrivateAttributeAccess: denied access to a protected
attribute
libexceptions.CustomAttributeError: denied read access to an
existing attribute, i.e. by its own desriptor
libexceptions.NotExistingAttribute: the attribute does not exist
Version 1.0.0.0
"""
objClass = object.__getattribute__(self, '__class__')
bLocked = object.__getattribute__(self, '__dict__').get('_bLocked',
False)
bCond1 = strAttrName.startswith('_')
bCond2 = not strAttrName.startswith('__')
if bCond1 and bCond2 and bLocked:
raise PrivateAttributeAccess(strAttrName, objClass, iSkipFrames = 1)
try:
gResult = object.__getattribute__(self, strAttrName)
except AttributeError:
raise NotExistingAttribute(strAttrName, objClass, iSkipFrames = 1)
#check if a descriptor but not a method
if (hasattr(gResult, '__get__') and
(not isinstance(gResult, types.FunctionType))):
try:
gResult = gResult.__get__(self, objClass)
except:
raise CustomAttributeError(strAttrName, objClass,
iSkipFrames = 1)
return gResult
def __setattr__(self, strAttrName, gValue):
"""
Special magic method hooking the modification of an attribute access on
the class instance level. Does not allow modification of the attributes
with the names starting with a single underscore, excepting those
starting with more than one undescore.
Signature:
str, type A -> None
Args:
strAttrName: str, name of an attribute to modify
gValue: type A, the value to assign
Raises:
libexceptions.PrivateAttributeAccess: denied access to a protected
attribute
libexceptions.CustomAttributeError: denied modification of an
existing attribute due to its own desriptor limitation, or
deletion of an instance, class or static method
Version 1.0.0.0
"""
objClass = object.__getattribute__(self, '__class__')
bLocked = object.__getattribute__(self, '__dict__').get('_bLocked',
False)
bCond1 = strAttrName.startswith('_')
bCond2 = not strAttrName.startswith('__')
if bCond1 and bCond2 and bLocked:
raise PrivateAttributeAccess(strAttrName, objClass, iSkipFrames = 1)
if strAttrName in self.__dict__.keys():
if hasattr(self.__dict__[strAttrName], '__set__'):
self.__dict__[strAttrName].__set__(self, gValue)
else:
self.__dict__[strAttrName] = gValue
elif hasattr(self, strAttrName):
for objParent in self.__class__.__mro__:
if strAttrName in objParent.__dict__.keys():
gAttrValue = objParent.__dict__[strAttrName]
bCond1 = hasattr(gAttrValue, '__set__')
bCond2 = isinstance(gAttrValue, (classmethod, staticmethod,
property, types.MethodType,
types.FunctionType))
if bCond1:
try:
gAttrValue.__set__(self, gValue)
except Exception as err:
if isinstance(err, ConstantAttributeAssignment):
raise ConstantAttributeAssignment(strAttrName,
objClass, iSkipFrames = 1)
else:
raise CustomAttributeError(strAttrName, objClass,
iSkipFrames= 1)
elif bCond2:
raise CustomAttributeError(strAttrName, objClass,
iSkipFrames = 1)
else:
type.__setattr__(objParent, strAttrName, gValue)
else:
self.__dict__[strAttrName] = gValue
def __delattr__(self, strAttrName):
"""
Special magic method hooking the deletion of an attribute on the class
instance level. Does not allow deletion of the attributes with the names
starting with a single underscore, excepting those starting with more
than one undescore.
Signature:
str -> None
Args:
strAttrName: str, name of an attribute to delete
Raises:
libexceptions.PrivateAttributeAccess: denied access to a protected
attribute
libexceptions.CustomAttributeError: denied delition of an existing
class attribute, or of an existing instance attribute due to its
own desriptor limitation
libexceptions.NotExistingAttribute: the attribute does not exist
Version 1.0.0.0
"""
objClass = object.__getattribute__(self, '__class__')
bCond1 = strAttrName.startswith('_')
bCond2 = not strAttrName.startswith('__')
if bCond1 and bCond2:
raise PrivateAttributeAccess(strAttrName, objClass, iSkipFrames = 1)
if strAttrName in self.__dict__.keys():
gAttrValue = self.__dict__[strAttrName]
if hasattr(gAttrValue, '__delete__'):
try:
gAttrValue.__delete__(self)
except Exception as err:
if isinstance(err, ConstantAttributeAssignment):
raise ConstantAttributeAssignment(strAttrName,
objClass, iSkipFrames = 1)
else:
raise CustomAttributeError(strAttrName, objClass,
iSkipFrames= 1)
self.__dict__[strAttrName] = None
object.__delattr__(self, strAttrName)
del gAttrValue
elif hasattr(self, strAttrName):
raise CustomAttributeError(strAttrName, objClass, iSkipFrames = 1)
else:
raise NotExistingAttribute(strAttrName, objClass, iSkipFrames = 1)
def __del__(self):
"""
Special magic method hooking the destruction of a class's instance.
Ensures the deletion of all instance attributes, especially the
'protected' ones.
Signature:
None -> None
Version 1.0.0.0
"""
strAttributes = self.__dict__.keys()
for strAttr in strAttributes:
gAttrValue = self.__dict__[strAttr]
if hasattr(gAttrValue, '__delete__'):
try:
gAttrValue.__delete__(self)
self.__dict__[strAttrName] = None
except:
pass
try:
object.__delattr__(self, strAttr)
del gAttrValue
except:
pass
#public class methods
@classmethod
def getClassFields(cls):
"""
Returns a list of all public class attributes available to this class
and its instances - excluding the methods and properties.
Signature:
None -> list(str)
Returns:
list(str): names of the public class data field attributes
Version 1.0.0.0
"""
strlstResult = []
for clsParent in cls.__mro__:
for strName, objItem in clsParent.__dict__.items():
bCond1 = not strName.startswith('_')
bCond2 = not (strName in strlstResult)
bCond3 = not isinstance(objItem, (classmethod, staticmethod,
property, types.FunctionType))
if bCond1 and bCond2 and bCond3:
strlstResult.append(strName)
return strlstResult
@classmethod
def getClassMethods(cls):
"""
Returns a list of all public class and static methods available to this
class and its instances.
Signature:
None -> list(str)
Returns:
list(str): names of the public class and static methods
Version 1.0.0.0
"""
strlstResult = []
for clsParent in cls.__mro__:
for strName, objItem in clsParent.__dict__.items():
bCond1 = not strName.startswith('_')
bCond2 = not (strName in strlstResult)
bCond3 = isinstance(objItem, (classmethod, staticmethod))
if bCond1 and bCond2 and bCond3:
strlstResult.append(strName)
return strlstResult
@classmethod
def getInstanceMethods(cls):
"""
Returns a list of all public instance methods visible to this class and
its instances, although they can be used only by the instances.
Signature:
None -> list(str)
Returns:
list(str): names of the public instance methods
Version 1.0.0.0
"""
strlstResult = []
for clsParent in cls.__mro__:
for strName, objItem in clsParent.__dict__.items():
bCond1 = not strName.startswith('_')
bCond2 = not (strName in strlstResult)
bCond3 = not isinstance(objItem, classmethod)
bCond4 = isinstance(objItem, types.FunctionType)
if bCond1 and bCond2 and bCond3 and bCond4:
strlstResult.append(strName)
return strlstResult
@classmethod
def getProperties(cls):
"""
Returns a list of all public instance methods visible to this class and
its instances, although they can be used only by the instances.
Signature:
None -> list(str)
Returns:
list(str): names of the public instance methods
Version 1.0.0.0
"""
strlstResult = []
for clsParent in cls.__mro__:
for strName, objItem in clsParent.__dict__.items():
bCond1 = not strName.startswith('_')
bCond2 = not (strName in strlstResult)
bCond3 = isinstance(objItem, property)
if bCond1 and bCond2 and bCond3:
strlstResult.append(strName)
return strlstResult
#public instance methods
def getInstanceFields(self):
"""
Returns a list of all public instance attributes available to this
specific instance of the class.
Signature:
None -> list(str)
Returns:
list(str): names of the public instance attributes
Version 1.0.0.0
"""
strlstResult = list(filter(lambda x: not x.startswith('_'),
self.__dict__.keys()))
return strlstResult
class FixedAttributes(ProtectedAttributes):
"""
Abstract base class implementing the modified attributes access scheme
* C++ like static fields based on the class attributes
* Protected class and instance attributes
* Support of the descriptors on the class and instance level
* Class, static and instance methods and properties cannot be deleted
or assigned to from a class object without instantiation
* Class, static and instance methods cannot be deleted or assigned to
from an instance of a class
* Properties can be assigned to from an instance of a class if the
property has __set__ descriptor
* Properties can be deleted from an instance of a class if the property
has __delete__ descriptor
* Neither class nor instance data attributes can be deleted or created
during the lifetime of the object
Sub-classes ProtectedAttributes.
Sub-classes should re-define as not abstract the protected instance method
_onInit(), there the instance attributes are supposed to be created. Do not
change the __init__() method! If the _onInit() method is not re-defined the
sub-class cannot be instantiated and will act as a singleton.
Class methods:
getClassFields():
None -> list(str)
getClassMethods():
None -> list(str)
getInstanceMethods():
None -> list(str)
getProperties():
None -> list(str)
Methods:
getInstanceFields():
None -> list(str)
Version 1.0.0.0
"""
__metaclass__ = FixedMeta
#magic instance methods
def __delattr__(self, strAttrName):
"""
Special magic method hooking the deletion of an attribute on the class
instance level. Does not allow deletion of the attributes with the names
starting with a single underscore, excepting those starting with more
than one undescore.
Signature:
str -> None
Args:
strAttrName: str, name of an attribute to delete
Raises:
libexceptions.PrivateAttributeAccess: denied access to a protected
attribute
libexceptions.CustomAttributeError: denied delition of an existing
attribute
libexceptions.NotExistingAttribute: the attribute does not exist
Version 1.0.0.0
"""
objClass = object.__getattribute__(self, '__class__')
bCond1 = strAttrName.startswith('_')
bCond2 = not strAttrName.startswith('__')
if bCond1 and bCond2:
raise PrivateAttributeAccess(strAttrName, objClass, iSkipFrames = 1)
if hasattr(self, strAttrName):
raise CustomAttributeError(strAttrName, objClass, iSkipFrames = 1)
else:
raise NotExistingAttribute(strAttrName, objClass, iSkipFrames = 1)
def __setattr__(self, strAttrName, gValue):
"""
Special magic method hooking the modification of an attribute access on
the class instance level. Does not allow modification of the attributes
with the names starting with a single underscore, excepting those
starting with more than one undescore.
Signature:
str, type A -> None
Args:
strAttrName: str, name of an attribute to modify
gValue: type A, the value to assign
Raises:
libexceptions.PrivateAttributeAccess: denied access to a protected
attribute
libexceptions.NotExistingAttribute: assignment to a non-existing
attribute, i.e. denied creation of a new attribute
libexceptions.CustomAttributeError: denied modification of an
existing attribute, i.e. by its own desriptor
Version 1.0.0.0
"""
objClass = object.__getattribute__(self, '__class__')
bLocked = object.__getattribute__(self, '__dict__').get('_bLocked',
False)
bCond1 = strAttrName.startswith('_')
bCond2 = not strAttrName.startswith('__')
if bCond1 and bCond2 and bLocked:
raise PrivateAttributeAccess(strAttrName, objClass, iSkipFrames = 1)
if strAttrName in self.__dict__.keys():
if hasattr(self.__dict__[strAttrName], '__set__'):
self.__dict__[strAttrName].__set__(self, gValue)
else:
self.__dict__[strAttrName] = gValue
elif hasattr(self, strAttrName):
for objParent in self.__class__.__mro__:
if strAttrName in objParent.__dict__.keys():
gAttrValue = objParent.__dict__[strAttrName]
bCond1 = hasattr(gAttrValue, '__set__')
bCond2 = isinstance(gAttrValue, (classmethod, staticmethod,
property, types.MethodType,
types.FunctionType))
if bCond1:
try:
gAttrValue.__set__(self, gValue)
except Exception as err:
if isinstance(err, ConstantAttributeAssignment):
raise ConstantAttributeAssignment(strAttrName,
objClass, iSkipFrames = 1)
else:
raise CustomAttributeError(strAttrName, objClass,
iSkipFrames= 1)
elif bCond2:
raise CustomAttributeError(strAttrName, objClass,
iSkipFrames = 1)
else:
type.__setattr__(objParent, strAttrName, gValue)
else:
if bLocked:
raise NotExistingAttribute(strAttrName, objClass,
iSkipFrames = 1)
else:
self.__dict__[strAttrName] = gValue