4

I would like to use python's typing module to check and document function arguments and the like.

Let's say I wanted to require a list with two elements, both of which are ints (e.g. [1,2], [214,12] are good while [1,2,3] or [214., 12] are bad). Is there a way to specify this? (Or is there, maybe, some deep reason why this wouldn't make sense for a python list?)

I see that you can do something like this with Typing.Tuple. However, the functionality seems somewhat limited.

webelo
  • 1,646
  • 1
  • 14
  • 32
  • Use your own validator function, check len(input) == 2 and each element in input are integers – Wonka Oct 01 '19 at 11:21
  • What do you mean *"limited"*? You can definitely express what you describe here. – jonrsharpe Oct 01 '19 at 11:23
  • I think you mean ```214``` and not ```214.``` – Sid Oct 01 '19 at 11:23
  • Typing and length-checks do not go hand in hand. Typing is used by some ide`s for compile time type checking/hinting. It is not enforced. Use a combination of typing ( `def do_something( data: List[int]) -> List[int]:` and normal length check assertions. – Patrick Artner Oct 01 '19 at 11:24
  • Thanks for pointing to the question. I was not able to find it previously. @Sid `214.` was an example of a bad case. – webelo Oct 01 '19 at 11:36
  • @jonrsharpe if you could answer the linked question that would be great. Both answers there point to the conclusion that this is not something that can or ought to be done. – webelo Oct 01 '19 at 11:45

0 Answers0