Skip to content

Freeze TelegramObjects only after de_json #5248

@harshil21

Description

@harshil21

What kind of feature are you missing? Where do you notice a shortcoming of PTB?

Currently we freeze TelegramObject's directly after instantiation. This is slightly undesirable because:

  1. Duplication: You have to add that line at the end of __init__, or maybe you have first unfreeze it to set all the attributes? This is extra overhead for the developer while implementing API updates.
  2. Error prone: You can simply forget to freeze the object.
  3. User instantiated classes: Some classes which are meant to be manually instantiated and passed to the API shouldn't really be frozen. This was brought up before: see e.g. [DISCUSSION] Dataclasses #2698 (comment) (point 4)

Describe the solution you'd like

I propose freezing the class only after we've finished deserializing. This makes more sense because it represents that data from Telegram is actually immutable.

We already set the bot for TelegramObjects in _de_json, this will just be a single call to set the frozen attribute.

Describe alternatives you've considered

Using __init_subclass__ -- if you want to automatically freeze the object after instantiation. I benchmarked this and found it to be ~6% slower, which is much less than I expected but could be significant for larger bots.

However doing it in _de_json is simply more correct and cleaner.

Additional context

Every file would need to be updated to remove the call, and an test to check if the frozen attribute is being set in _de_json

Metadata

Metadata

Assignees

No one assigned

    Labels

    Priority

    Low

    Effort

    High

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions