[issue46051] Make @atexit.register work for functions with arguments

Serhiy Storchaka report at bugs.python.org
Mon Dec 20 13:27:46 EST 2021


Serhiy Storchaka <storchaka+cpython at gmail.com> added the comment:

It cannot work this way.

atexit.register() as a function allows you to specify arguments which will be passed to the registered function, but if it is used as a decorator, only one argument (the function itself) is passed to atexit.register() (it is how decorators work). When used as a decorator it can only register functions without parameters.

On other hand, the function corresponding to a class method requires the class argument. There is no magic to determine it at the decoration time, because the class does not exist yet. It will be created only after the class definition body be executed.

It is possible to create a decorator which work the way you want. The simplest method perhaps to create a classmethod subclass with __set_name__() method. __set_name__() will be called after creating the class.

class mydecorator(classmethod):
    def __set_name__(self, type, name):
        atexit.register(self.__func__, type)

class Program:
    @mydecorator
    def clean_up(cls):
        ...

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue46051>
_______________________________________


More information about the Python-bugs-list mailing list