3 ms·
it's difficult to say that .format and %s are both strictly worse (I think "{}.format()" is strictly better than %s, but both are a bit orthogonal to f-strings
by joshuamorton 4y ago
it's difficult to say that .format and %s are both strictly worse (I think "{}.format()" is strictly better than %s, but both are a bit orthogonal to f-strings because both are lazily applied. F-strings evaluate locals immediately, but .format can be called later. That is, concretely, f-strings are almost equivalent to `"".format(*locals())`, but f-strings fail for cases where, for example, the string to be formatted itself is not available at "compile" time.
- pmontra 4y agoYou can use eval to trasform a string to f string and evaluate it. Of course format is better in that case. https://stackoverflow.com/questions/44757222/transform-string-to-f-string https://stackoverflow.com/questions/44757222/transform-strin...
- masklinn 4y ago> I think "{}.format()" is strictly better than %s It’s not, because it’s way too powerful. A user-provided printf string is not much of an issue, a user-provided str.format one very much is, as provides significant traversal capabilities.
- joshuamorton 4y agoIs the .format sublanguage notably stronger than the %-one? I know in c, for example, the printf sublanguage can be used to do turing-complete things, but I didn't think that was possible in either in python.
- masklinn 4y ago> Is the .format sublanguage notably stronger than the %-one? Yes, it allows arbitrary attribute traversal as well as broad indexing. The % sublangage is a lot more restrictive and doesn’t suffer from the arbitrary reading of the C version (if you format an object that wasn’t passed in you get an error not a read off of the stack or a register). I don’t think format is anywhere near turing complete, but it allows significant information querying and retrieval (https://lucumr.pocoo.org/2016/12/29/careful-with-str-format/ https://lucumr.pocoo.org/2016/12/29/careful-with-str-format/). Both still allow for resource exhaustion but that’s what it is.