Created
October 24, 2021 14:48
-
-
Save vlad-bezden/cf6520a676f89879945ee85fb6eed279 to your computer and use it in GitHub Desktop.
Content manager for joining strings. Similar to "join" function,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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