Skip to content

Instantly share code, notes, and snippets.

@amcgregor
Last active October 21, 2019 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amcgregor/e4c251bf494ddb10f9a87da4c4d00395 to your computer and use it in GitHub Desktop.
Save amcgregor/e4c251bf494ddb10f9a87da4c4d00395 to your computer and use it in GitHub Desktop.
A comparison of various ways of (declaratively) defining classes whose attributes comprise instance fields.
from typeguard import typechecked
class Foo:
@typechecked
def __init__(self, name: str, age: int, gender: str = 'na'):
self.name = name
self.age = age
self.gender = gender
print(Foo.__annotations__.get('name')) # -> None -- ugh, it's in the damn constructor.
from dataclasses import dataclass
@dataclass
class Foo:
name: str
age: int
gender: str = 'na'
print(Foo.__annotations__.get('name')) # -> str -- simple, yay! but… absolutely no way to specify behaviour.
from marrow.schema import Container, Attribute
class Foo(Container):
name = Attribute()
age = Attribute()
gender = Attribute(default='na')
print(Foo.__annotations__.get('name')) # -> None -- bugger, but sorta makes sense, these are generic "attributes"
from marrow.mongo import Document
from marrow.mongo.field import String, Integer
class Foo(Document):
name = String()
age = Integer()
gender = String(choices=('m', 'f', 'na'), default='na')
print(Foo.__annotations__.get('name')) # -> str -- works as of today
# Imports **purely** for type annotation. >_<
from typing import Union
from bson import ObjectId as OID
from collections.abc import MutableMapping
from datetime import datetime, timedelta
# Actual imports.
from marrow.mongo import Document
from marrow.mongo.field import ObjectId
class Foo(Document):
id: Union[OID,datetime,timedelta,MutableMapping,str,bytes] = ObjectId()
# Imagine having to put that "boilerplate" everywhere you use an ObjectId field.
# Let me think long and no.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment