If you are asking can you specify a list of dictionaries containing a custom object as keys, then the answer is below. If you wish to specify more than one type of object as a key within the same dictionary though, this won't work.
You can do the former in Python 3.9 with type aliases. Reference https://docs.python.org/3/library/typing.html gives example with list of dicts.
Example below shows a list of dicts containing custom objects as keys.
from collections.abc import Sequence
class MyClass:
def __init__(self, arg1, arg2):
self.attr1 = arg1 + arg2
class AnotherClass:
def __init__(self, arg1, arg2):
self.attr1 = arg1 + arg2
seq1 = dict[MyClass, int]
seq2 = list[seq1]
def myfunc(arg1: Sequence[seq2]) -> seq2:
for dict in arg1:
for key, value in dict.items():
print(key.attr1, value)
#Correct type provided.
myobj1 = MyClass('A', '1')
myobj2 = MyClass('B','2')
listdict= [{myobj1: 10, myobj2: 20}, {myobj2: 100, myobj1: 200}]
listdict
myfunc(listdict)
#Incorrect type provided.
myobj1 = AnotherClass('A', '1')
myobj2 = AnotherClass('B','2')
listdict= [{myobj1: 10, myobj2: 20}, { myobj2: 100, myobj1: 200}]
myfunc(listdict)
A1 10
B2 20
B2 100
A1 200
Note: Linters may not recognize valid inputs though. E.g. mypy complains that the list of dict(object, int) is not a sequence thereof.
typing.TypedDict
might be what you're looking for? – RepentanceTypeError
message is true: thelist
anddict
classes is not subscriptable.You need to useList
andDict
, after importing them fromtyping
. However, neither is quite what you want; as @IainShelvington points out, you probably wanttyping.TypedDict
(new in Python 3.8). I don't think you can state the type of your parameterx
as accurately as you'd like in Py3.7 -- no type for dicts with heterogeneous values (or keys). – Backfilldict
assumes that all the keys are strings, and you are simply listing the value types, but you aren't indicating which key maps to which types. Positional order isn't appropriate: would your use case really consider{'data': int, "my_object": my_object}
to have a different, incorrect type? – Fecundate