pythonpython-decoratorspython-3.10

Get the name of a decorated class given the class object


I have decorator function and a simple class that's decorated:

import typing


def mydeco(cls: type) -> typing.Callable:
    def inner(*args: typing.Any, **kwargs: typing.Any) -> object:
        return cls(*args, **kwargs)

    return inner


@mydeco
class Wheels:
    def __init__(self, count: int) -> None:
        self.count = count


if __name__ == "__main__":
    print(Wheels)                         # <function mydeco.<locals>.inner at 0x7f8d663b6d40>
    print(Wheels.__class__)               # <class 'function'>
    print(Wheels.__qualname__)            # mydeco.<locals>.inner
    print(Wheels.__class__.__name__)      # function
    print(Wheels.__class__.__qualname__)  # function
    print(type(Wheels))                   # <class 'function'>

What I would like is to retrieve something like this <class '__main__.Wheels'>, or at least just the name of the class Wheels.


Solution

  • The information I was looking for was saved a bit deeper inside the Wheels object:

    print(Wheels.__closure__[0].cell_contents)  # <class '__main__.Wheels'>
    

    Which is exactly what I needed