Python Forum

Full Version: Should a function ever be more permissive than its type hints?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Here is some (trimmed) code, written by Guido for the random module.

    def randrange(start, stop=None, step=1):
        """Choose a random item from range(start, stop[, step]).
        """
        istart = int(start)
        if istart != start:
            raise ValueError("non-integer arg 1 for randrange()")
        # [don't reference start again, use istart from here]
Here, Guido allows not only an int argument for start, but any argument that can be cast into an int. So 1 will work for start, and so will 2.0 or even "3".

Of course, neither 2.1 nor "3.1" will work. Not even "3.0" will work.

I'd like to know how you would type hint such a function.

# describe intention?
def randrange(start: int, ... 

# or describe functionality?
def randrange(start: Union[int, float, str], ...
actually, the type of rndrange is class
and the arguments of rndrange are considered names (have no type).
This makes them extremely powerful, here's an example:

def show_type(start):
    print(type(start))

show_type(1)
show_type('1')
show_type([1])
show_type({'1': 'one'})
results of running above:
Output:
<class 'int'> <class 'str'> <class 'list'> <class 'dict'>