'How come this python typings check doesn't understand I'm returning a bool?

I have two methods, both type annotated in python3.

The first being:

def is_user_edit_only(self) -> bool:
    company = self.get_company()
    if company:
        return company.is_company_edit_only()
    return False

and the method is_company_edit_only looks like this:

def is_company_edit_only(self) -> bool:
    return bool(*internal company logic)

the actual logic isnt important, the functions work just fine. My question is, how come I get the type error error: Returning Any from function declared to return "bool" why cant mypy tell that the method being called in is_user_edit_only returning a bool since it is also labelled as returning a bool? Why does it think its returning any???



Solution 1:[1]

This is probably a problem with company = self.get_company(). You need to include a hint that this is of type Company. For example:

class Company:
    ...
    def is_company_edit_only(self) -> bool:
        return bool(*internal company logic)

and when using this class

def is_user_edit_only(self) -> bool:
    company: Company  # <- include this type hint
    company = self.get_company()
    if company:
        return company.is_company_edit_only()
    return False

This way, it is clear that company.is_company_edit_only() will return a bool.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nechoj