python-betterproto icon indicating copy to clipboard operation
python-betterproto copied to clipboard

Provide a way to use a custom base class instead of betterproto.Message

Open domeniconappo opened this issue 9 months ago • 2 comments

Summary

Allow to customize the base class, to provide helper methods and enrich the model

What is the feature request for?

The core library

The Problem

We developed an internal library on top of betterproto and pika rabbitmq packages. During development, we found that

  1. betterproto lacks a way to customize the base class for the generated messages classes.
  2. it's not possible to access message classes in the following way:
import mylib as ml

ml.messages.device.settings.ConfigureDevice(*args)

The Ideal Solution

To ease all above, would be handy to provide:

  1. A way to use a MyMessageBaseClass(betterproto.Message) as base class for generated messages. This would probably be a new cli argument for the compiler e.g. --base_class=mylib.base.MyMessageBaseClass to use in the init jinja template.
  2. import subpackages (if any) in the __init__.py generated files.

The Current Solution

To enrich the classes with helper methods and to override some methods of the betterproto.Message class, we first patched the generated classes, to add mixins and overridden methods at runtime.

This is working well, but Python IDEs' support is limited.

We solved some of the issues above by adding a post compilation step at installation time, to add code to the betterproto generated files. During this step, we also add subpackages imports to __init__.py files, to access messages conveniently using the fqn (see point 2. of the issue).

domeniconappo avatar Apr 04 '25 11:04 domeniconappo

I do this I think in an ok way in my own library (See https://github.com/Gobot1234/steam.py/tree/main/steam/protobufs/msg.py) this is a pretty niche feature. If you're wanting extra build steps I'd recommend just having a build script that runs a find and replace.

Gobot1234 avatar Apr 07 '25 19:04 Gobot1234

I do this I think in an ok way in my own library (See https://github.com/Gobot1234/steam.py/tree/main/steam/protobufs/msg.py) this is a pretty niche feature. If you're wanting extra build steps I'd recommend just having a build script that runs a find and replace.

Thanks for the reply! I will have a look at that part of the code as it looks interesting. I've ended up having an extra build script that does post_compilation.

domeniconappo avatar Nov 03 '25 14:11 domeniconappo