1

I want to unwrap a classmethod into an instance method. Is it possible to do it?

class A:
    @classmethod
    def my_classmethod(cls, *args, **kwargs):
        ...


class B:
    # in this case my_uwrapped_method is still a classmethod
    my_uwrapped_method = A.my_classmethod 

Is it possible to unwrap the my_classmethod into a instance method with some python magic, meanwhile retaining the same code from the original method?

I found this way of unwrapping a staticmethod here: "Unwraping" and wrapping again @staticmethod in meta class

But the same does not work with classmethods, unfortunately.

sg_rs
  • 411
  • 3
  • 13
  • Maybe it's better to have separated method which you would call in your my_classmethod? And if you didn't want to use classmethod you could call that method? – funnydman Aug 09 '22 at 12:00

1 Answers1

2

2 ways to unwrap a classmethod:

A.my_classmethod.__func__  # Get the bound method

A.__dict__['my_classmethod'].__wrapped__  # Unwrap the `classmethod` object

After unwrapping the classmethod, it can be wrapped again to be applied to a new object.

class A:
    @classmethod
    def my_classmethod(cls, *args, **kwargs):
        ...


class B:
    # New classmethod bound to `B`
    my_classmethod2 = classmethod(A.my_classmethod.__func__)
Conchylicultor
  • 4,631
  • 2
  • 37
  • 40