Tips & Tricks
Dynamic Scope using Enums
The Problem
During database design it is common to have multiple tables that have the same column name that are used for the same purpose but contain different values based on the useage of the table.
An example of this might be a status column which can have different values depending on the table it is used in.
One way to address this is to have a global StatusMixin which is applied to every table and contains every value and it's
accessor methodsthat could be used in any table.
This can quickly become very complicated especially if some values can have multiple contexts.
An example is the value PENDING
This also means that any value can also be used in any table which could create data integirty issues.
Solution - Dynamic Scope using Enum for context
Overview
The global scope uses a provided Enum class to provide scope methiods named is_<enum value> for the class it is
attached to.
This means there is no accidental usage of methids which are not used in the table context.
It also throw KeyError for invalid string values used via the has_status() method
Setup
# statusMixin.py
from .statusScope import StatusScope
class StatusMixin:
"""Mixin to add methods for status filtering"""
def boot_StatusMixin(self, builder):
if not hasattr(self, "__statuses__"):
raise AttributeError("__statuses__ is not defined")
builder.set_global_scope(StatusScope(getattr(self, "__statuses__")))Usage
Example usage
Last updated