Python 3.11: A Guided Tour Through Code Transcripts
Chapter: Type Updates for 3.11
Lecture: Pythons LiteralString Type

Login or purchase this course to watch this video and the rest of the course contents.
0:00 In the type system in Python 3.11 we now have an explicit type for a literal string.
0:08 This is not a new class or new thing that you create instead of a string with quotes in python it's
0:15 just the type system. So here's an example. We have this function that's gonna execute sql commands.
0:22 You know what we don't want to do take arbitrary strings combined from user input and run them against our database
0:27 New, that's a bad idea. So what we can do now is we can say from typing import literal string and then the sql query itself is the literal string.
0:40 Here's a literal string, select star from users where name is like some percent thing and then we can say
0:47 for u in users execute this where the name is like Sarah and notice we're using the question mark.
0:54 That means Sarah is being passed as a database parameter to the query where the query syntax itself is fixed.
1:01 The database knows where that question mark is. That's where we put the value of Sarah and that can't be
1:07 combined a short circuit. Some kind of sql statement or inject new ones. So this one is totally safe. This comes to us of course from Pep 675.
1:20 On the other hand, if we tried our trick before select star from data where these ideas this we
1:28 tried to execute it not at runtime but at mypy checking time we would get something like error. We expected a literal string but we got str again.
1:40 Both of these are really classes instances of the string class.
1:45 it's just a matter of were they created with input from parsing some kind of F string or string dot format
1:53 or the actual literal strings? One final comment on this as well. This one's valid literal string here sql select star from users.
2:03 We can combine it with addition, like plus or other types of things with other literal strings.
2:10 So we could have an if statement that says if you want to sort sql plus equals order by name or
2:19 order by date registered or something like that. That would still be a literal string because both the original and
2:26 the thing being combined with it or literal. So you can do interesting things with these literal strings.
2:31 They don't have to be purely static in this sense.
2:34 They just can't be taken from variables and then have not formatted to generate the string where who knows what got
2:41 into the string. Alright, that's the arbitrary literal string type and pep 675. Pretty cool. Hopefully that leads to just a couple of less.
2:52 XKCD jokes about sql injection, at least for us, python folks.


Talk Python's Mastodon Michael Kennedy's Mastodon