DrBwts
DrBwts

Reputation: 3657

Confusing indentation issue

I'm using an API from this GIT repository to control a JDS6600 signal generator.

Now some of the commands work & some dont due I think to the unit I'm using being slightly different to the one used by the author of the API.

So to fix this I tried to see what data the device was sending back before an error is raised. I thought a simple print(data) would do it but I keep getting an indentation error, sorry screen shots but I think you get a better idea from a picture in this case.

First with the newly added print(data), note little red cross on the left

enter image description here

Second without,

enter image description here

So how come I'm getting this error? No matter where I place that print(data) within the method I get an indentation error & the code falls over.

EDIT: The problem was fixed running reindent on the offending file, which converts all the tabs to spaces. As pointed out by Tyberius in a comment below the file was a mix of tabs & spaces. It seems Spyder has a unique attitude to such cases.

Upvotes: 0

Views: 140

Answers (2)

shyamcody
shyamcody

Reputation: 46

The line will actually fail. For example, look below:

   if a in [0.5,0.4]:
       raise TypeError(a)
   print("what")
   File "<stdin>", line 3
   print("what")
       ^
   SyntaxError: invalid syntax

Now, why does this happen? answer is mentioned here. Basically, as you define the error in the previous line, the error gets caught in the print. For example, it is technically similar to the following:

>>> while True print('Hello world')
File "<stdin>", line 1
while True print('Hello world')
               ^
SyntaxError: invalid syntax

So that is why, your print is raising the error instead of the previous line. Also, there is no meaning of printing after you raise the error, as it will never get executed as the error will halt the execution. So the solution will be to put the print statement before the raise.

Upvotes: 0

JackLeo
JackLeo

Reputation: 4740

You're seeing an error highlighted by the IDE (lint error), not an actual python error (you would get it after running and seeing a traceback). In general anything after : is expected to be in the next line and IDE is probably making that assumption.

The general style guide is defined by PEP-8 and it covers compound statements. The way you're trying to use is generally considered within the "rather not" section.

So really it should be

if a not in (0, 1):
    raise RuntimeError(a)
print(data)

If you would use something like black autoformatter it would sort it out for you.

Upvotes: 1

Related Questions