2

I am new to python. I found my python code return unreasonably return tab error:

msgs['to'] = "xxx@gmail.com"
^ TabError: inconsistent use of tabs and spaces in indentation

Here is part of my code:

def send_email(self):
    try:
        msgs = MIMEMultipart()
        msgs['to'] = "xxx"
        msgs['from'] = "xxx"
        msgs['subject'] = "abc"
        msgs.attach(MIMEText(file("~/att1.py").read())
        msgs.attach(MIMEText(file("~/att2.docx").read())

        server = smtplib.SMTP()
        server.connect('smtp.gmail.com:587')
        server.login('xxx','xxx')
        server.sendmail(msgs['from'], msgs['to'],msgs.as_string())
        server.quit()
        print "Successfully sent email"
        return True
    except SMTPException:
        print "Error: unable to send email"
        print str(SMTPException)
        return False
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Evan Lee
  • 41
  • 1
  • 1
  • 2
  • 3
    Why is it unreasonable? Python's parser is a machine, it knows no reason. It found a line that uses tabs to indent while other lines use spaces. Remove the tabs, I'd say. – Martijn Pieters Feb 12 '16 at 15:42
  • I resolved this issue by opening python file in default editor and then selecting all content using edit -> Select all, after that format -> untabify region (with 8 spaces as tabs). this has fixed the issue. – user1710989 Feb 03 '21 at 08:07

1 Answers1

13

Your code is indeed using tabs spaces inconsistently. When copying your original post to Sublime Text 3, then selecting all the lines, I can see both tabs (lines) and spaces (dots):

enter image description here

Note that I set tabs to expand to 8 spaces, which is what Python does too. Note how the msgs[..] lines are not even lining up anymore now. It is also a syntax error in Python 3 to mix tabs and spaces for indentation.

Configure your text editor to insert spaces when you use the TAB key instead. This is the recommended configuration for Python code, because tab widths are editor configuration dependent, while a space is always the same width. This is what the Python styleguide (PEP 8) recommends:

Tabs or Spaces?

Never mix tabs and spaces.

The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs only. Code indented with a mixture of tabs and spaces should be converted to using spaces exclusively. When invoking the Python command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended!

For new projects, spaces-only are strongly recommended over tabs. Most editors have features that make this easy to do.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343