1

I have the code below, I understand that the function takes 2 integers, so (n : int, m : int), and it returns a tuple with integers of any length, therefore -> tuple[int,...]:

I think this also correct for an empty tuple T : tuple[()] since the tuple at some point in the function has only one value.

However I get this error

main.py:14: error: Incompatible types in assignment (expression has type "Tuple[int]", variable has type "Tuple[]")

What am I missing?


def vectorise(n : int, m : int) -> tuple[int,...]:
  '''creates a tuple of element n repeated m times'''
  T : tuple[()] = () #empty tuple
  counter : int = 0
  while counter < m:
    T = T + (n,) #in Python (n,) is a tuple with one element n
    counter+=1
  #as a result, T can be of arbitrary length
  return T

L = vectorise(100, 5)
2
  • 2
    Why not start as you mean to go on - T: tuple[int, ...] = ....
    – jonrsharpe
    Commented Nov 2, 2021 at 11:39
  • "What am I missing?": The type for T needs to at least be equivalent (able to encompass) the intended return type. As you have hinted T to be an EMPTY tuple, you cannot then return a different type - hence the type incompatibility error. You could instead add the OTHER hint for the return type e.g. tuple[int,...] | tuple[()] to cater for both eventualities. Commented Oct 22, 2023 at 16:42

1 Answer 1

2

The variable T has the type "empty tuple". You are trying to assign something to it which is not an empty tuple. Therefore, you get a type error.

You either need to make sure that you are only assigning empty tuples to T, or make sure that the type of T admits non-empty tuples.

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.