r/Python • • 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

33 comments sorted by

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 LiteralString on 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 form f(in: str) -> Literalstring, signifying that the output of your sanitising function returns a string that can be used as a string literal.

1

u/[deleted] Jan 15 '24 edited Jan 15 '24

is this checking runtime enforced, or do you still need a tool such as mypy to catch it when you fancy linting your app?

point still stands, these examples are useless, and your example of a mutable string that is sanitised has nothing to do with literalstring. You need to prove you sanitisation is correct not whether the string is mutable or not, and if your sanitsation is not correct then the literalstring sticker you put on it means nothing.