Hi everyone,
Now that PEP 750 is accepted, I’d like to discuss how tools can detect what language is inside a template string. For example, when we write:
query = t"SELECT * FROM users WHERE id = {user_id}"
Ideally, our IDEs should highlight the SQL syntax. But how can our tools determine that this template contains SQL?
The PEP mentions this challenge but delegates the solution to the community: PEP 750 – Template Strings | peps.python.org
I’ve been experimenting with using Annotated
for this:
from typing import Annotated
from templatestrings import Template # or wherever this ends up
query: Annotated[Template, "sql"] = t"SELECT * FROM {table}"
This approach seems promising - I’ve created a prototype LSP to test it (GitHub - koxudaxi/t-linter). However, I’m not sure this is the best path, so I’d like feedback from the community.
The advantage of using Annotated is that type checkers could potentially leverage this information as well - for instance, applying SQL-specific validation rules only to SQL templates. Additionally, it maintains backward compatibility since tools that don’t recognize the annotation can simply ignore it.
That said, there might be better approaches:
- Subclassing:
class SQLTemplate(Template): ...
- Hints package: Pre-defined types like
from template_hints import SQLTemplate
- No coordination: Let each tool implement its own detection (though this might lead to fragmentation)
I’d appreciate your thoughts on whether we should coordinate this effort as a community, or if it would be better to let different tools develop their own solutions independently.
I’m also interested in your opinions on the format for language identifiers - should we use simple names like “sql” or MIME-style types (e.g., “text/x-sql”, “text/html”)?
I look forward to hearing your perspectives, especially from those working on type checkers or IDEs.
Depending on the discussion, we might consider creating a shared package with type aliases or documenting best practices - but let’s first see what approach makes the most sense for our community.
Thank you!