OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Why does overloading __new__ with singledispatchmethod not work as expected?

  • Thread starter Thread starter Daraan
  • Start date Start date
D

Daraan

Guest
I want my __new__ method to behave differently in some cases and wanted to split it into overloaded functions with singledispatchmethod.
For other methods it works like expected. However for __new__ it does not work, the overloading functions are never called. What is the reason for that?

Code:
from functools import singledispatchmethod

class Foo:
     @singledispatchmethod
     def __new__(cls, arg1, **kwargs):
         return "default call"

     @__new__.register(int)
     def _(cls, arg1, **kwargs):
         return "called with int " + str(arg1)

print(Foo("hi"))
# default call
print(Foo(1))
# default call


As an experiment also used singledispatch instead but without success.
<p>I want my <code>__new__</code> method to behave differently in some cases and wanted to split it into overloaded functions with <code>singledispatchmethod</code>.<br />
For other methods it works like expected. However for <code>__new__</code> it does not work, the overloading functions are never called. What is the reason for that?</p>
<pre><code>from functools import singledispatchmethod

class Foo:
@singledispatchmethod
def __new__(cls, arg1, **kwargs):
return "default call"

@__new__.register(int)
def _(cls, arg1, **kwargs):
return "called with int " + str(arg1)

print(Foo("hi"))
# default call
print(Foo(1))
# default call
</code></pre>
<hr />
<p>As an experiment also used <code>singledispatch</code> instead but without success.</p>
 

Latest posts

ن
Replies
0
Views
1
نعمان منذر محمود الجميلي
ن
Top