Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Created October 24, 2021 14:48
Show Gist options
  • Save vlad-bezden/cf6520a676f89879945ee85fb6eed279 to your computer and use it in GitHub Desktop.
Save vlad-bezden/cf6520a676f89879945ee85fb6eed279 to your computer and use it in GitHub Desktop.
Content manager for joining strings. Similar to "join" function,
from contextlib import contextmanager
from typing import List, Any, Iterator
class StringJoiner(List[str]):
def __init__(self, sep: str = " ", *args: str) -> None:
super().__init__(*args)
self.sep = sep
@contextmanager
def joiner(*args: Any) -> Iterator[StringJoiner]:
string_list = StringJoiner(*args)
try:
yield string_list
finally:
string_list.result = f"{string_list.sep}".join(string_list)
# usage example
with joiner(", ") as j:
j.append("Hello World!!!")
j.append("Happy Coding!!!")
print(j.result)
# Hello World!!!, Happy Coding!!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment