4

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?
2
  • 2
    Python itself never enforces variable, parameter, or return types. It is a dynamically typed language Commented Jun 8, 2018 at 21:31
  • 1
    They're called type hints for a reason. The interpreter does not use them at all, although they are available as object attributes during runtime. Commented Jun 8, 2018 at 21:59

1 Answer 1

5

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.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.