Sep-04-2021, 05:52 PM

@staticmethod def formula_obj_to_string(formula: Formula) -> str: """Recursive function to assemble a string representation of the formula described by the a Formula object. Parameters: formula: The Formula object to build the string repr. of. Returns: A string representing the formula object. """ if is_variable(formula.root) or is_constant(formula.root): return formula.root return ( Formula.negate_formula(formula) if is_unary(formula.root) else Formula.create_binary_formula( formula.root, formula.first, formula.second ) )

class Formula: """An immutable propositional formula in tree representation, composed from atomic propositions, and operators applied to them. Attributes: root (`str`): the constant, atomic proposition, or operator at the root of the formula tree. first (`~typing.Optional`\\[`Formula`]): the first operand to the root, if the root is a unary or binary operator. second (`~typing.Optional`\\[`Formula`]): the second operand to the root, if the root is a binary operator. """ root: str first: Optional[Formula] second: Optional[Formula]

@lru_cache(maxsize=100) # Cache the return value of is_unary def is_unary(string: str) -> bool: """Checks if the given string is a unary operator. Parameters: string: string to check. Returns: ``True`` if the given string is a unary operator, ``False`` otherwise. """ return string == "~"

`Mypy`

gives me an error: `Argument 1 to "formula_obj_to_string" of "Formula" has incompatible type "Optional[Formula]"; expected "Formula"`

But in this case, I know that according to the conditions that the argument

`formula.first`

will be of type `Formula`

. How can I type-assert it here so that `Mypy`

won't yell on that?Thanks in advance!