Extend dict keys to allow for string literals?
See original GitHub issueCurrently, string literals canāt be used as dict keys in a Struct
. See example below:
from typing import Literal
from msgspec import Struct, json
AorB = Literal["a", "b"]
class Test(Struct):
d: dict[AorB, float]
data = Test(d={'a': 1.0, 'b': 2.0})
encoded = json.encode(data)
print(encoded)
decoded = json.decode(encoded, type=Test) # TypeError: JSON doesn't support dicts with non-string keys - type `dict[typing.Literal['a', 'b'], float]` is not supported
I would think it should be allowed - but Iād like to hear your thoughts.
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (6 by maintainers)
Top Results From Across the Web
Python "extend" for a dictionary - Stack Overflow
However, I want to point out that many times I have seen the extend method of mapping/set objects desire that in the syntax...
Read more >PEP 589 ā TypedDict: Type Hints for Dictionaries with a Fixed ...
Let's consider a dictionary object that has exactly two valid string keys, 'name' with value type str , and 'year' with value type...
Read more >Dictionaries in Python - Real Python
In this Python dictionaries tutorial, you'll cover the basic characteristics and learn how to access and manage dictionary data. Once you have finished...
Read more >Python List extend() Method (With Examples) - TutorialsTeacher
The extend() method adds all the items from the specified iterable (list, tuple, set, dictionary, string) to the end of the list.
Read more >Template Designer Documentation - Jinja
A dict or iterable of (key, value) pairs will be joined as a query string. When given a string, ā/ā is not quoted....
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
With the new
rename
config option (https://jcristharif.com/msgspec/structs.html#renaming-field-names) in 0.6.0, this could also be represented as a struct with field names renamed to"1"
and"2"
. For example:One reason to prefer this over a dict with literal keys is it allows you to mark fields as required, or provide defaults if theyāre optional (thereās no way to do this for a dict with literal keys). This should also be a bit faster than decoding a dict with literal keys, but whether that matters is application dependent. No reason to change what you have now if itās working for you, just demonstrating another way this could be handled.
š
My example does look silly to write this way, but my IRL use case looks like:
Because the
PdChannel
s are numbers, I canāt use them as keys / attrs!