Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When is a class decorator called?

I am using the stanza NLP library which uses a decorator to register processors. Stanza has a help page for building your own processors here

They use a class decorator @register_processor("processor_name"). The code for register_processor appears pretty simple. It puts the name of the processor in a dict as the key and the class as the value.

It is unclear to me when the decorator, or the function attached to this decorator is called. Is it called just before the class it initialised or at some other point?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I did try Google searching, I found lots on how to use decorators and when function decorators are called but I couldn’t find this specific answer on class decorators easily.

>Solution :

As @jonrsharpe said, it’s called after the class has been built. Here’s an example of a similar decorator. (Note how the register_class function actually returns a specific inner function; that’s the general pattern for any decorator in Python.)

registry = {}


def register_class(name):
    def decorator(cls):
        registry[name] = cls
        print(f"Registered {name}: {cls}")
        return cls

    return decorator


print("Hello!")


@register_class("foo")
class Bloop:
    pass


print(f"Hi there! We have {registry} in the house.")


@register_class("another")
class Else:
    pass

print(f"Whew, that's a lot of classes! {registry}")

This prints out

Hello!
Registered foo: <class '__main__.Bloop'>
Hi there! We have {'foo': <class '__main__.Bloop'>} in the house.
Registered another: <class '__main__.Else'>
Whew, that's a lot of classes! {'foo': <class '__main__.Bloop'>, 'another': <class '__main__.Else'>}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading