pythonoopdjango-modelsdslclass-members

How python declarative attribute pattern is called


What is a name of the pattern that allows to define object instance variables as class variables?

Usually python object attributes are defined in __init__ method. Few libraries allow to define object attributes outside __init__:

# django models
class User(Model):
    name = fields.StringField()
    lastname = fields.StringField()

# django forms
class LoginForm(Form)
    username = fields.StringField()
    password = fields.PasswordField()

# elasticsearch_dsl
class Post(DocType):
    title = Text()
    created_at = Date()
    published = Boolean()

What is the name of this pattern?


Solution

  • Django, Elasticsearch DSL, and many other packages allow class level variables to declare/impose type-of-instance variables, reinforce behavior, transformation. I do not think there is a single official name for this pattern, yet usually it is called:

    Mind the term 'design pattern' was defined in the context of the "true" OOP languages such as Java and Smalltalk, as a way to handle some shortcomming, and not necesery applicable to solutions specific to Python. Functional programmers, for instance deny that work desing pattern is applicable to functional programming (since it is comletely free of any shortcomings:) Thus, likely, here is no official name for declarative attributes. Perhaps, "idiomatic" Python Class DSL might be better term than "pattern".

    While such API offer other controls such as different parent classes, hooks, etc the most striking feature is use of class variables to model the similarly named instance variables.

    The modern Class DSL API are usually used in model transformation, Active-Record or Data-Mapper patterns, yet is not limited too.

    Django is classic example of Active-Record implementation, which is defined by 3 as f

    The active record pattern is an approach to accessing data in a database. A database table or view is wrapped into a class. Thus, an object instance is tied to a single row in the table... The wrapper class implements accessor methods or properties for each column in the table or view.

    "

    Technique, on which such 'magic' declarative class oriented API packages are based called meta-programming. Even Python does not have any means to declare object or class variables out of box, it offers means to create such declaration, via meta programming, specific DSL API, which is exploited by Django, SQL Alchemy, Elastic Search and alike, typically using class variables. While class-variable DSL most often used in object serialization to other models/formats, generic class declaration packages that aim at improving and "dedunderifying" Python OOP in general are not unheard of, e.g. https://github.com/python-attrs/attrs

    Few side notes: