Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a81dd65

Browse files
committed
Issue #15528: Delay importing atexit until weakref.finalize() used.
1 parent 99c5afc commit a81dd65

1 file changed

Lines changed: 7 additions & 3 deletions

File tree

Lib/weakref.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
import collections # Import after _weakref to avoid circular import.
2424
import sys
2525
import itertools
26-
import atexit
2726

2827
ProxyTypes = (ProxyType, CallableProxyType)
2928

@@ -464,11 +463,18 @@ class finalize:
464463
_shutdown = False
465464
_index_iter = itertools.count()
466465
_dirty = False
466+
_registered_with_atexit = False
467467

468468
class _Info:
469469
__slots__ = ("weakref", "func", "args", "kwargs", "atexit", "index")
470470

471471
def __init__(self, obj, func, *args, **kwargs):
472+
if not self._registered_with_atexit:
473+
# We may register the exit function more than once because
474+
# of a thread race, but that is harmless
475+
import atexit
476+
atexit.register(self._exitfunc)
477+
finalize._registered_with_atexit = True
472478
info = self._Info()
473479
info.weakref = ref(obj, self)
474480
info.func = func
@@ -569,5 +575,3 @@ def _exitfunc(cls):
569575
finalize._shutdown = True
570576
if reenable_gc:
571577
gc.enable()
572-
573-
atexit.register(finalize._exitfunc)

0 commit comments

Comments
 (0)