vendredi 15 avril 2022

Python. Dependency injection for user defined handler

I want to create some sort of dependency injection that I personally calls context_extractor (not sure that this is correct description).

Why: I use python-telegram-bot (PTB). A user defined handler in PTB looks like:

def my_handler(update, context):

Where update - event/update from a server (user messasge for an example), and context is access for all types of persistence data. my_handler expects exactly 2 arguments, this is PTB feature.

For an example access to saved user name looks like: context.user_data['name'] or even context.user_data['user_object'].name. Typing every time this lines is not cool. Using name = context.user_data['name'] - makes many overhead in code.

Here is declaration of user defined handler:

my_handler_cmd = CommandHandler(command=config.my_handler_s, callback=handlers.my_handler)

I want to make handler declaration with an optional dict:

my_handler_cmd = CommandHandler(command=config.my_handler_s, callback=handlers.my_handler, extra_data={'name': 'context.user.name', 'age': "context.user_data['user_object'].name"})

Key is are expecting variable name and value is path to this variable inside a context.

(all keys and values are literals but values can be replaced for an parent objects/classes) in future versions.

At this case a user defined handler becomes like: def my_handler(update, context, name, age: int = '') (recalls a Depends in FastAPI.

My questions:

  1. Is it a good idea and I choosed a good approach for implementation?
  2. Is a similar framework for this goal already exists for no reinventing a wheel?

Aucun commentaire:

Enregistrer un commentaire