Python 3.x multi line comment throws syntax error - python

I'm working on a Python project and as of now, my code has over 400+ lines. At one point, I had to write a multi-line comment about a small bug which needs a work around, and the interpreter decided to throw a syntax error.
According to the interpreter, the syntax error is occuring at elif.
I re-checked my indentation, converted tabs to spaces etc. Nothing seems to work.
if some_condition_1 == True:
do_something()
"""
Sub stage (b):
Refer documentation [1.7A] for ...
....
....
....
"""
elif condition_1 == True:
if condition_2 == False:
list.append(item)
However, if I remove the multi-line comment, the code executes fine.
Any idea what's going wrong? Please note that the code sample I've show above, is at very top of the file, and there's no chance for anything to go wrong elsewhere.

This is an indentation error. Your "multi-line comment" (really multi-line string) must be indented under the if block just like anything else.
""" These kinds of things """ are not really comments in Python. You're just creating a string and then throwing the value away (not storing it anywhere). Since Python doesn't have true multi-line comments, many people use them this way. However, since they are not true comments (they aren't ignored by the interpreter), they must obey all normal syntax rules, including indentation rules.
(Do note that when I say "creating a string" I'm speaking loosely. CPython, at least, has an optimization not to create an object here.)

Related

How to tackle SyntaxError in Python

Since there are a bunch of questions here on Stack Overflow that deal with SyntaxError in Python, we might want to know:
How do we tackle a SyntaxError? Are there strategies that can generally be applied?
0. Before the Error appears: Syntax Highlighting and Code Formatting
Even before running into a SyntaxError, there are important measurements to deal with SyntaxErrors, because the best way to deal with SyntaxErrors is to avoid them in the first place. This can be done first and foremost by using an editor or an Integrated Development Environment (IDE) which has syntax highlighting for Python.
Besides that, we can decrease the risk of running into a SyntaxError by good code and formatting style. There is a formal definition of the term "good formatting style", PEP 8 -- Style Guide for Python Code. Proper formatting makes our code much more readable which decreases the risk writing code that leads to a SyntaxError.
A very good way to apply good formatting to our code is to use an automatic code formatting tool. A code formatter has multiple advantages, amongst which are the following: Its code formatting is consistent. It applies best practices you might not even have thought of yet. It is very convenient.
For Python, black is a great code formatting tool.
1. Understand the Error Message
The Syntax Error indicates in which file and in which line the interpreter came across a problem in our code. We should use this information to find the bug.
We should be aware that the Python interpreter sometimes indicates a SyntaxError in the line after the actual problem. This is because the parser expects something in the erroneous line and can recognise that this is missing only when the whole line has been parsed. The prototypic example for that kind of SyntaxError is a missing parenthesis. So for instance, the following code raises a SyntaxError in line 2, even though the bug is in line 1:
bar = foo(
baz()
EOL stands for "End Of Line". This helps understanding the very common SyntaxError: EOL while scanning string literal. This is usually raised when you did not properly close a string definition with closing quotation marks, such as in the following example:
foo = "bar
2. Simplify the Code
Generally, a good strategy of bug fixing is to reduce any code that throws an Error or an Exception (or that does not return the expected output) to a minimal example. (This is a requirement for questions here on Stack Overflow, but much more than this, it is a good technique for pinning down a bug.)
In case of a SyntaxError, producing a minimal example is usually very easy, because a SyntaxError does not depend on any values of a variable, or any state of an object or any other semantics of your code. That's why the source of a SyntaxError is usually one line of code.
So, to identify the bug, we remove all the code besides the line that we think is the source of the Error. If the Error vanishes, it has been in a different line. If the Error persists, we try to simplify this line. For instance, we replace nested parentheses, by defining intermediate variables that hold the values:
Instead of
bar = foo(foo(baz(foo()))
the following (logically equivalent) code:
first = foo()
second = baz(first)
third = foo(second)
bar = foo(third
makes it much easier for us to identify the missing closing parenthesis.
Refer to documentation. Syntax Errors unfortunately cannot be captured in a Try: Except: block, so the only way to deal with them is to read the message returned, and if that doesn't help, following up with the python documentation:
https://docs.python.org/3/

Does python have an EXIT_SUCCESS constant?

I'm returning 0 all over the place in a python script but would prefer something more semantic, something more readable. I don't like that magic number. Is there an idea in python similar to how in C you can return EXIT_SUCCESS instead of just 0?
I was unable to find it here:
https://docs.python.org/3.5/library/errno.html
I'm returning 0
return is not how you set your script's exit code in Python. If you want to exit with an exit code of 0, just let your script complete normally. The exit code will automatically be set to 0. If you want to exit with a different exit code, sys.exit is the tool to use.
If you're using return values of 0 or 1 within your code to indicate whether functions succeeded or failed, this is a bad idea. You should raise an appropriate exception if something goes wrong.
Since you discuss return here, it seems like you may be programming Python like C. Most Python functions should ideally be written to raise an exception if they fail, and the calling code can determine how to handle the exceptional conditions. For validation functions it's probably best to return True or False - not as literals, usually, but as the result of some expression like s.isdigit().
When talking about the return value of a process into its environment you caonnt use return because a module isn't a function, so a return statement at top level would be flagged as a syntax error. Instead you should use sys.exit.
Python might seem a little minimalist in this respect, but a call to sys.exit with no arguments defaults to success (i.e. return code zero). So the easiest way to simplify your program might be to stop coding it with an argument where you don't want to indicate failure!
As the documentation reminds us, integer arguments are passed back, and string arguments result in a return code of 1 and the string is printed to stderr.
The language doesn't, as far as I am aware, contain any constants (while it does have features specific to some environments, if it provided exit codes their values might need to be implementation- or platform-specific and the language developers prefer to avoid this where possible.

Python:- what is meaning of "if(true)"

I am trying to debug current code and I am new in python,
Need to understand below code
Why they use this code and Whats use of this code in python
def _init_():
if(true):
Before figuring out what if(True) does, think of if(False) first. if(False) is actually a commonly used idiom which has the same effect as commenting out multiple lines - all the code that's in its indentation block will not be executed since the condition is always evaluated as false. Later, if you want those lines of code below if(False) to be executed again, you can simply change False to True - that's how if(True) comes in. Itself doesn't do anything, it is its opposite if(False) that is useful.

Python REPL: issuing commands in advance to execute after block

This is a bit of an odd question; it came up in the context of a tool that exposes a Python API, which we spend a lot of time querying interactively from the REPL. The particular idiom causing issues is something like this:
for var in slow_generator_of_giant_list():
stats = update(stats, var)
print stats
To enter this at the REPL, I can type this:
>>> for var in slow_generator_of_giant_list():
... stats = update(stats, var)
...
If I now attempt to type the print, I get a syntax error due to improper indentation. (Or else I put the print inside the loop and do it on every iteration.)
But if I hit enter to go to the next line, the loop runs immediately, and I have to wait for it to finish, or type the print command in the face of possible output coming at me, etc.
Obviously I can define a function containing the above, and it might be worth saving into a file anyway, but in the general case we're constructing these on the fly, and it would be nice to have a way to "schedule" a command to run after the end of a loop from the REPL. In a language with block delimiters, I could of course put it after the ending delimiter (and any necessary statement separator). But my coworkers and I were stumped trying to do something similar here.
Is there perhaps an ugly abuse of Pythonic syntax that will do the trick that my coworkers and I couldn't think of? Or a recommended way to avoid the problem while still making it easy to throw together ad hoc interactive queries?
Thanks for any pointers.
Not beautiful, but this should work:
>>> mygen = slow_generator_of_giant_list()
>>> try:
... while True: stats = update(stats, mygen.next())
... except StopIteration:
... print stats
...
I would just say that you would find it easier just to not use the interactive shell for this.
It's not much effort to save a file and run it. You only have to keep it around for as long as you use it.
I actually have found this answering on SO. I keep a file open in my text editor with a terminal in the right directory, and just use it as a scratchpad for mocking up answers in.

When would `if False` execute in Python?

While browsing some code, I came across this line:
if False: #shedskin
I understand that Shedskin is a kind of Python -> C++ compiler, but I can't understand that line.
Shouldn't if False: never execute? What's going on here?
For context:
This is the whole block:
if False: # shedskin
AStar(SQ_MapHandler([1], 1, 1)).findPath(SQ_Location(1,1), SQ_Location(1,1))
More context is on Google Code (scroll down all the way).
It won't execute, because it isn't supposed to. The if False: is there to intentionally prevent the next line from executing, because that code's only purpose is seemingly to help Shed Skin infer type information about the argument to the AStar() function.
You can see another example of this in httplib:
# Useless stuff to help type info
if False :
conn._set_tunnel("example.com")
It will never get executed. It's one way to temporarily disable part of the code.
Theoretically, it could get executed:
True, False = False, True
if False: print 'foo'
But typically this will be used to temporarily disable a code path.
You are correct in assuming that this will never evaluate to true. This is sometimes done when the programmer has a lot of debugging code but does not want to remove the debugging code in a release, so they just put if False: above it all.
not enough reputation to comment yet apparently, but tim stone's answer is correct. suppose we have a function like this:
def blah(a,b):
return a+b
now in order to perform type inference, there has to be at least one call to blah, or it becomes impossible to know the types of the arguments at compile-time.
for a stand-alone program, this not a problem, since everything that has to be compiled for it to run is called indirectly from somewhere..
for an extension module, calls can come from the 'outside', so sometimes we have to add a 'fake' call to a function for type inference to become possible.. hence the 'if False'.
in the shedskin example set there are a few programs that are compiled as extension modules, in order to be combined with for example pygame or multiprocessing.

Categories

Resources