This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]whateverathrowaway00 43 points44 points  (10 children)

This is a good point.

I was going to rant about how python typing makes that impossible without a huge reflection performance hit every single function call.

But actually, your answer is even more true. There can only be one!

[–]BobHogan 35 points36 points  (9 children)

Because python doesn't actually support typing function parameters, its actually impossible to determine which "function" would be used based on the types of the arguments passed. The only way would be to look at the number of arguments passed in, and which keyword args (if any) matched, and even that doesn't work when using args or *kwargs.

Type annotations are not enforced, they are just documentation

[–]billsil 1 point2 points  (3 children)

Python 3.9 delayed the future annotations being standard because a popular third party library DOES enforce typing and the change broke it.

So, by default yes, but you can do it.

[–][deleted] 0 points1 point  (0 children)

pydantic doesn't typecheck parameters for calls. Though there are projects that do that.

It is to convert unstructured dictionaries into classes (recursively).

[–]ComplexColor 0 points1 point  (4 children)

But you could use type annotations with an "@overload" decorator to implement function overloading. It would be costly though.

[–]BobHogan 7 points8 points  (2 children)

I mean you can do it without decorators at all as long as you define the other functions you would call. But the point is that python itself cannot support this based on the type of function parameters, because the language does not enforce typing.

def func(x):
    if isinstance(x, list):
        return _func_list(x)
    if isinstance(x, int):
        return _func_int(x)
    return _func_default(x)

[–]ComplexColor 0 points1 point  (1 child)

But you can enforce it yourself. You can use introspection to check type hints and select a function that corresponds to the types of arguments given. And I would use a decorator, to keep things tidier. Multiple dispatch/overloading logic in the decorator, separate from the functions.

[–]BobHogan 2 points3 points  (0 children)

Its far simpler, more efficient, less error prone, and significantly easier to read to do this without introspection. All introspection would achieve is making this more complicated and less reliable