Space between "return" and string

When a function in Python returns a string, the string can be directly connected after “return”. The following is an error example:

def foo():
    return"Foo"

This way of writing is extremely irregular, but it can still be interpreted and run normally.

Perhaps this way of writing should be standardized and a grammatical error message should be added to it.

This sort of thing is code style, there’s many more examples of valid syntax that look bad or are difficult to read.

That’s why linters like flake8, pylint and auto formatters like black exist. They help us keep our code style consistent and readable.

You shouldn’t retroactively make valid syntax invalid, solely for the purposes of code style, that’s a terrible user experience, since it breaks backwards compatibility and adds more potential errors in REPL input.

5 Likes

It’s not a grammatical error. return"Foo" can be tokenized unambiguously as the name return followed by the string literal "Foo". The use of whitespace to further separate the two tokens should be considered a style issue.

You are perhaps suggesting that this produce a SyntaxWarning. Those, however, tend to be used for code that could lead to run-time errors or unintended semantics. That’s not the case here.

5 Likes

If you start with return"Foo", and then decide that “Foo” should be a name (a constant FOO perhaps?), the parser now sees a name returnFOO, and this is most likely a NameError. I would argue that it would be easier for everyone to mandate return to be followed by a space or ( (since some people might be using return like a function). Not having a space works, but I can’t think of a good reason to use it in code other than confusing readers and requiring auto-refactoring tools to special-case for it.

There’s also the well-known [0xfor x in [1, 2]] — this returns [15] because of similar whitespace ambiguity — and that throws a SyntaxWarning.

2 Likes

I can’t think of a good reason to have it in code either, but this is not a reason to change the syntax. Bad code style can be fixed with revision. If any of the problems you mention ever happen, they’ll get fixed at that time. Changing the allowed syntax breaks those cases immediately[1] for no clear benefit.


  1. well, except it would take years for this to end up in a new release of Python, and possibly years more for people to upgrade ↩︎

2 Likes

Most static code analyzers for Python will give warnings about coding style, including the posted case.

The issue applies to any keyword that can be followed by a string literal: ‘if’, ‘elif’, ‘while’ and likely others. I don’t see any of these as a real problem and thus no need to change anything.

6 Likes

纵观github上所有与 “return”/“if”/“while”/“elif” 有关的代码, 虽然没有这种"错误"的写法. 但是我尊重并理解您的决定.

For the benefit of most people here who aren’t readers of Chinese, DeepL suggests the following translation:

1 Like