Reputation: 4700
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.
assert
in general?Upvotes: 4
Views: 96
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