Syntaxerror Inconsistency in Python

SyntaxError inconsistency in Python?

In the first case, the exception is raised by the compiler, which is running before the try/except structure even exists (since it's the compiler itself that will set it up right after parsing). In the second case, the compiler is running twice -- and the exception is getting raised when the compiler runs as part of eval, after the first run of the compiler has already set up the try/except.

So, to intercept syntax errors, one way or another, you have to arrange for the compiler to run twice -- eval is one way, explicit compile built-in function calls another, import is quite handy (after writing the code to another file), exec and execfile other possibilities yet. But however you do it, syntax errors can be caught only after the compiler has run one first time to set up the try/except blocks you need!

Why isn't Python excepting error in list comprehension

Syntax Error Inconsistency

As @BrianMcCutchon mentions, if you are checking the syntax error inconsistency, please use eval for the same-

try:
eval("[2 * x for x in [1,2,3] if x > 1 else 0]") #<----
except SyntaxError:
print("Why isn't this printed?")
Why isn't this printed?

Syntax error in list comprehension

The error gets fixed if you fix the else in your list comprehension.

try:
[2 * x if x > 1 else 0 for x in [1,2,3]] #<----
except SyntaxError:
print("Why isn't this printed?")

As @Ch3steR mentions in their comment as well, please refer to this post for more details.

#Returning element based on condition
[i for i in l if condition=True]

#Adding if else in list comprehension
[i if condition=True else j for i in l]

Why can't SyntaxError be caught by user code?

SyntaxError is thrown before the code is actually run. In particular your error handlers haven't been created executed yet.

(You will notice that if you have anything that generate output in your code, such as print statements, the output will not be generated when there's a problem with the syntax, no matter where they are in the code).

However in the use case you described, I don't really see why you would need to catch SyntaxError. It seems to me that you would want to catch errors that depend on the program's state. SyntaxError don't pop up unexpected. If you were able to run your programs once, you will not a SyntaxError in later invocations (unless, of course, you change the code).

Inconsistent comprehension syntax?

You are mixing syntax here. There are two different concepts at play here:

  • List comprehension syntax. Here if acts as a filter; include a value in the iteration or not. There is no else, as that is the 'don't include' case already.

  • A conditional expression. This must always return a value, either the outcome of the 'true' or the 'false' expression.

Remember: list comprehensions produce a sequence of values from a loop. By using if you can control how many elements from the input iterable are used for the output.

A conditional expression on the other hand, works like any other expression: an expression always produces a single result; the conditional expression lets you pick between two possible outcomes. But because it must produce a result you can’t write one without the else part.

Note that expressions can and are frequently nested. The conditional expression itself contains three sub-expressions:

expr1 if expr2 else expr3
# ^ ^
# \ used when expr2 |
# is true |
# /
# used when expr2 is
# false

List comprehension also contain sub-expressions. The one at the start (before the for <target> in <iterable> part) is the sub-expression that is executed each iteration to produce the value in the output list. The iterator expression (after in) is another. The optional if filter takes an expression too. In any of these places you could use a conditional expression if you so choose. But, that doesn’t mean you can add an extra else to the list comprehension without the other parts of the conditional expression syntax.

inconsistent use of tabs and spaces in indentation for ask the expert coding

There are a lot of problems with this code, although I did not actually encounter the error you specified.

You shouldn't be using both tabs and spaces to indent code in the same program. The Python style guide discourages uses of tabs, and prefers using 4 spaces instead, see https://www.python.org/dev/peps/pep-0008/

I'll go through the problems that I did find.

You should be using indention here

    for line in file:
line = line.rstrip('\n')
country, city = line.split('/')
the_world[country] = city4

would become

    for line in file:
line = line.rstrip('\n')
country, city = line.split('/')
the_world[country] = city

Quotation marks do not go around function arguments

def write_to_file(' country_name, city_name):

would become

def write_to_file(country_name, city_name):

You need to put a colon after with statements, and you forgot to indent here as well. You also do not need the last quotation mark.

with open('capital_data.txt,' 'a') as file
file.write('\n' + country_name + '/' + city_name')

would become

with open('capital_data.txt,' 'a') as file:
file.write('\n' + country_name + '/' + city_name')

There is a space in your variable name here

    query_ country = simpledialog.askstring('country', 'type the name of a country:')

would become

        query_country = simpledialog.askstring('country', 'type the name of a country:')

You yet again forgot indentation here,

if query_country in the_world:
result = the_world[query_country]
messagebox.showinfo ('answer',
'The capital city of ' + query_country + ' is ' + result + '!')

would be

    if query_country in the_world:
result = the_world[query_country]
messagebox.showinfo ('answer',
'The capital city of ' + query_country + ' is ' + result + '!')

Likewise here

else:
new_city = simpledialog.askstring('teach me',
'i don\ 't know! ' +
'what is the capital of ' + query_country + '?')

would become

else:
new_city = simpledialog.askstring('teach me',
'i don\ 't know! ' +
'what is the capital of ' + query_country + '?')

Here, you attempt to escape your quotation mark using \, but instead escape the space which comes after it.

'i don\ 't know! ' +

should be

'i don\'t know! ' +

Here, you attempt to escape your quotation mark using \, but instead escape the space which comes after it.

'i don\ 't know! ' +

should be

'i don\'t know! ' +

The full working code is below

from tkinter import Tk, simpledialog, messagebox

def read_from_file():
with open('capital_data.txt') as file:
for line in file:
line = line.rstrip('\n')
country, city = line.split('/')
the_world[country] = city

def write_to_file(country_name, city_name):
with open('capital_data.txt','a') as file:
file.write('\n' + country_name + '/' + city_name)

print(' ask the expert - capital city of the world')
root = Tk ()
root.withdraw()
the_world = {}

read_from_file()

while True:
query_country = simpledialog.askstring('country', 'type the name of a country:')

if query_country in the_world:
result = the_world[query_country]
messagebox.showinfo ('answer',
'The capital city of ' + query_country + ' is ' +
result + '!')
else:
new_city = simpledialog.askstring('teach me',
'i don\'t know! ' +
'what is the capital of ' +
query_country + '?')
the_world[query_country] = new_city
write_to_file(query_country, new_city)

root.mainloop()

Failed to catch syntax error python

You can only catch SyntaxError if it's thrown out of an eval, exec, or import operation.

>>> try:
... eval('x === x')
... except SyntaxError:
... print "You cannot do that"
...
You cannot do that

This is because, normally, the interpreter parses the entire file before executing any of it, so it detects the syntax error before the try statement is executed. If you use eval or its friends to cause more code to be parsed during the execution of the program, though, then you can catch it.

I'm pretty sure this is in the official manual somewhere, but I can't find it right now.

Why isn't my code excepting the errors?

Those errors that has to do with syntax are parse level errors, which means, that are errors that take place before that particular code being interpreted.

The following aren´t the same type of errors:

print("Hello)  # Note the missing '"'

that

print(4/0)     # Syntactically correct, but obviously an error.

Hence, syntax error can't be handled by the try -- except block.

See this answer for more detail: SyntaxError inconsistency in Python?



Related Topics



Leave a reply



Submit