basedmypy
basedmypy copied to clipboard
Figure out overloads automatically
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.
Sounds like an interesting idea.
Do you mean that it:
- infers that
optionalis abool, so can beTrueorFalse - looks at all of the
return/raisestatements, and determines how parameters have been narrowed at that point (eg thereturn Noneis only reachable whenoptionalisTrue, and the raise is only reachable whenoptionalisFalse) - in that example, should infer that when
optionalisTrue, return isstr | None - in that example, should infer that when
optionalisFalse, return isstr - 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
- infers that
optionalis abool, so can beTrueorFalse- looks at all of the
return/raisestatements, and determines how parameters have been narrowed at that point (eg thereturn Noneis only reachable whenoptionalisTrue, and the raise is only reachable whenoptionalisFalse)- in that example, should infer that when
optionalisTrue, return isstr | None- in that example, should infer that when
optionalisFalse, return isstr- 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
aisTrue,bhas to be astr
That seems out of scope for this feature at this point, but an interesting suggestion.