summaryrefslogtreecommitdiffstats
path: root/Lib/typing.py
diff options
context:
space:
mode:
authorJelle Zijlstra <jelle.zijlstra@gmail.com>2022-04-05 14:21:03 (GMT)
committerGitHub <noreply@github.com>2022-04-05 14:21:03 (GMT)
commitcfb849a326e52a4edc577112ebf60e1d9d0d7fdb (patch)
tree275214ff4cbeb981b7f579f3c9f953e260ac11a7 /Lib/typing.py
parenta7551247e7cb7010fb4735281f1afa4abeb8a9cc (diff)
downloadcpython-cfb849a326e52a4edc577112ebf60e1d9d0d7fdb.zip
cpython-cfb849a326e52a4edc577112ebf60e1d9d0d7fdb.tar.gz
cpython-cfb849a326e52a4edc577112ebf60e1d9d0d7fdb.tar.bz2
bpo-47088: Add typing.LiteralString (PEP 675) (GH-32064)
Co-authored-by: Nick Pope <nick@nickpope.me.uk>
Diffstat (limited to 'Lib/typing.py')
-rw-r--r--Lib/typing.py31
1 files changed, 30 insertions, 1 deletions
diff --git a/Lib/typing.py b/Lib/typing.py
index 4636798..26c6b8c 100644
--- a/Lib/typing.py
+++ b/Lib/typing.py
@@ -126,6 +126,7 @@ __all__ = [
'get_origin',
'get_type_hints',
'is_typeddict',
+ 'LiteralString',
'Never',
'NewType',
'no_type_check',
@@ -180,7 +181,7 @@ def _type_check(arg, msg, is_argument=True, module=None, *, allow_special_forms=
if (isinstance(arg, _GenericAlias) and
arg.__origin__ in invalid_generic_forms):
raise TypeError(f"{arg} is not valid as type argument")
- if arg in (Any, NoReturn, Never, Self, TypeAlias):
+ if arg in (Any, LiteralString, NoReturn, Never, Self, TypeAlias):
return arg
if allow_special_forms and arg in (ClassVar, Final):
return arg
@@ -524,6 +525,34 @@ def Self(self, parameters):
@_SpecialForm
+def LiteralString(self, parameters):
+ """Represents an arbitrary literal string.
+
+ Example::
+
+ from typing import LiteralString
+
+ def run_query(sql: LiteralString) -> ...
+ ...
+
+ def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
+ run_query("SELECT * FROM students") # ok
+ run_query(literal_string) # ok
+ run_query("SELECT * FROM " + literal_string) # ok
+ run_query(arbitrary_string) # type checker error
+ run_query( # type checker error
+ f"SELECT * FROM students WHERE name = {arbitrary_string}"
+ )
+
+ Only string literals and other LiteralStrings are compatible
+ with LiteralString. This provides a tool to help prevent
+ security issues such as SQL injection.
+
+ """
+ raise TypeError(f"{self} is not subscriptable")
+
+
+@_SpecialForm
def ClassVar(self, parameters):
"""Special type construct to mark class variables.