Package: instruct
A compact, fast object system that can serve as the basis for a DAO model.To that end, instruct uses__slots__to prevent new attribute addition, properties to control types, event listeners and historical changes, and a Jinja2-driven codegen to keep a pure-Python implementation as fast and as light as possible.I want to basically have a form of strictly typed objects that behave like C structs but can handle automatically coercing incoming values correctly, have primitive events and have fast__iter__,__eq__while also allowing for one to override it in the final class (and even call super!)This girl asks for a lot but I like taking metaclassing as far as it can go without diving into using macropy. 😉Current Capabilities:Support multiple inheritance, chained fields and__slots__[Done]Support type coercions (via_coerce__) [Done]Strictly-typed ability to define fixed data objects [Done]Ability to drop all of the above type checks [Done]Track changes made to the object as well as reset [Done]Fast__iter__[Done]Native support of pickle [Done]/json [Done]Support List[type] declarations and initializations [Done]optionally data class annotation-like behavior [Done]_asdict,_astuple,_aslistfunctions like in a NamedTuple [Done]get,keys,values,itemfunctions available in the module and in a mixin namedmapping=TrueThis effectively allows access like other packages e.g.attrs.keys(item_instance)bytes/bytearrayare urlsafe base64 encoded by default, can override per field via a class levelBINARY_JSON_ENCODERS = {key: encoding_function}[Done]Allow__coerce__to have a tuple of field names to avoid repetition on__coerce__definitions [Done]Allow use ofLiteralin the type (exact match of a value to a vector of values) [Done]Allow subtraction of properties like(F - {"a","b"}).keys()== F_without_a_b.keys()[Done]This will allow one to slim down a class to a restricted subtype, like for use in a DAO system to load/hold less data.Allow subtraction of properties like(F - {"a":{"b"}).keys()== F_a_without_b.keys()[Done]This allows for one to remove fields that are unused prior to class initialization.Allow subtraction of properties via an inclusive list like(F & {"a","b"}).keys()== F_with_only_a_and_b.keys()[Done]Allow subtraction to propagate to embedded Instruct classes like(F - {"a.b","a.c"}).a.keys()== (F_a.keys() - {"b","c"))[Done]This would really allow for complex trees of properties to be rendered down to thin SQL column selects, thus reducing data load.Replace references to an embedded class in a__coerce__function with the subtracted form in case of embedded property subtractions [Done]Allow use of Annotated i.e.field: Annotated[int, NoJSON, NoPickle]and haveto_jsonandpickle.dumps(...)skip “field” [Done]Would grant a more powerful interface to controlling code-gen’ed areas viacls._annotated_metadata(maps field -> what’s inside theAnnotation)Next Goals:Allow Generics i.e.class F(instruct.Base, T): ...->F[str](...)Would be able to allow specialized subtypesCStruct-Base class that operates on an_cvaluecffi struct.Cython compatibilityDesign GoalThis comes out of my experience of doing multiple object systems mean to represent database relations and business rules. One thing that has proven an issue is the requirements for using as little memory as possible, as little CPU as possible yet prevent the developer from trying to stick a string where a integer belongs.Further complicating this model is that desire to “correct” data as it comes in. Done correctly, it is possible to feed aninstruct.Base-derived class fields that are not of the correct data type but are eligible for being coerced (converted) into the right type with a function. With some work, it’ll be possible to inline alambda val: ...expression directly into the setter function code.Finally, multiple inheritance is a must. Sooner or later, you end up making a single source implementation for a common behavior shared between objects. Being able to share business logic between related implementations is a wonderful thing.Wouldn’t it be nice to define a heirachy like this:importpickleimportdatetimefromtypingimportListtry:fromtypingimportAnnotatedexceptImportError:fromtyping_extensionsimportAnnotatedfrominstructimportBase,NoJSON,NoIterable,NoPickle,NoHistoryclassMember(Base):__slots__={"first_name":str,"last_name":str,"id":int}def_set_defaults(self):self.first_name=self.last_name=""self.id=-1super()._set_defaults()classOrganization(Base,history=True):# ARJ: Note how we can also use the dataclass/typing.NamedTuple# definition format and it behaves just like the ``__slots__`` example# above!name:strid:intmembers:List[Member]created_date:datetime.datetimesecret:Annotated[str,NoJSON,NoPickle,NoIterable,NoHistory]__coerce__={"created_date":(str,lambdaobj:datetime.datetime.strptime("%Y-%m-%d",obj)),"members":(List[dict],lambdavalues:[Member(**value)forvalueinvalues]),}def_set_defaults(self):self.name=""self.id=-1self.members=[]self.created_date=datetime.datetime.utcnow()super()._set_defaults()And have it work like this?data={"name":"An Org","id":123,"members":[{"id":551,"first_name":"Jinja","last_name":"Ninja"}],}org=Organization(secret="my secret",**data)assertorg.members[0].first_name=="Jinja"assertorg.secret=="my secret"org.name="New Name"org.created_date=datetime.datetime(2018,10,23)print(tuple(org.list_changes()))# Returns# (#     LoggedDelta(timestamp=1652412832.7408261, key='name', delta=Delta(state='default', old=Undefined, new='', index=0)),#     LoggedDelta(timestamp=1652412832.7408261, key='id', delta=Delta(state='default', old=Undefined, new=-1, index=0)),#     LoggedDelta(timestamp=1652412832.7408261, key='members', delta=Delta(state='default', old=Undefined, new=[], index=0)),#     LoggedDelta(timestamp=1652412832.7408261, key='created_date', delta=Delta(state='default', old=Undefined, new=datetime.datetime(2022, 5, 13, 3, 33, 52, 740650), index=0)),#     LoggedDelta(timestamp=1652412832.740923, key='id', delta=Delta(state='initialized', old=-1, new=123, index=4)),#     LoggedDelta(timestamp=1652412832.741002, key='members', delta=Delta(state='initialized', old=[], new=[<__main__.Member._Member object at 0x104364640>], index=5)),#     LoggedDelta(timestamp=1652412832.741009, key='name', delta=Delta(state='initialized', old='', new='An Org', index=6)),#     LoggedDelta(timestamp=1652412832.741021, key='name', delta=Delta(state='update', old='An Org', new='New Name', index=7)),#     LoggedDelta(timestamp=1652412832.741031, key='created_date', delta=Delta(state='update', old=datetime.datetime(2022, 5, 13, 3, 33, 52, 740650), new=datetime.datetime(2018, 10, 23, 0, 0), index=8))# )assertnotany(y=="my secret"foryintuple(org))assertOrganization.to_json(org)=={"created_date":"2018-10-23T00:00:00","id":123,"members":[{"first_name":"Jinja","id":551,"last_name":"Ninja"}],"name":"New Name",}org2=pickle.loads(pickle.dumps(org))assertorg2.secretisNoneassertorg2.to_json()=={"created_date":"2018-10-23T00:00:00","id":123,"members":[{"first_name":"Jinja","id":551,"last_name":"Ninja"}],"name":"New Name",}Example Usage>>>frominstructimportBase>>>>>>classMyClass(Base):...foo:int...bar:Optional[str]...baz:Union[Dict[str,str],int]...def__eq__(self,other):...ifisinstance(other,tuple)andlen(other)==3:...# Cast the tuple to this type!...other=MyClass(*other)...returnsuper().__eq__(other)...>>>instance=MyClass(1,None,baz={"a":"a"})>>>assertinstance.foo==1>>>assertinstance.barisNone>>>instance.bar="A String!">>>>>>assertinstance==(1,"A String!",{"a":"a"})>>>>>>instance.foo='I should not be allowed'Traceback (most recent call last):File"<stdin>", line1, in<module>File"<getter-setter>", line36, in_set_fooTypeError:Unable to set foo to 'I should not be allowed' (str). foo expects a int>>>Instruct adds aRangetype for use inAnnotated[...]type definitions.RangeclassRange(lower,upper,flags:RangeFlags=<RangeFlags.CLOSED_OPEN:4>,*,type_restrictions:Tuple[Type,...]=())...loweranduppercan be anything that supports__lt__,__gt__,__eq__.type_restrictionscan be used to apply a Range constraint to some value types.flagscan be used to set theinterval type. Default is closed-open [).>>>fromtypingimportTuple,type>>>frominstructimportRange,RangeFlags,RangeError>>>lower,upper=0,255>>>r=Range(lower,upper,flags:RangeFlags=RangeFlags.CLOSED_OPEN)>>>10inrTrue>>>0inrTrue>>>256inrFalseWhen used inside aninstruct-derived class, an attempt to assign a value that doesn’t satisfy a tuple of ranges will throw a RangeError (inherits from ValueError and TypeError).Inside is thevalue(what was rejected) and a copy of the ranges atrangesthat were tried (and failed). If thetype_restrictionsare specified in a range, it will not be tried if the value type isn’t applicable.classRangeError(value:Any,ranges:Tuple[Range,...],message:str="")...Example:>>>frominstructimportSimpleBase,Range>>>fromtyping_extensionsimportAnnotated>>>fromtypingimportUnion>>>classPlanet(SimpleBase):...mass_kg:Annotated[Union[float,int],Range(600*(10**18),1.899e27)]...radius_km:Annotated[Union[float,int],Range(2439.766,142_800)]...>>>>>>mercury=Planet(3.285*(10**23),2439.766)>>>mars=Planet(0.64169*(10**24),3376.2)>>>>>>pluto=Planet(1.30900*(10**22),1188.30742)Traceback (most recent call last):File"/Users/autumn/software/instruct/instruct/__init__.py", line2113, in__init__setattr(self,key,value)File"<getter-setter>", line30, in_set_radius_kmFile"/Users/autumn/software/instruct/instruct/typedef.py", line40, in__instancecheck__returnfunc(instance)File"/Users/autumn/software/instruct/instruct/typedef.py", line227, intest_funcraiseRangeError(value,failed_ranges)instruct.exceptions.RangeError:('Unable to fit 1188.30742 into [2439.766, 142800)', 1188.30742, (Range(2439.766, 142800, flags=CLOSED_OPEN, type_restrictions=()),))The above exception was the direct cause of the following exception:

Traceback (most recent call last):File"<stdin>", line1, in<module>File"/Users/autumn/software/instruct/instruct/__init__.py", line2128, in__init__self._handle_init_errors(errors,errored_keys,unrecognized_keys)File"/Users/autumn/software/instruct/instruct/__init__.py", line2094, in_handle_init_errors)fromerrors[0]instruct.exceptions.ClassCreationFailed:('Unable to construct Planet, encountered 1 error', RangeError('Unable to fit 1188.30742 into [2439.766, 142800)', 1188.30742, (Range(2439.766, 142800, flags=CLOSED_OPEN, type_restrictions=()),)))>>>Comparison to PydanticPydantic is a much larger project with many more eyes. Instruct was designed from the beginning to support multiple-inheritance and__slot__specialization. Pydantic does much the same as Instruct. Pydantic is much more feature-filled and infinitely more popular. Instruct is a one-woman crew.Instruct was a reflexive response to years of dealing with needing to handle Object-Relational impedance mismatch in MySQL/Postgres. It was meant as a building block for enabling templated SQL writing in a controlled manner without resorting to ORMs (more akin to DAO approach). As such, its design and evolution reflects that.Instruct is not better. Nor is it worse. Instruct simply does what it’s designed to do and no more.I suggest you use Pydantic if you’re interested in a far bigger, far more lively, far better supported library. Instruct has different ambitions and does not intend to replace or compete with Pydantic.Instruct was designed in October 7, 2017 but was released in Dec 9, 2018.Pydantic’s earliest release (0.1.0) is in 2017-06-03.Design differences between the two:Instruct attempts toNOTprovide functions/attributes that may be clobbered viaSimpleBaseand remapping the public variables to_{{varname}}_Pydantic allows one to override the remapping, but does occupy names likedict,json, etc,.Pydantic providesModelproperties likedict(),json(),copy(), etcInstructBase(viaJSONSerializable) providesto_json,__json__,from_json,from_many_jsonIf you useSimpleBase, you can access similar properties ONLY on the class itself (we do not attach it to the class instance to avoid clobbering)Instruct is shifting to a paradigm of using free-functions likeasdict,astuple,keys,items,values, etc instead of clobbering fields on an objectwe want to allow as many user-specified names as possibleInstruct wants to remain smallInstruct wants to supportCStruct``sand possible basis for using a ``bytearrayas the underlying memory for enabling rich types while allowing a nearmemcpy.Things Instruct can do that Pydantic doesn’t:Class subtraction and maskingYou can subtract out a field by a string represetation, multiple by subtracting out anIterable[str], or even apply such via a nested dict (where the values areNoneor another mapping to apply to a sub-object)You cancls & {"field"}orcls & {"field":{"keep_this"}}and get a class with onlyfieldandfield.keep_thisAllows unsupported types by fields to call functions to parse/coerce it into a valid value (__coerce__)Pydantic suggests you useData bindto handle weirdiesPydantic does a lot of conversions for you automaticallyInstruct demands you make them explicit in your handling functions.Instruct creates custom types representing complex, nested data structures such it does an effectisinstance(value, ComplexType)to verify if a complex, nested tree of objects does match.The types are meant only for anisinstancecheck.Things Pydantic does that Instruct doesn’t:Discriminated Unions (Current approach in Instruct is to add the common class into the Union and specialize after__init__or do it in the__coerce__phase)Type/Callable/Generator attribute assignmentGenerics (on my todo)validation (instruct is used to provide the building blocks for validation, not doing it by itself. That might change.)actual mypy, vscode, pycharm, etc integrationschema exportaliases (Instruct expects you to just add a@propertythat gets/sets the true field)lots more little goodiesDesignSolving the multiple-inheritance and__slots__problemConsider the following graph:Base1    Base2
     \  /
   Class AIf both defined__slots__ = (), Class A would be able to declare__slots__to hold variables. For now on, we shall consider both Base’s to have__slots__ = ()for simplicity.However, consider this case:Base1    Base2
     \  /
   Class A     Class B
          \    /
          Class CNow this isn’t possible if Class A has non-empty__slots__.But what if we could change the rules. What if, somehow, when you__new__ed a class, it really gave you a specialized form of the class with non-empty__slots__?Such a graph may look like this:Base1    Base2
     \  /
   Class A     Class B
      |  \    /     |
Class _A  Class C  Class _B
            |
          Class _CNow it is possible for any valid multiple-inheritance chain to proceed, provided it respects the above constraints - there are either support classes or data classes (denoted with an underscore in front of their class name). Support classes may be inherited from, data classes cannot.Solving the Slowness issueI’ve noticed that there are constant patterns of writing setters/getters and other related functions. Using Jinja2, we can rely on unhygenic macros while preserving some semblance of approachability. It’s more likely a less experienced developer could handle blocks of Jinja-fied Python than AST synthesis/traversal.Callgraph PerformanceRelease Process$ rm -rf dist/* && python -m pytest tests/ && python setup.py sdist bdist_wheel && twine upload dist/*BenchmarkLatest benchmark run::(python) Fateweaver:~/software/instruct [master]$ python --version
Python 3.7.7
(python) Fateweaver:~/software/instruct [master]$ python -m instruct benchmark
Overhead of allocation, one field, safeties on: 19.53us
Overhead of allocation, one field, safeties off: 19.50us
Overhead of setting a field:
Test with safeties: 0.27 us
Test without safeties: 0.17 us
Overhead of clearing/setting
Test with safeties: 0.75 us
Test without safeties: 0.65 us
(python) Fateweaver:~/software/instruct [master]$Before additions of coercion, event-listeners, multiple-inheritance$ python -m instruct benchmark
Overhead of allocation, one field, safeties on: 6.52us
Overhead of allocation, one field, safeties off: 6.13us
Overhead of setting a field:
Test with safeties: 0.40 us
Test without safeties: 0.22 us
Overhead of clearing/setting
Test with safeties: 1.34 us
Test without safeties: 1.25 usAfter additions of those. Safety is expensive.$ python -m instruct benchmark
Overhead of allocation, one field, safeties on: 19.25us
Overhead of allocation, one field, safeties off: 18.98us
Overhead of setting a field:
Test with safeties: 0.36 us
Test without safeties: 0.22 us
Overhead of clearing/setting
Test with safeties: 1.29 us
Test without safeties: 1.14 us