format integers in a sequence (list, tuple, set)

Viewed 75

I have a class where one of the members is an integer sequence. It may be one of list, tuple or set. When in print (__str__) the instances of this class, I need to format the integers but keep the type of the sequence.

As an example i have the class

class A:
    def __init__(self, seq):
        self.seq = seq

and the three instances

a = A(seq=tuple(range(5, 12)))
b = A(seq=list(range(17, 21)))
c = A(seq=set(range(26, 31)))

and I would like to have the following output for

print(a)  # A(seq=(0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b))
print(b)  # A(seq=[0x11, 0x12, 0x13, 0x14])
print(c)  # A(seq={0x1a, 0x1b, 0x1c, 0x1d, 0x1e})

My first try was this (and it does not work! the items are represented as strings.)

class A:

    def __str__(self):
        seq2 = self.seq.__class__(f"0x{i:02x}" for i in self.seq)
        return f"A(seq={seq2})"

# A(seq=('0x05', '0x06', '0x07', '0x08', '0x09', '0x0a', '0x0b'))
# A(seq=['0x11', '0x12', '0x13', '0x14'])
# A(seq={'0x1b', '0x1c', '0x1d', '0x1a', '0x1e'})

An approach that works but seems very clumsy is this:

class A:

    def __str__(self):
        item_str = ", ".join(f"0x{i:02x}" for i in self.seq)
        if isinstance(self.seq, list):
            o, c = "[", "]"
        elif isinstance(self.seq, tuple):
            o, c = "(", ")"
        elif isinstance(self.seq, set):
            o, c = "{", "}"
        else:
            raise ValueError
        return f"A(seq={o}{item_str}{c})"

# A(seq=(0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b))
# A(seq=[0x11, 0x12, 0x13, 0x14])
# A(seq={0x1a, 0x1b, 0x1c, 0x1d, 0x1e})

Is there not a more elegant version of this? Or do I have to subclass list, tuple and set to a version that allows for formatting options in __str__?

2 Answers

Just use str.replace():

class A:
    def __init__(self, seq):
        self.seq = seq

    def __str__(self):
        seq2 = self.seq.__class__(f"0x{i:02x}" for i in self.seq)
        return f"A(seq={seq2})".replace("'", '')

a = A(seq=tuple(range(5, 12)))
b = A(seq=list(range(17, 21)))
c = A(seq=set(range(26, 31)))

print(a)
print(b)
print(c)

Prints:

A(seq=(0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b))
A(seq=[0x11, 0x12, 0x13, 0x14])
A(seq={0x1b, 0x1c, 0x1a, 0x1d, 0x1e})

I would use an addressing dictionary:

class A:
    def __str__(self):
        wrappers = {
            list : "[]",
            tuple: "()",
            set  : "{}",
        }
        item_str = ", ".join(f"0x{i:02x}" for i in self.seq)
        o, c = wrappers.get(type(self.seq), "||")
        return f"A(seq={o}{item_str}{c})"
Related