Python Forum
mypy, type aliases and type variables
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
mypy, type aliases and type variables
#1
I'm not sure, whether it's a good place to ask such question. If it's not, please tell me, where it suits better.

I use Python 3.11/3.12, and mypy 1.6.0.

Here's the code:

from typing import TypeVar, Callable

T = TypeVar('T')

# type alias, for Python 3.11
IntToSomething = Callable[ [int], T ]

def callPlusOne(f : IntToSomething, val : int) -> T:
  return f(val+1)

def prettyInt(val : int) -> str:
  return f'Your pretty number is {val}'

print( callPlusOne(prettyInt, 10) )
It's perfectly fine, and can be run without any problems. mypy finds it incorrect, though (it's about the callPlusOne function):

Output:
error: A function returning TypeVar should receive at least one argument containing the same TypeVar [type-var]
The solution (?) is to get rid of type alias (who needs them, anyway? Wink ):

from typing import TypeVar, Callable

T = TypeVar('T')

def callPlusOne(f : Callable[ [int], T ], val : int) -> T:
  return f(val+1)

def prettyInt(val : int) -> str:
  return f'Your pretty number is {val}'

print( callPlusOne(prettyInt, 10) )
No type alias used, no problem for mypy. And anyone is happy. Well, anyone but me: I'd like to use type aliases, since they make my code more readable.

Am I missing something, or mypy has some problems with type parameters in type aliases?
Reply


Messages In This Thread
mypy, type aliases and type variables - by tomciodev - Oct-18-2023, 07:34 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Is changing processes by using match with type function impossible? cametan 1 157 May-30-2024, 02:16 PM
Last Post: cametan
Sad [Solved] I'm not getting the good type slain 18 1,180 Apr-11-2024, 01:36 PM
Last Post: slain
Question How to get a removable disc type in drive Daring_T 12 1,598 Feb-11-2024, 08:55 AM
Last Post: Gribouillis
  all of attributes and methods related to a special type akbarza 4 601 Jan-19-2024, 01:11 PM
Last Post: perfringo
  Precision with Decimal Type charlesrkiss 9 918 Jan-18-2024, 06:30 PM
Last Post: charlesrkiss
  How to detect this type of images AtharvaZ 0 399 Jan-02-2024, 03:11 PM
Last Post: AtharvaZ
  problem with help(type(self)) in Idle akbarza 1 558 Dec-26-2023, 12:31 PM
Last Post: Gribouillis
  Static type checking with PyPy pitosalas 1 532 Dec-14-2023, 09:29 PM
Last Post: deanhystad
  How does sqlite3 module determine value type mirlos 2 1,030 Dec-12-2023, 09:37 AM
Last Post: mirlos
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 562 Oct-17-2023, 09:46 AM
Last Post: tomciodev

Forum Jump:

User Panel Messages

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