Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Set __module__ attribute of created class to caller frame in ABCMeta.…
…__new__.

This is to make dynamically-defined classes pickleable.
  • Loading branch information
alegonz committed Jun 16, 2019
commit ccdf280fe9fe694f0c74ece31fb9db2f778a1589
13 changes: 13 additions & 0 deletions Lib/_py_abc.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import sys
from _weakrefset import WeakSet


Expand Down Expand Up @@ -33,6 +34,18 @@ class ABCMeta(type):
_abc_invalidation_counter = 0

def __new__(mcls, name, bases, namespace, /, **kwargs):

if '__module__' not in namespace:
try:
# Set __module__ to the frame where the class is created
module = sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
# Bypass for environments where sys._getframe is not defined (e.g. Jython)
# or sys._getframe is not defined for arguments greater than 0 (IronPython)
pass
else:
namespace['__module__'] = module

cls = super().__new__(mcls, name, bases, namespace, **kwargs)
# Compute set of abstract method names
abstracts = {name
Expand Down
13 changes: 13 additions & 0 deletions Lib/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

"""Abstract Base Classes (ABCs) according to PEP 3119."""

import sys

def abstractmethod(funcobj):
"""A decorator indicating abstract methods.
Expand Down Expand Up @@ -82,6 +83,18 @@ class ABCMeta(type):
even via super()).
"""
def __new__(mcls, name, bases, namespace, **kwargs):

if '__module__' not in namespace:
try:
# Set __module__ to the frame where the class is created
module = sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
# Bypass for environments where sys._getframe is not defined (e.g. Jython)
# or sys._getframe is not defined for arguments greater than 0 (IronPython)
pass
else:
namespace['__module__'] = module

cls = super().__new__(mcls, name, bases, namespace, **kwargs)
_abc_init(cls)
return cls
Expand Down