marrow / schema

A generic declarative schema system.
MIT License
6 stars 3 forks source link

Expose descriptor object annotation hints to containing classes. #12

Open amcgregor opened 5 years ago

amcgregor commented 5 years ago

Trivial example:

from marrow.mongo import Document
from marrow.mongo.field import String

class Sample(Document):
    name:str = String()

This should stand out, glaringly, as a DRY failure. We are assigning a data descriptor object explicitly to handle strings, why must we declare, then, that instances contain strings within this attribute? The trivial example hides the scope of the majesty of this problem. A better example:

from bson import ObjectId as OID
from datetime import datetime, timedelta
from collections.abc import MutableMapping

from marrow.mongo import Document
from marrow.mongo.field import ObjectId

class Sample(Document):
    name:Union[OID,datetime,timedelta,MutableMapping,str,bytes] = ObjectId()

Ruh-roh! Requiring developers using Marrow Mongo to declare such a Union on every ObjectId field (even if abbreviated, e.g. through assignment of that Union to a variable) is a very bad idea. The descriptor itself knows what values it can handle, and what it will hand out. (Additionally, until lazy evaluation of annotations is more widespread, it'd be nice to not force those extra imports on people.)

Introduced in c2a4554d30ab14f86d527f370530fb7d258ca033 and patched in 98a0f5dcefc6167d64d36274cc5e7dd0e04b4ccb to permit preservation of explicit annotations, remaining are tests and documentation.

The Attribute subclasses implementing fields may then declare an annotation attribute, which will be hoisted up into the containing class' __annotations__.

MCVE. Demonstration of intent.

amcgregor commented 5 years ago

Partially implemented in develop, refinement to final form in #13 as utilized by the next branch of marrow.mongo.