docopt icon indicating copy to clipboard operation
docopt copied to clipboard

[FIX] "TypeError: unsupported operand type(s) for +" when something is not str

Open alanjds opened this issue 12 years ago • 4 comments

Got an issue on https://github.com/opdemand/deis CLI, but seems to be related to naive concatenation of parameters of DocoptExit.__init__()

This should fix the issue.

alanjds avatar Dec 18 '13 20:12 alanjds

I think unicode() is Python 2 only. Would str() be okay?

cjwelborn avatar Jul 05 '16 03:07 cjwelborn

Hum... you are right. But what if it contains accents and is Python 2 ?

alanjds avatar Jul 05 '16 22:07 alanjds

After thinking about this for a second, DocoptExit is just a wrapper around SystemExit that expects a string (message) to print to the console. SystemExit accepts an int (exit code), or some other value that will be stringified and printed (str(val)) with the exit code set to 1 by default.

I don't think DocoptExit necessarily needs to accept the int, because it's just not used like that. Can I ask you what was being passed to it for your original error?

This would not cause that TypeError for + (whether it's str or bytes, + should work):

raise DocoptExit(unicode('àâæçéêèëùûüÿ€ôîïœ') + unicode('𝖕𝖞𝖙𝖍𝖔𝖓³'))
# Or even:
raise DocoptExit('àâæçéêèëùûüÿ€ôîïœ' + '𝖕𝖞𝖙𝖍𝖔𝖓³')

However, this would:

raise DocoptExit(1)

I really think this is a misuse of the DocoptExit, and could be circumvented with a subclass:

class MyDocoptExit(DocoptExit):
    def __init__(self, message=''):
        if isinstance(message, int):
           # Let SystemExit handle the int exit code.
            SystemExit.__init__(self, message)
        else:
           # Let DocoptExit handle the message, with an exit code of 1.
            super(DocoptExit, self).__init__(message)

I just hadn't thought much about it until now. Can you point me to the original error so I can investigate a little more?

cjwelborn avatar Jul 05 '16 23:07 cjwelborn

Unfortunately, no. I did not even remember what project I was working on when I hit this.

alanjds avatar Jul 06 '16 14:07 alanjds