Skip to content

SupportsBool - an abc for bool-like objects #191

Closed
@wittekm

Description

@wittekm

Warning: This is sort of a weird use case.

In our codebase, we have

class FalseWithAssociatedReason(object):
    def __init__(self, reason):
        self.reason = reason

    def __nonzero__(self):
        # This object is always false in a boolean context.
        return False

The usecase for this is something like the following

def parameter_equals_one(param):
  # type: (Any) -> ???
  if param == 1:
    return True
  else:
    return FalseWithAssociatedReason("Param {} is not 1.".format(param))

def main(...):
  result = parameter_equals_one("2345")
  if not result:
    print result.reason

There's no return type we can use for parameter_equals_one that wouldn't be a union. I propose a SupportsBool abc that FalseWithAssociatedReason could inherit from.

(Only catch: I believe falseness is described by both __nonzero__ and __len__.)

And to those who say the above use case can be covered by exceptions: hey, you're not wrong, but this is a hyper-simplified usecase.

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: featureDiscussions about new features for Python's type annotations

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions