Skip to content

Instantly share code, notes, and snippets.

@fralau fralau/GoldenString.md
Last active Mar 29, 2018

Embed
What would you like to do?
Golden String (pattern):

Golden String: A Python design pattern to salvage a function returning a string

Problem:

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?

Solution

Principle

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

or:

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 __init__.

Calling function

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.

Code

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

Notes

Generalization

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.