TypeError: unsupported operand types for +: 'NoneType' and 'str'

Dave Angel davea at ieee.org
Wed Nov 18 00:02:01 EST 2009


aurfalien at gmail.com wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">Hi all,
>
> I tried to make the subject as specific as possible rather then just 
> "help me" or "its broke" or "my server is down", etc...
>
> So please excuse me if its too specific as I wasn't trying to be 
> ridiculous.
>
> So I've been handed some one else's work to fix.
>
> While its fun and all, I haven't had much luck in debugging this 
> particular issue.
>
> The error I get;
>
> File "myscript.py", Line 18, in ?
> projectpath = ourHome+"/etc/TEMPLATE"
> TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
>
> Python 2.4.3
>
> I've read were when passing a string to exec may need to end with a '\n'
>
> I've tried a few diff variations on the below line 18 w/o luck.  Any 
> one mind helping out a bratha from anatha ... planet that is?
>
> line 18;
>
> projectpath = ourHome+"/etc/TEMPLATE"
>
> line 17;
> ourHome = os.environ.get('some_env')
>
>
> Thanks in advance,
> - aurf
>
>
Short answer:   you (the program) don't have any such environment 
variable, and forgot to check for it, just implicitly assuming that 
it'll be present.  When it isn't, the + doesn't make any sense.

Longer answer:  When you get an error on a line, try to figure out which 
of the variables on the line might be in doubt, and look at them in your 
debugger.  Since the error is complaining about operands to + you'd look 
at both the ourHome variable and the literal.  And then you'd look, and 
see that ourHome is equal to None.  Which is what the error said.  Now 
you look at the last place which bound that variable and it's 
os.environ.get().  How can get() return a None?  Answer:  when there's 
no such variable.

As to how to fix it, you have to decide what behavior you want when the 
user doesn't have such a variable.   Read the manual you wrote for the 
user, telling him to define it.  If no such paragraph exists, then 
perhaps you intended a default value to be used, such as   
"/default/special"   Add a paragraph to the manual, and a corresponding 
field to the get().

    ourHome = os.environ.get("some_env", "/default/special")

Now it'll always have a text value, either specified by the environment 
var, or /default/special.

Alternatively, you could catch the exception, print an error to the 
user, telling him exactly how to fix his environment, and exit.  Of 
course, this assumes you do the check pretty early in the program's run.

DaveA




More information about the Python-list mailing list