Miladiouss
Miladiouss

Reputation: 4700

How to specify the type of a function input and output without using assert?

I am using Python 3.6 and would like to define a function that takes two integers a and b and returns their division c = a//b. I would like to enforce the input and output types without using assert. My understanding from what I have found in the documentations and on this site is that one should define this function as such:

def divide(a: int, b: int) -> int:
    c = a // b
    return c

divide(3, 2.) # Output: 1.0

I was expecting an error (or a warning) since b and c are not integers.

  1. What is the issue with my particular code?
  2. How can I specify input and output types correctly without using assert in general?

Upvotes: 4

Views: 96

Answers (1)

wim
wim

Reputation: 362597

Enforcing runtime validation is currently only done by user code, for example using a 3rd party library.

One such choice is enforce:

>>> import enforce  # pip install enforce
>>> @enforce.runtime_validation
... def divide(a: int, b: int) -> int:
...     c = a // b
...     return c
... 
... 
>>> divide(3, 2.0)
RuntimeTypeError: 
  The following runtime type errors were encountered:
       Argument 'b' was not of type <class 'int'>. Actual type was float.

Upvotes: 5

Related Questions