Change the __str__ function of frozenset (or any other native type)

173 Views Asked by At

I am working with frozensets.

When I do print(my_frozenset) the output is something like "frozenset({1, 2, 3})".

However I have many nested frozensets and I find this print very long and hard to read.

I want to modify it so that print(my_frozenset) outputs, for example, "fs{1,2,3}" or something different.

1

There are 1 best solutions below

0
mxp-xc On BEST ANSWER

It is not recommended to modify the native code directly.

You can define new function to print frozenset or new class inherit frozenset.

If you have to replace the built-in frozenset, you can try like this

import builtins


class _frozenset(frozenset):
    def __str__(self):
        return "custom..."


builtins.frozenset = _frozenset

print(frozenset([1, 2, 3]))

But this may cause unexpected errors