{
  "$type": "site.standard.document",
  "canonicalUrl": "https://rednafi.com/python/difference-between-typevar-and-union/",
  "description": "Understand when to use constrained TypeVar vs Union in Python type hints for consistent types across function parameters and return values.",
  "path": "/python/difference-between-typevar-and-union/",
  "publishedAt": "2022-01-19T00:00:00.000Z",
  "site": "at://did:plc:fgtm2c26vfcj74rfmeggbyqj/site.standard.publication/3mnl6f7ob462z",
  "tags": [
    "Python",
    "Typing",
    "TIL"
  ],
  "textContent": "If you want to define a variable that can accept values of multiple possible types, using\ntyping.Union is one way of doing that:\n\nHowever, there's another way you can express a similar concept via constrained TypeVar.\nYou'd do so as follows:\n\nSo, what's the difference between these two and when to use which? The primary difference\nis:\n\n> T's type needs to be consistent across multiple uses within a given scope, while U's\n> doesn't.\n\nWith a Union type used as function parameters, the arguments, as well as the return type,\ncan all be different:\n\nHowever, the above type definition will be too loose if you need to ensure that all of your\nfunction parameters must be of the same type in a single scope. Here's where constrained\nTypeVar can come in handy:\n\nIf you run Mypy against the above snippet, you'll get this:\n\nAs the comment implies, this error is coming from the line where I called add(\"hello\", 1).\nThe function add can take parameters of either integer or string type. However, the type\nof both the parameters needs to be the same. Also, the type of the input parameters will\ndefine the type of the output value. So, the types of the input parameters must match,\notherwise, Mypy will complain and in this case, the snippet will also raise a TypeError in\nruntime. Mypy is statically catching a bug that'd otherwise appear in runtime, how\nconvenient!\n\nFurther reading\n\n- [What's the difference between a constrained TypeVar and a Union?]\n\n\n\n\n[what's the difference between a constrained typevar and a union?]:\n    https://stackoverflow.com/questions/58903906/whats-the-difference-between-a-constrained-typevar-and-a-union",
  "title": "Difference between constrained 'TypeVar' and 'Union' in Python"
}