driscollis,
@driscollis@mastodon.social avatar

#Python supports function overloading using the functools module. 🐍🔥

It isn't as full-featured as other languages, but it's a handy tool.

Here's an example:

fohrloop,
@fohrloop@fosstodon.org avatar

@driscollis yet another thing in the #python standard library I've never seen or used. I wonder when one would use the functools.singledispatch over a set of if isinstance(..) elif isinstance(..)? The singledispatch feels like a bit of magic since going to the definition of the function does not show what it does and one has to go to Ctrl-F for all the @func.register's to find the implementation 🤔

#functools #pythonstandardlibrary

fohrloop,
@fohrloop@fosstodon.org avatar

@driscollis One use case perhaps for library makers to give possibility for their users to extend their library to new types. Let's say there is somefunc which is used on many places within the library. That supports few types.

To support sometype, user could add an implementation in their own code with:

@somefunc.register(sometype)
def implementation(..):
...

stfn,
@stfn@fosstodon.org avatar

@fohrloop @driscollis I feel that those things, while nice are not exactly Pythonic. Python is most of all a duck-typed language, and should not care about the type of a function arguments, as long as they have a common and expected protocol.

treyhunner,
@treyhunner@mastodon.social avatar

@stfn @fohrloop @driscollis dunder methods are a big exception to the usual "don't check types" suggestion.

We love duck typing everywhere else but the implementation of eq, add, etc. typically have isinstance checks for correctness (they're expected to return NotImplemented for types they don't know how to work with).

I do see singledispatch used rarely though. It's helpful for allowing extension of a third party function, but other than that I'd use match/case today.

stfn,
@stfn@fosstodon.org avatar

@treyhunner @fohrloop @driscollis Right, that is a very good point, thanks for that

  • All
  • Subscribed
  • Moderated
  • Favorites
  • python
  • DreamBathrooms
  • ngwrru68w68
  • tester
  • magazineikmin
  • thenastyranch
  • rosin
  • khanakhh
  • InstantRegret
  • Youngstown
  • slotface
  • Durango
  • kavyap
  • mdbf
  • tacticalgear
  • JUstTest
  • osvaldo12
  • normalnudes
  • cubers
  • cisconetworking
  • everett
  • GTA5RPClips
  • ethstaker
  • Leos
  • provamag3
  • anitta
  • modclub
  • megavids
  • lostlight
  • All magazines