Golden String: A Python design pattern to salvage a function returning a string
What to do if you have a well-used API with a function returning a string, and you want to return other information without breaking the calling code?
Pass that information as attributes to the string itself! Since the standard str type does not allow it, a new class GoldenStr must be created.
In the called function
In the called function, you could use the code below to write:
text = GoldenStr(text) text.attr1 = .... text.attr2= ... return text
text = GoldenStr(text, attr1=..., att2=...)
On a large project where APIs need to be documented and predictable, you would want to define an ad-hoc subclass of
str with well defined (and documented) properties instead of attributes. Using properties would allow the programmer of a calling function to have easier access to those new features, e.g. through the use of the
help function. It is important to remember that such a class must be defined through
__new__ and not
Any existing calling function would be undisturbed, since the new returned object is entirely compatible with the str class and will even respond True to
is_instance(str). A new calling function could, however, access that newly available information if it needs it.
class GoldenStr(str): "A string with attached values" def __new__(cls, content, **kwargs): "Intialize the object, with additional parameters" instance = super().__new__(cls, content) for k in kwargs: setattr(instance, k, kwargs[k]) return instance
This method can be generalized to functions returning other immutable types (int, float...)
On the Name
A Golden Thread "something obvious that leads to other things or is woven into other things"; particularly a clear maxim that governs action (used e.g. in case law). See also Ariadne's Thread, used to help Theseus get out of the Labyrinth (which was red). Applied by analogy to a character string.