7

I currently type hint a function returning tuple as follows:

FuncOutput = Tuple[nib.Nifti1Image,
                   nib.Nifti1Image,
                   nib.Nifti1Image,
                   nib.Nifti1Image,
                   nib.Nifti1Image,
                   nib.Nifti1Image,
                   nib.Nifti1Image]

Is there a way to do this in a concise manner where I can specify the length without typing it so many times?

Luca
  • 10,458
  • 24
  • 107
  • 234
  • I only know the `Tuple[nib.Nifti1Image, ...]` syntax that doesn't specify the length, but have you tried something like `Tuple[*[nib.Nifti1Image]*7]`. I have low expectations though. – Adirio Sep 04 '20 at 12:20
  • 1
    @Adirio, you don't need to unpack list, use tuple instead `Tuple[(nib.Nifti1Image,) * 7]`. – Olvin Roght Sep 04 '20 at 12:21
  • 1
    @OlvinRoght would any of these two solutions (list unpacking or tuple) work in type hints? – Adirio Sep 04 '20 at 12:24
  • 1
    Does this answer your question? [Specify length of Sequence or List with Python typing module](https://stackoverflow.com/questions/44833822/specify-length-of-sequence-or-list-with-python-typing-module) – Georgy Dec 07 '20 at 17:35

2 Answers2

5

No. typing.Tuple only supports typing each element or a variable number of elements.

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
  • 2
    No, you're not right. `Tuple[(nib.Nifti1Image,) * 7]` will work. – Olvin Roght Sep 04 '20 at 12:20
  • @OlvinRoght are you sure that gets translated to `Tuple[nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image]` and not to `Tuple[(nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image)]`? Notice the brackets in the second one. – Adirio Sep 04 '20 at 12:22
  • @Adirio, yes, I am sure. – Olvin Roght Sep 04 '20 at 12:22
  • 1
    @OlvinRoght ``mypy`` rejects that as ``error: Invalid type comment or annotation``. – MisterMiyagi Sep 04 '20 at 12:24
  • @MisterMiyagi, [check](https://repl.it/repls/PhonyDarkmagentaCygwin) – Olvin Roght Sep 04 '20 at 12:25
  • 2
    @OlvinRoght That is not a static type annotation/hint. It is a runtime representation, which can of course be constructed in arbitrary ways. One could in principle use ``exec`` to construct such a runtime type – that does not make it a valid static type. – MisterMiyagi Sep 04 '20 at 12:26
0

You can use type variable.

T = TypeVar('T')
tuple7 = tuple[T, T, T, T, T, T, T]
# then you can write
FuncOutput = tuple7[nib.Nifti1Image]
function2
  • 106
  • 1
  • 8