How to understand the difference between class_eval() and instance_eval()?

As the documentation says, class_eval evaluates the string or block in the context of the Module or Class. So the following pieces of code are equivalent: class String def lowercase self.downcase end end String.class_eval do def lowercase self.downcase end end In each case, the String class has been reopened and a new method defined. That … Read more

How can I use functools.singledispatch with instance methods?

Update: As of Python 3.8, functools.singledispatchmethod allows single dispatch on methods, classmethods, abstractmethods, and staticmethods. For older Python versions, see the rest of this answer. Looking at the source for singledispatch, we can see that the decorator returns a function wrapper(), which selects a function to call from those registered based on the type of … Read more