basedmypy icon indicating copy to clipboard operation
basedmypy copied to clipboard

Figure out overloads automatically

Open KotlinIsland opened this issue 1 year ago • 2 comments

def f(value: str, optional=False):
    if value.startswith("a"):
        if optional:
            return None
        raise ValueError
    return value

This should find the two overloads automatically.

KotlinIsland avatar Apr 24 '24 03:04 KotlinIsland

Sounds like an interesting idea.

Do you mean that it:

  • infers that optional is a bool, so can be True or False
  • looks at all of the return / raise statements, and determines how parameters have been narrowed at that point (eg the return None is only reachable when optional is True, and the raise is only reachable when optional is False)
  • in that example, should infer that when optional is True, return is str | None
  • in that example, should infer that when optional is False, return is str
  • this same logic will be applied to all functions / methods that do not specify a return type
  • infers specific exceptions (like TypeError or ValueError) to mean the combination of parameters are wrong

Would it also look at other statements, to find which combinations of parameters would result in an error, such as:

foo: list[str]

def bar(a: bool, b: int | str):
    if a:
        foo.append(b)
   print(b)

infer that when a is True, b has to be a str

Zeckie avatar Jun 12 '24 11:06 Zeckie

  • infers that optional is a bool, so can be True or False
  • looks at all of the return / raise statements, and determines how parameters have been narrowed at that point (eg the return None is only reachable when optional is True, and the raise is only reachable when optional is False)
  • in that example, should infer that when optional is True, return is str | None
  • in that example, should infer that when optional is False, return is str
  • this same logic will be applied to all functions / methods that do not specify a return type

yes

infers specific exceptions (like TypeError or ValueError) to mean the combination of parameters are wrong

Not specifically those types, just the reachability of the control flow.

infer that when a is True, b has to be a str

That seems out of scope for this feature at this point, but an interesting suggestion.

KotlinIsland avatar Jun 12 '24 11:06 KotlinIsland