pythonprintingfrozenset

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


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.


Solution

  • 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