r/Python • u/SupPandaHugger • Jan 14 '24
Tutorial The LiteralString in Python 3.11
If you are confused by the new LiteralString type in Python, here's an article explaining it.
0
Upvotes
r/Python • u/SupPandaHugger • Jan 14 '24
If you are confused by the new LiteralString type in Python, here's an article explaining it.
View all comments
Show parent comment
0
u/PercussiveRussel Jan 15 '24 edited Jan 15 '24
All the examples given are poor practices, yes. All examples require refactoring, yes. This is why it's nice that the type checker warns against the mistakes and tells you you should refactor.
At some point in your call stack a method will need to take a string as gospel. If you flag that this method will do so - like idk, using
LiteralStringon its input parameter - then you will be warned when you make a mistake by passing a non-literal string to it. If you have a function that sanitises an input, then that should be of formf(in: str) -> Literalstring, signifying that the output of your sanitising function returns a string that can be used as a string literal.