0
def pair_with_target_sum(nums: Sequence[int], target: int) -> Tuple[int, int]:
    x = _pair_with_target_sum(nums, target, 0, len(nums) - 1)
    return (nums[x[0]], nums[x[1]]) if x else x

Given that _pair_with_target_sum may return None or a Tuple[int, int], the above code works as expected. However, if I remove the parentheses around the tuple in the return statement, and when x is None, the code fails with TypeError: 'NoneType' object is not subscriptable.

Why?.

Other relevant questions:

Python tuple unpacking in return statement

NoneType has no attribute IF-ELSE solution

Abhijit Sarkar
  • 21,927
  • 20
  • 110
  • 219

1 Answers1

2

nums[x[0]], nums[x[1]] if x else x will be treated as:

nums[x[0]], (nums[x[1]] if x else x)

Proof:

>>> import ast
>>> root = ast.parse("nums[x[0]], nums[x[1]] if x else x")
>>> print(ast.dump(root, indent=1))
Module(
 body=[
  Expr(
   value=Tuple(
    elts=[
     Subscript(
      value=Name(id='nums', ctx=Load()),
      slice=Subscript(
       value=Name(id='x', ctx=Load()),
       slice=Constant(value=0),
       ctx=Load()),
      ctx=Load()),
     IfExp(
      test=Name(id='x', ctx=Load()),
      body=Subscript(
       value=Name(id='nums', ctx=Load()),
       slice=Subscript(
        value=Name(id='x', ctx=Load()),
        slice=Constant(value=1),
        ctx=Load()),
       ctx=Load()),
      orelse=Name(id='x', ctx=Load()))],
    ctx=Load()))],
 type_ignores=[])
>>> 

As you can see, the elements of the tuple are Subscript (nums[x[0]]) and IfExp.

Apparently, x is None, but nums[x[0]] will attempt to index into it anyway.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • In case of operator associativity and precedence, I can understand, but why does it associate this way? – Abhijit Sarkar Mar 01 '21 at 07:55
  • @AbhijitSarkar, you can have a look at the [operator precedence table](https://docs.python.org/3/reference/expressions.html#operator-precedence). – ForceBru Mar 01 '21 at 07:59
  • I have, there's nothing about comma or tuple in it. I'll accept your answer since it explains the behavior, but I'm curious as to why this behavior occurs. – Abhijit Sarkar Mar 01 '21 at 08:00