I want to declare instance variables in the body of a Class Baz in order to add typehints to another function Foo that returns variables of said types.
The class is largely a wrapper, and looks something like this:
Class BazWrapper:
def __init__(self, number, bar):
bz = bar.get_baz(number)
self.title = bz.title
self.location = bz.location
self.is_bazable = bz.bazable
Following the Typehints Cheatsheet from MyPy, I have tried to declare the instance variables in the class body in order to type them. I am trying to set them
Class BazWrapper:
title: baz.title #Expected Type Expression but received "property"
def __init__(self, number, bar):
bz = bar.get_baz(number)
self.title = bz.title
self.location = bz.location
self.is_bazable = bz.bazable
Alright, reasonable enough. So I tried to get the type of the property by wrapping it.
title: type(baz.title)
#type() call should not be used in type annotation Use Type[T] instead
Again, reasonable, so I did.
title: Type[baz.title] #Expected Type Expression but received "property"
Back to square one.
On some level I get what is happening here, the error message is clear and I know that a property is a method attached as an attribute.
Also, I have a workaround, I could just do title: string and call it a day.
But since I do not have control of Baz, there is this little voice in the back of my head that says "What if baz.title changes? Where will your hardcoded types be then?"
So, where do I go from here? Is it possible to use the type of a property as a typehint? If not, what is the best course of action going forward to get BazWrapper typed?