0

While working on a Python project, I realized that during my editing I had left a string floating around in the middle of my code and it didn't generate an error. For example, these few lines execute just fine:

print("Starting")

"This string does nothing"
["Neither does", "this list"]

print("Done")

Output:

Starting
Done

It seems to me that since there are no statements or function calls, those should generate syntax errors. Why is there no exception raised, and is there some use for a construct like this?

4
  • 2
    "is there some use for a construct like this?" - for a start, docstrings.
    – jonrsharpe
    Commented Dec 11, 2014 at 17:43
  • @jonrsharpe Docstrings are a good point, but I would argue that not catching the return value of a print statement is not the same thing. A statement or function call implies that something else is happening, even if you don't catch the return value. Removing a function call can drastically alter the behavior of a program, but removing a lone string won't.
    – skrrgwasme
    Commented Dec 11, 2014 at 17:47
  • I didn't say it was the same thing - you asked whether there was some use for an unassigned string literal and I provided one!
    – jonrsharpe
    Commented Dec 11, 2014 at 17:48
  • 2
    print('Done') is also an expression. It even returns None (produces a value). Should it be a syntax error too? How can I distinguish that call from tuple(['some', 'list']), where tuple() is a type and produces an object? As far as Python syntax is concerned calling a type to produce an object and calling a function are the exact same thing, so you cannot distinguish function calls from other expressions. Commented Dec 11, 2014 at 18:26

1 Answer 1

4

It’s an expression statement. In the REPL, the repr of the result of an expression statement is printed if it’s not None. You use this type of statement all the time when calling functions:

f(x)

It’s just that those functions typically have side effects, whereas literals do not. This is a common syntactic feature of imperative languages with a statement–expression distinction.

1
  • Well that certainly clarifies it. I didn't realize it was considered a statement.
    – skrrgwasme
    Commented Dec 11, 2014 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.