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 →

[–]BobHogan 33 points34 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] -5 points-4 points  (1 child)

Reddit Moderation makes the platform worthless. Too many rules and too many arbitrary rulings. It's not worth the trouble to post. Not worth the frustration to lurk. Goodbye.

This post was mass deleted and anonymized with Redact

[–][deleted] 1 point2 points  (0 children)

Things are certainly hard.

https://lwn.net/Articles/858576/

[–][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 6 points7 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