Cory Kramer
Cory Kramer

Reputation: 117906

Implicit truthiness of return type

I have a function that returns a list

def get_something() -> List[str]:
    return ['abc']

later I have a function that (among other things) returns a bool based on this list being empty or not. Based on PEP 8 recommendation of

For sequences, (strings, lists, tuples), use the fact that empty sequences are false

I wanted to write something like

def check_something_implicit() -> bool:
    return get_something()  # implicit truthiness of returned list

but the type checker will return an error like

error: Incompatible return value type (got "List[str]", expected "bool")

Instead I have to write an explicit version like

def check_something_explicit() -> bool:
    return len(get_something()) > 0

# or

def check_something_explicit() -> bool:
    return get_something() != []

Is there a way to use implicit truthiness in a return statement context?

Upvotes: 2

Views: 207

Answers (1)

Nyps
Nyps

Reputation: 886

As stated by @matszwecja, you simply cast your list to a boolean, i.e.

def check_something_explicit() -> bool:
    return bool(get_something())

I think using implicit booleanness would actually be to avoid the check_something_explicit function altogether. In your code this would look like this for example:

# instead of this
if check_something_implicit():
    # some further operations

# directly use this
if get_something():
    # some further operations

Upvotes: 2

Related Questions