So, there is no explicit C#- or Java-style StringBuilder class provided with Python.
Note, I am a bit new to Python, so I am not sure if my idea is a good one.
Suppose I want to have a decorator (if possible) that would join the iterables together. This particular example can be implemented differently, but I can think of other use cases. So …
@string_builder
def build_insert_statement(table_name, col_names, values, where_clause):
yield 'insert into '
yield table_name
yield ' ( '
yield ', '.join(col_names)
yield ' ) values ( '
yield ', '.join(values)
yield ' ) where '
yield where_clause
yield ';'
Again, I know that there are alternative ways to do this. However, can this be done? Can a decorator always respect the original function’s signature or only sometimes or not at all? If this is possible, then is it a heresy? Why?
The following definition for
string_buildershould work:Using the function defined in your question with
string_builderas a decorator:Note that using [
functools.wraps][1] is not necessary, but it is good practice because without it the name of the function (build_insert_statement.__name__) after decoration would be “wrapped” instead of “build_insert_statement”.So it is possible, is it a good idea?
Not for your example, but you said you have other use cases. A decorator like this is not heresy, but you shouldn’t overuse decorators because it can obscure the implementation.
If you are just worried about line length, consider one of the following alternatives:
Using
''.join()on a list:Combining the strings with
+: