jaraco / inflect

Correctly generate plurals, ordinals, indefinite articles; convert numbers to words
https://pypi.org/project/inflect
MIT License
957 stars 107 forks source link

Improve typehints for singular_noun #186

Closed zmievsa closed 1 year ago

zmievsa commented 1 year ago

Please note that I am only fixing the problem that I personally encountered. If this pattern of "value or False" is more common in the library -- we'd need to fix those cases as well :)

jaraco commented 1 year ago

What is the problem you encountered?

zmievsa commented 1 year ago

@jaraco Let's say you want to get a singular version of the word but you don't know whether the word is already singular.

import inflect

p = inflect.engine()

def get_singular(word: str) -> str:
    new_word = p.singular_noun(word)
    if new_word is False:
        return word
    return new_word

At this point any adequate type checker will tell you that you can't return new_word because its type is str | Literal[True] which makes sense because we have only checked that it's False and your type hints indicate that it can return True.

Essentially I am just making the type hints here more specific to make sure that type checkers are not angry and for correctness.