Mypy correctly rejects this:
❯ type .\t.py
from numbers import Number
from typing import Dict
Data = Dict[str, Number]
def foo(bar: Data):
print(bar)
bar[1.0] = b'hello'
PS 17:48 00:00.008 C:\Work\Scratch\foo
❯ mypy .\t.py
t.py:9: error: Invalid index type "float" for "Dict[str, Number]";
expected type "str"
t.py:9: error: Incompatible types in assignment (expression has type
"bytes", target has type "Number")
Found 2 errors in 1 file (checked 1 source file)
If typeguard doesn't, maybe you need to raise that as a bug against
that project?
Paul
On Fri, 15 Oct 2021 at 17:20, Sebastian M. Ernst <[email protected]> wrote:
>
> Hi all,
>
> disclaimer: I have no idea on potential syntax or if it is applicable to
> a wide audience or if there is already a good solution to this. It is
> more like a "gap" in the type hint spec that I ran across in a project.
>
> In function/method signatures, I can hint at dictionaries for example as
> follows:
>
> ```python
> from numbers import Number
> from typing import Dict
>
> from typeguard import typechecked
>
> Data = Dict[str, Number]
>
> @typechecked
> def foo(bar: Data):
> print(bar)
> ```
>
> Yes, this is using run-time checks (typeguard), which works just fine.
> Only strings as keys and Number objects as values are going through. (I
> was told that MyPy does not get this at the moment.)
>
> The issue is that `bar` itself still allows "everything" to go in (and out):
>
> ```python
> @typechecked
> def foo2(bar: Data):
> bar[1.0] = b'should not be allowed'
> ```
>
> PEP 589 introduces typed dictionaries, but for a fixed set of predefined
> keys (similar to struct-like constructs in other languages). In
> contrast, I am looking for an arbitrary number of typed keys/value pairs.
>
> For reference, related question on SO:
> https://stackoverflow.com/q/69555006/1672565
>
> Best regards,
> Sebastian
> _______________________________________________
> Python-ideas mailing list -- [email protected]
> To unsubscribe send an email to [email protected]
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/[email protected]/message/DY5DPGWXLOOP3NQYSD73S53EMTRNKD74/
> Code of Conduct: http://python.org/psf/codeofconduct/
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/FOJST3EZKQMK2R342OWN5M3VPEBNYXSC/
Code of Conduct: http://python.org/psf/codeofconduct/