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
  SQLAlchemy with type hints gontajones 1 2,191 Jun-17-2020, 06:52 PM
Last Post: gontajones
  Creating function inside classes using type wolfmansbrother 3 880 Mar-20-2020, 01:21 AM
Last Post: wolfmansbrother
  Type hints and style MaxPowers 1 843 Feb-19-2020, 06:56 PM
Last Post: micseydel
  Type hinting - return type based on parameter micseydel 2 1,070 Jan-14-2020, 01:20 AM
Last Post: micseydel
  Getting type from input() function in Python 3.0 leodavinci1990 7 1,761 Jul-29-2019, 08:28 PM
Last Post: avorane
  Type function does not work sunnyarora 2 1,156 Mar-15-2019, 10:50 AM
Last Post: sunnyarora
  Parameters type in a function girbinho 2 1,571 Oct-09-2018, 10:36 PM
Last Post: micseydel
  function type? microphone_head 3 1,923 Sep-13-2018, 05:44 AM
Last Post: vijayhackr
  Why args type is always tuple, when passed it as argument to the function. praveena 5 2,846 Jan-16-2018, 09:07 AM
Last Post: praveena

Forum Jump:

User Panel Messages

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