Suppose one writes a function relying on local objects whose instantiation can be somewhat taxing. I'd like to check whether a word is of the "woody" kind, here:
def is_woody(word): return word in {"gone", "vacuum", "prodding", "sausage", "bound", "vole", "recidivist", "caribou"}
The set will be instantiated during each function call, which is a waste. It doesn't matter whether the object is mutable or immutable; new instances will sprout after each function invocation.
In "C" one could declare a locally scoped function static variable, in "C#" one might declare a compile-time const ...
In Python, one might:
- declare the set in a parent scope and pass it down to the function as an argument — pollutes the namespace and function parameters, hinders the separation of concerns, etc.
- embed the set in a function attribute — requires either verbose syntax and impaired performance or the function attribute to be set in an outer scope
- create a singleton that initialises the set as a class attribute and contains a method accessing it — imposes object oriented approach, a multitude of singletons to keep concerns separate and slow class member access
Are there better patterns to address this rather trivial issue?