Home > Mobile >  Python string plus extra data, mutability
Python string plus extra data, mutability

Time:01-31

I'm looking for a Python class that behaves exactly like str execpt that

  • it should be mutable, i.e., its content modifyable in-place, and
  • it should carry some extra data.

This

class MyString(str):
    def __init__(self, string):
        super().__init__()
        self._foo = "more data"


a = MyString("123")

print(a)
print(isinstance(a, str))
123
True
more data

works for the extra-data part, but I'm not sure if I can modify "123".

Any hints?

CodePudding user response:

The actual string data itself cannot be mutable with a subclass of str; str data is immutable.

If you need something that behaves in a string-like manner and you can mutate, you might build on top of collections.UserString, but even there you'd need to override additional methods to make it mutable, replacing the data member with a new str when you mutate it.

If you can live with raw binary data, not text data, subclassing bytearray might get you what you want, since bytearray is a mutable type. You could even override __str__ so it automatically decodes (based on a common default encoding, or one provided to the initializer) when stringified.

CodePudding user response:

Not sure if this is what you want:

class MyString(str):
    def __init__(self, string):
        super().__init__()
        self.string = string
        self._foo = "more data"

    def __str__(self):
        return self.string

    def modify(self, new_string):
        self.string = new_string


a = MyString("123")

print(a)
print(isinstance(a, str))
print(a._foo)

a.modify("456")

print(a)
print(isinstance(a, str))
print(a._foo)

Output:

123
True
more data
456
True
more data
  • Related