Python Forum
Should a function ever be more permissive than its type hints?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Should a function ever be more permissive than its type hints?
#1
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], ...
Reply
#2
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'>
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  determine parameter type in definition function akbarza 1 582 Aug-24-2023, 01:46 PM
Last Post: deanhystad
  i want to use type= as a function/method keyword argument Skaperen 9 1,838 Nov-06-2022, 04:28 AM
Last Post: Skaperen
  match type with value in csv parsing function vinci 2 1,300 Jan-21-2022, 12:19 PM
Last Post: Larz60+
  SQLAlchemy with type hints gontajones 1 6,737 Jun-17-2020, 06:52 PM
Last Post: gontajones
  Creating function inside classes using type wolfmansbrother 3 2,324 Mar-20-2020, 01:21 AM
Last Post: wolfmansbrother
  Type hints and style MaxPowers 1 1,852 Feb-19-2020, 06:56 PM
Last Post: micseydel
  Type hinting - return type based on parameter micseydel 2 2,469 Jan-14-2020, 01:20 AM
Last Post: micseydel
  Getting type from input() function in Python 3.0 leodavinci1990 7 3,727 Jul-29-2019, 08:28 PM
Last Post: avorane
  Type function does not work sunnyarora 2 2,477 Mar-15-2019, 10:50 AM
Last Post: sunnyarora
  Parameters type in a function girbinho 2 2,734 Oct-09-2018, 10:36 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020