I am new to Python. I have a function like below which returns a dictionary.
def get_my_class_object(self, input):
return {
"foo": {"test": {}}, // this is hard-coded
"var": "FIRST" // real code computes var using the input
}
I'd like to define a class for the return type so I can enable the type using Pyre. What is the best practice to create a python class for above structure?
I tried below class and changed the function signature to return MyClassObject.
class MyClassObject(NamedTuple):
foo: Dict
var: str
def get_my_class_object(self, input) -> MyClassObject:
// create MyClassObject from input and return the object
But Dict is not allowed by Pyre as it is too generic. I can't change "foo": {"test": {}} due to backward compatibility.
There are a few things you might be able to do in this case. Without any context, it is quite hard to know what might be best for you.
But, using a more specific type-hint might work:
Here, instead of a
NamedTuple, it might also be best to use aDataClassHere,
foois typed asdict[str, dict]which may be specific enough for Pyre. If you know what the type of the "innermost" dictionary should be, you can type-hint that here too. For example, let's say the innermost dictionary will eventually be used to map a string to an int, you could type-hint it as:It may also be more clear to use type aliases. Check out the python documentation for more info, but that could look something like:
You might need to change the names of these to better fit your purpose.
Also note, I'm using python 3.9+ syntax for type-hinting, if you are using a lower version, you'll need to import the
Dicttype from thetypingmodule.