Search code examples
python-3.xattributeerrornonetypeisalpha

Python : NoneType error in isalpha() function


I am currently stuck at problem with NoneType and using function isalpha() in Python. What I want to do is lexical analysis and I want to devide the whole code into four categories. Here is my code

import sys
import keyword  #keyword.iskeyword()

**strong text**def check_chars(tmp,x):
if (tmp == "" or tmp.isalpha()) and (x =="" or x.isalpha()):
    if keyword.iskeyword(tmp):
        print("Key: "+ tmp)
        return ""
    return tmp+x    
if tmp.isalpha() and not x.isalpha():
    print("Var: "+tmp)
    return x        


separators = ['(',')','[',']','{','}',',',':','.',';','@','=','->','+=','-=','*=','/=','//=','%=','@=','&=','|=','^=','>>=','<<=','**=']
operators = ['+','-','*','**','/','//','%','<<','>>','&','|','^','~','<','>','<=','>=','==','!=']

f = open(sys.argv[1],'r')
program = f.read()

tmp = ""
for x in program:

tmp = check_chars(tmp,x)
if tmp in separators:
    print("Sep: "+ tmp)
    tmp = ""
if tmp in operators:    
    print("Ope: "+ tmp)
    tmp = ""
if x is " ":
    tmp = ""

When I reach end of a first line in a sample program which is this:

def funkce(a,b):
c=''
a**=b
if a<b:
    print('ahoj\'ky',a)
else:
    print(0xff,0b11101,0o777,.90e-10,123E+5,c)
    print('''To je dlouhy
    retezec pres mnoho
    radku''')
funkce(-256+356,.85**.33)

An error occurs:

Traceback (most recent call last):
File "HW09.py", line 24, in <module>
tmp = check_chars(tmp,x)
File "HW09.py", line 5, in check_chars
if (tmp == "" or tmp.isalpha()) and (x =="" or x.isalpha()):
AttributeError: 'NoneType' object has no attribute 'isalpha'

I wouldn't be surprised if the error rises at the beggining of the program. But how is possible that it rises at the end of line? Is it possible that the error is somehow connected with end of line character "\n". Thank you for suggestions :)


Solution

  • Your problem is that not all of the paths through your check_chars() function return a value. Therefore, sometimes (specifically, in your case, when tmp contains '\n') this:

    tmp = check_chars(tmp,x)
    

    assigns None to tmp, and then the next time you call check_chars(), this:

    tmp.isalpha()
    

    attempts to call isalpha() on None, and causes your problem.

    The solution is to make sure all paths through check_chars() return a value.