News for hackers. Stuff that matters.
Re:Advanced Python Features by stitched2gethr on Wednesday April 23, 2025 @09:40AM (#43772060)
> @overload is a decorator from Python’s typing module that lets you define multiple signatures for the same function.

I'll be honest, I've never understood this language feature (it exists in several languages). Can someone honestly help me understand? When is a function with many potential signatures more clear than just having separate function names?

Re:Advanced Python Features by ryandv on Wednesday April 23, 2025 @10:12AM (#43772473)
It's an implementation of "ad-hoc polymorphism", where, for example, it may make sense to "add" (+) together numbers of various types: integers, floating points, rational numbers, etc.

Thus the (+) operator for addition is "overridden" or "polymorphic" in the types of numbers that can be added together.

The argument for having a polymorphic signature rather than just multiple separate "monomorphic" functions is similar to that for "generics," otherwise known as "parametric polymorphism": why not just have a function `forEachInt` for iterating over lists of ints, a separate function `forEachChar` for iterating over lists of characters, and so on?

Higher levels of abstraction and generality, less boilerplate and coupling to any particular choice of data structure or implementation.

You could of course go the route of golang which indeed just had you write "monomorphized" versions of everything. Several years later generics were added to the language.

Alternatively, you throw everything out and never have to worry about typing or polymorphism, at the cost of static safety.

Re:Advanced Python Features by klankeser on Wednesday April 23, 2025 @09:44AM (#43772126)
I would recommend reading the article example once more. Going from the example, without the overload, the function would return a union type which means any time you use the function, you have to put a type check to the result to know if the output is a list or not. With overload, as soon as an argument to the function is a certain type, the output is determined, so you won't need to type check.
Re:Advanced Python Features by pdabbadabba on Wednesday April 23, 2025 @09:56AM (#43772264)
I think that GP's point is that you could accomplish the same thing by simply having separate functions with different names, signatures, and return types.
Re:Advanced Python Features by Izkata on Wednesday April 23, 2025 @09:45AM (#43772142)
In other languages it's an alternate way to do default or optional values in function arguments. Python instead usually uses kwargs for this.
Re:Advanced Python Features by morkalork on Wednesday April 23, 2025 @09:47AM (#43772162)
That's what you get when you add a typing system and come full circle to doing OOP like Java.