Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support 'oxford comma' format and non-string types in listing #690

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

zwimer
Copy link

@zwimer zwimer commented Sep 27, 2024

Fixes: #693

This PR:

  1. Adds support for the 'oxford comma' format list format in listing. Depending on location etc., some people list items using an oxford comma. For example:
x = []
for i in range(3):
    x.append(i)
    print(listing(z, ",", "and"))
    print(listing(z, ",", "and", oxford=True))

Prints out

0
0
0 and 1
0 and 1
0, 1 and 2
0, 1, and 2

The default is oxford=False to avoid changing the default behavior.

  1. Allows the use of types other than str in listing. The code for this function almost entirely already allowed this, this PR mostly changes type annotations and adds a couple of str() calls to fully support it. This allows for things like:
class Translate:
    def __init__(self, msg, language):
        self.msg = msg
        self.language = language
    def __str__(self) -> str:
        return translate(self.language, self.msg)   #  External API call 

print(listing([1, 2], ","))  # Non-string items
print(listing([1, 2], ",", Translator("and", "Spanish"))  # Non-string separators and conjunctions

Which may print:

1, 2
1 y 2
  1. Fixes type annotation on items. Python defines list type as invariant; we should use Sequence instead as that is covariant. That is:
class Special(str):
    pass

s = [Special("")]

x: list[str] = s       # type error: since list is invariant, list[Special] is not a list[str]
y: Sequence[str]  = s  # ok: since Sequence is covariant, list[DerivedClass] is a list[BaseClass]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Oxford comma support in listings
1 participant