dbrattli / OSlash

Functors, Applicatives, And Monads in Python
MIT License
708 stars 50 forks source link

Fix str() bug for tuple values #33

Open cfs-pure opened 8 months ago

cfs-pure commented 8 months ago

Replaced the use of old-style formatting strings in str methods.

At first, that seems like a dated but harmless practice, but unfortunately

While dated and seemingly a harmless practice, OSlash actually uses it in an incorrect way.

If a program using OSlash deals with types other than strings, then the str methods for classes like Left, Right, and Either, OSlash directly writes:

return '%s' % value

where value is an arbitrary type.

Unfortunately, '%s' % value is only guaranteed to work if the value is a string, since Python will not call str() on it.

(Well, more precisely, '%s' % value is guaranteed to fail if the value happens to be a tuple of a certain kind, since Python will try to unpack the tuple into the string formatting operation)

The upshot is that such programs will get TypeErrors. Instead, use Python 3.8+ f-strings to guarantee that the value is converted to a string.