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

Add a __class_getitem__ to Formatter #2665

Merged
merged 1 commit into from Mar 24, 2024
Merged

Conversation

Akuli
Copy link
Contributor

@Akuli Akuli commented Mar 16, 2024

This is a simpler and less disruptive alternative to #2081.

The type stubs in typeshed distinguish between formatters that output strings and bytes. In type annotations, these are distinguished with Formatter[str] and Formatter[bytes]. For the most part, this works fine without any changes in pygments: users just tell Python to not evaluate type annotations at runtime (with from __future__ import annotations), and then a Formatter[str] type annotation won't cause an error even though subscripting the Formatter class wouldn't work.

But one special case happens when you try to subclass a Formatter. For that, you actually need to specify a class, not a type annotation. So users end up with:

from typing import TYPE_CHECKING
from pygments.formatter import Formatter

if TYPE_CHECKING:
    StringFormatter = Formatter[str]
else:
    StringFormatter = Formatter

class MyFormatter(StringFormatter):
   ...

With this PR, this simplifies to:

from pygments.formatter import Formatter

class MyFormatter(Formatter[str]):
   ...

@Anteru Anteru merged commit 2b9936c into pygments:master Mar 24, 2024
13 checks passed
@Anteru
Copy link
Collaborator

Anteru commented Mar 24, 2024

Merged, thanks!

@Anteru Anteru added this to the 2.18.0 milestone Mar 24, 2024
@Akuli Akuli deleted the class-getitem branch March 24, 2024 15:44
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.

None yet

2 participants