Take these examples:
>>> raise(BaseException())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
BaseException
>>> raise BaseException()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
BaseException
Recall this aphorism:
There should be one-- and preferably only one --obvious way to do it.
If raise
is a keyword, why is it syntactically allowed to be viewed as being invoked like a function?
There are some other keywords as well which allow attached parenthesis. Isn't it confusing?
CodePudding user response:
Putting parentheses around something just makes it a parenthesized value; it does not magically make it a function call.
1
is the same as (1)
, therefore return 1
is the same as return (1)
.
But it's not a function call.
CodePudding user response:
You can add parentheses around any expression, it’s just that the parentheses are required for function calls.
print 123 # error
print(123) # ok
print((123)) # extra parentheses ok
And
raise BaseException() # ok
raise (BaseException()) # extra parentheses ok
CodePudding user response:
Using bare parenthesis would do nothing to the element.
Therefore there is no difference between with and without parenthesis:
>>> (BaseException())
BaseException()
>>> BaseException()
BaseException()
>>>
Only if you add a comma would make it a tuple.
So in short:
raise
is a keyword!
CodePudding user response:
It's not being invoked as a function, you simply have extra parenthesis around the exception object. Consider:
ex = (BaseException())
raise ex
Additionally, your second example provides a counterargument. If raise
was not a keyword, that example would fail.