Python construct a mutable global object from another global object

141 views Asked by At

I have main.py and app.py. app.py contains create_app() which returns the app object. main.py calls create_app(). I have to construct a mutable global object in main.py. This global object takes app as input parameter. This seems complex to me in python. How do I possibly achieve this global object construction when the application starts up?

Specifically, I am using flask_oidc and needs to construct an oidc = OpenIDConnect(app) in main.py and makes oidc object available in other controller .py files. This oidc object will store user info and validates if a user is authenticated.

Any advice and insight is appreciated.

1

There are 1 answers

7
Tushar Kolhe On

You can create a module that initialize your oidc object at the start of the application

helper.py

oidc = None # global instance

def init_oidc(app):
  # initalise the oidc here and assign to the global variable
  global oidc
  oidc = OpenIDConnect(app)
  return oidc

main.py

import init_oidc from helper


app = create_app()
# init only once at the start of the application
oidc = init_oidc(app)

In other controller files sample_controller.py

import oidc from helper

# use the same oidc here

The other option is to create a singleton class with a attribute oidc in it, it will be helpfull if you need other methods along with oidc