Optimizing unpacking constants values

I had one use case…

cls.pretty_units_of_any(size, 1000.,  'B',
                                      ('', *'kMGTPEZY')

Why not

cls.pretty_units_of_any(size, 1000., 'B',
                                      ('', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')


I was a little surprised when I found out that it actually loads this constant 'kMGTPEZY' and turns it into Starred Expression (unpacks into this tuple)
Although a fairly obvious way would be to immediately form a ready-made tuple ('', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')

I wrote a prototype of what needs to be done on my knee (for clarity, I just took NodeTrabsformer, the implementation is certainly not without flaws).

from ast import *
from typing import Iterable

class Visitor(NodeTransformer):
    __slots__ = ()

    def _reform_const_elements(self, elts: list[expr]) -> list[expr]:
        new_elts = []
        for elt in elts:
            if isinstance(elt, Starred):
                if isinstance(elt.value, Constant) and isinstance(elt.value.value, Iterable):
                    for val in elt.value.value:
                elif isinstance(elt.value, (Tuple, List)):
                    new_elts += self.visit(elt.value).elts
        return new_elts

    def _visit_constant_starred(self, node: expr) -> expr:
        node.elts = self._reform_const_elements(node.elts)
        return node

    visit_Tuple = visit_List = visit_Set = _visit_constant_starred

In this particular case, a calculation speedup of 90-95%

So I think additional conversions might be justified.

I would have put the tuple in a global for maintenance reasons, then the optimisation is not needed.

Do you see this pattern often in python code?

I had to deal with such writing. But yes, this is not a common practice.

In fact, this is just for the beauty and brevity of the code, although the programmer is able to follow this himself (the idea is to not have to do it).