Text of peps.python.org › pep-0675 as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

PEP 675 – Arbitrary Literal String Type | peps.python.org

PEP 675 – Arbitrary Literal String Type PEP 675 – Arbitrary Literal String Type Author : Pradeep Kumar Srinivasan <gohanpra at gmail.com>, Graham Bleaney <gbleaney at gmail.com> Sponsor : Jelle Zijlstra <jelle.zijlstra at gmail.com> Discussions-To : Typing-SIG thread Status : Final Type : Standards Track Topic : Typing Created : 30-Nov-2021 Python-Version : 3.11 Post-History : 07-Feb-2022 Resolution : Python-Dev message Table of Contents Abstract Motivation Usage statistics Rationale Specification Runtime Behavior Valid Locations for LiteralString Type Inference Inferring LiteralString Examples Interaction with TypeVars and Generics Interactions with Overloads Backwards Compatibility Rejected Alternatives Why not use tool X?

Why not use a NewType for str ? Why not try to emulate Trusted Types? Runtime Checkable LiteralString Rejected Names LiteralBytes Reference Implementation Appendix A: Other Uses Command Injection Cross Site Scripting (XSS) Server Side Template Injection (SSTI) Logging Format String Injection Appendix B: Limitations Appendix C: str methods that preserve LiteralString Appendix D: Guidelines for using LiteralString in Stubs Resources Literal String Types in Scala Thanks Copyright Important This PEP is a historical document: see LiteralString and typing.LiteralString for up-to-date specs and documentation.

Canonical typing specs are maintained at the typing specs site ; runtime typing behaviour is described in the CPython documentation. × See the typing specification update process for how to propose changes to the typing spec. Abstract There is currently no way to specify, using type annotations, that a function parameter can be of any literal string type. We have to specify a precise literal string type, such as Literal["foo"] .

This PEP introduces a supertype of literal string types: LiteralString . This allows a function to accept arbitrary literal string types, such as Literal["foo"] or Literal["bar"] . Motivation Powerful APIs that execute SQL or shell commands often recommend that they be invoked with literal strings, rather than arbitrary user controlled strings. There is no way to express this recommendation in the type system, however, meaning security vulnerabilities sometimes occur when developers fail to follow it.

For example, a naive way to look up a user record from a database is to accept a user id and insert it into a predefined SQL query: def query_user ( conn : Connection , user_id : str ) -> User : query = f "SELECT * FROM data WHERE user_id = { user_id } " conn . execute ( query ) ... # Transform data to a User object and return it query_user ( conn , "user123" ) # OK. However, the user-controlled data user_id is being mixed with the SQL command string, which means a malicious user could run arbitrary SQL commands: # Delete the table. query_user ( conn , "user123; DROP TABLE data;" ) # Fetch all users (since 1 = 1 is always true). query_user ( conn , "user123 OR 1 = 1" ) To prevent such SQL injection attacks, SQL APIs offer parameterized queries, which separate the executed query from user-controlled data and make it impossible to run arbitrary queries.

For example, with sqlite3 , our original function would be written safely as a query with parameters: def query_user ( conn : Connection , user_id : str ) -> User : query = "SELECT * FROM data WHERE user_id = ?" conn . execute ( query , ( user_id ,)) ... The problem is that there is no way to enforce this discipline. sqlite3’s own documentation can only admonish the reader to not dynamically build the sql argument from external input; the API’s authors cannot express that through the type system.

Users can (and often do) still use a convenient f-string as before and leave their code vulnerable to SQL injection. Existing tools, such as the popular security linter Bandit , attempt to detect unsafe external data used in SQL APIs, by inspecting the AST or by other semantic pattern-matching. These tools, however, preclude common idioms like storing a large multi-line query in a variable before executing it, adding literal string modifiers to the query based on some conditions, or transforming the query string using a function. (We survey existing tools in the Rejected Alternatives section.) For example, many tools will detect a false positive issue in this benign snippet: def query_data ( conn : Connection , user_id : str , limit : bool ) -> None : query = """ SELECT user.name, user.age FROM data WHERE user_id = ?

""" if limit : query += " LIMIT 1" conn . execute ( query , ( user_id ,)) We want to forbid harmful execution of user-controlled data while still allowing benign idioms like the above and not requiring extra user work. To meet this goal, we introduce the LiteralString type, which only accepts string values that are known to be made of literals. This is a generalization of the Literal["foo"] type from PEP 586 . A string of type LiteralString cannot contain user-controlled data.

Thus, any API that only accepts LiteralString will be immune to injection vulnerabilities (with pragmatic limitations ). Since we want the sqlite3 execute method to disallow strings built with user input, we would make its typeshed stub accept a sql query that is of type LiteralString : from typing import LiteralString def execute ( self , sql : LiteralString , parameters : Iterable [ str ] = ... ) -> Cursor : ... This successfully forbids our unsafe SQL example.

The variable query below is inferred to have type str , since it is created from a format string using user_id , and cannot be passed to execute : def query_user ( conn : Connection , user_id : str ) -> User : query = f "SELECT * FROM data WHERE user_id = { user_id } " conn . execute ( query ) # Error: Expected LiteralString, got str. ... The method remains flexible enough to allow our more complicated example: def query_data ( conn : Connection , user_id : str , limit : bool ) -> None : # This is a literal string. query = """ SELECT user.name, user.age FROM data WHERE user_id = ?

""" if limit : # Still has type LiteralString because we added a literal string. query += " LIMIT 1" conn . execute ( query , ( user_id ,)) # OK Notice that the user did not have to change their SQL code at all. The type checker was able to infer the literal string type and complain only in case of violations. LiteralString is also useful in other cases where we want strict command-data separation, such as when building shell commands or when rendering a string into an HTML response without escaping (see Appendix A: Other Uses ).

Overall, this combination of strictness and flexibility makes it easy to enforce safer API usage in sensitive code without burdening users. Usage statistics In a sample of open-source projects using sqlite3 , we found that conn.execute was called ~67% of the time with a safe string literal and ~33% of the time with a potentially unsafe, local string variable. Using this PEP’s literal string type along with a type checker would prevent the unsafe portion of that 33% of cases (ie. the ones where user controlled data is incorporated into the query), while seamlessly allowing the safe ones to remain.

Rationale Firstly, why use types to prevent security vulnerabilities? Warning users in documentation is insufficient - most users either never see these warnings or ignore them. Using an existing dynamic or static analysis approach is too restrictive - these prevent natural idioms, as we saw in the Motivation section (and will discuss more extensively in the Rejected Alternatives section). The typing-based approach in this PEP strikes a user-friendly balance between strictness and flexibility.

Runtime approaches do not work because, at runtime, the query string is a plain str . While we could prevent some exploits using heuristics, such as regex-filtering for obviously malicious payloads, there will always be a way to work around them (perfectly distinguishing good and bad queries reduces to the halting problem). Static

The rest of this page is on the live site.