Safestruct serves as a base class for any class that wants to protect its members from misspelling.
Version: 1.0Safestruct serves as a base class for any class that wants to protect its members from misspelling.
Operating System: Linux
Since Python allows adding attributes to a class object at runtime, it is a simple mistake to assign to a non-existent attribute somewhere in your code, inadvertently creating a new attribute, and quietly introducing an error that may be very hard to find.
The Safestruct class traps all accesses to your class and raises an exception when an assignment is made to a non-existent attribute.
This class traps accesses to attributes and raises an exception when an assignment to a non-previously-existing attribute is performed. The idea is that of a "safe structure", as in C++ where each member of a class is declared at compile time and assignments to non-existent members cannot be made at run time. The safe structure guards against programming errors wherein attribute names are mispelled, leading to quiet runtime errors.
There are two classes defined here, TrappingStruct and NontrappingStruct. Both present the same interface but the latter does no attribute checking. It is meant to be used once the code is debugged, since it is faster.
The SafeStruct member is either set equal to TrappingStruct or NontrappingStruct (possibly by the SetDebug function) to easily switch from safe accesses to faster accesses by just changing one thing in one file.
See the test code at the bottom for example usage.