Skip to content

Commit

Permalink
example
Browse files Browse the repository at this point in the history
  • Loading branch information
szabgab committed Dec 14, 2024
1 parent 3130c89 commit 43a2cd0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 9 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,30 @@
def the_same[T](x: T, y: T) -> None:
print(x, y)

def no_problem[T](x: T, y: T) -> None:
print(type(x).__name__, type(y).__name__)

no_problem(2, 2)
no_problem("hi", "hi")
no_problem("hi", 2)

# -----------------------------
from typing import TypeVar

T = TypeVar('T', int, str)

def the_same(x: T, y: T) -> None:
print(type(x).__name__, type(y).__name__)

the_same(2, 2)
the_same("hi", "hi")
the_same("hi", 2)


# -----------------------------
Q = TypeVar('Q', int, str)

def different(x: T, y: Q) -> None:
print(type(x).__name__, type(y).__name__)

different(2, 2)
different("hi", "hi")
different("hi", 2)
18 changes: 11 additions & 7 deletions python/python-types-at-pyweb-2024-12.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,17 @@ Found 1 error in 1 file (checked 1 source file)

![](examples/python-types-at-pyweb-2024-12/generics.py)

## Two variables of the same and different types
{id: python-types-at-pyweb-2024-12-same-and-different-types}

![](examples/python-types-at-pyweb-2024-12/generics_two_types.py)

```
$ mypy generics_two_types.py
generics_two_types.py:10:1: error: Value of type variable "T" of "the_same" cannot be "object" [type-var]
Found 1 error in 1 file (checked 1 source file)
```

## mypy suggestions
{id: python-types-at-pyweb-2024-12-mypy-suggestions}

Expand Down Expand Up @@ -301,11 +312,4 @@ Found 1 error in 1 file (checked 1 source file)
```


## Two variables of the same and different types
{id: python-types-at-pyweb-2024-12-same-and-different-types}

TODO: Why is mypy accepting this?

![](examples/python-types-at-pyweb-2024-12/generics_two_types.py)


0 comments on commit 43a2cd0

Please sign in to comment.