mercredi 14 juillet 2021

Optimal way to access class instances globally

I need to access class instances from various modules within my application

Current solution:

I am using the Flask framework, with the Blueprints design pattern. Because Python objects can have other (arbitrary) objects 'attached' to them as attributes and Flask allows you to access the current app globally using the current_app alias I am doing the following:

#app.py
def app_factory() -> Flask:
    app = Flask(...)

    # attaching instances to my flask app
    app.ExampleClassInstance0 = ExampleClass0(...)
    app.ExampleClassInstance1 = ExampleClass1(...)
    app.ExampleClassInstance2 = ExampleClass2(...)

    return app

Which allows me easy access to these instances:

#blueprint.py
from flask import current_app as app


data = app.ExampleClassInstance0.<method>()
other_data = app.ExampleClassInstance1.<attribute>

Is there a better way to manage these global instances? It seems like a possible OO-antipattern to me but I'm still fairly novice in this area. How do people typically share state throughout apps of this nature? I'm also interested in the rationale behind solutions.

Aucun commentaire:

Enregistrer un commentaire