-
Notifications
You must be signed in to change notification settings - Fork 0
JDict
dxstiny edited this page Oct 28, 2022
·
2 revisions
(Wiki is WIP)
from typing import Optional
from pyaddict import JDict
match = {
"home": {
"name": "Liverpool",
"score": 2
},
"away": {
"name": "Chelsea",
"score": 1
}
}
match2 = {
"home": {
"name": "Manchester City",
"score": 3
},
# opponent is not known yet
}
jdict = JDict(match)
jdict2 = JDict(match2)
print(type(match2.get("home", dict()).get("name"))) # Any | None -> <class 'str'>
print(type(match2.get("away", dict()).get("name"))) # Any | None -> <class 'NoneType'>
print(type(match2.get("away", dict()).get("name", None))) # Any | None -> <class 'NoneType'>
# you can't specify the type you want; you can only specify the default value
# if you want to specify the type, you have to do this
name: Optional[str] = match2.get("away", dict()).get("name")
# but this is not safe
# because you can't be completely sure that the value is a actually string:
score: Optional[str] = match2.get("home", dict()).get("score")
print(type(score), score) # <class 'int'> 3
# ---------------------------------------------
# JDict offers this out of the box
print(type(jdict2.ensureCast("home", JDict).optionalGet("name", str))) # str | None -> <class 'str'>
print(type(jdict2.ensureCast("away", JDict).optionalGet("name", str))) # str | None -> <class 'NoneType'>
# your IDE knows the type of the value already
score = jdict2.ensureCast("home", JDict).optionalGet("score", str)
print(type(score), score) # <class 'NoneType'> None
score = jdict2.ensureCast("home", JDict).optionalGet("score", int)
print(type(score), score) # <class 'int'> 3
(The full example can be found here)