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
Question how to type hint a function in a dataclass? Calab 3 881 Feb-27-2025, 04:40 AM
Last Post: Calab
  help with a script that adds docstrings and type hints to other scripts rickbunk 2 1,273 Feb-24-2025, 05:12 AM
Last Post: from1991
  word guessing game, hints STUdevil 1 1,740 Oct-12-2024, 01:53 AM
Last Post: menator01
  word game, how to give hints STUdevil 5 1,644 Oct-07-2024, 06:20 PM
Last Post: STUdevil
  Is changing processes by using match with type function impossible? cametan 1 750 May-30-2024, 02:16 PM
Last Post: cametan
  determine parameter type in definition function akbarza 1 1,262 Aug-24-2023, 01:46 PM
Last Post: deanhystad
  i want to use type= as a function/method keyword argument Skaperen 9 3,698 Nov-06-2022, 04:28 AM
Last Post: Skaperen
  match type with value in csv parsing function vinci 2 2,175 Jan-21-2022, 12:19 PM
Last Post: Larz60+
  SQLAlchemy with type hints gontajones 1 8,527 Jun-17-2020, 06:52 PM
Last Post: gontajones
  Creating function inside classes using type wolfmansbrother 3 3,334 Mar-20-2020, 01:21 AM
Last Post: wolfmansbrother

Forum Jump:

User Panel Messages

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