This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author dino.viehland
Recipients dino.viehland
Date 2020-01-14.21:33:30
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
I'm trying to create a custom module type for a custom loader where the returned modules are immutable.  But I'm running into an issue where the immutable module type can't be used as a module for a package.  That's because the import machinery calls setattr to set the module as an attribute on it's parent in

        # Set the module as an attribute on its parent.
        parent_module = sys.modules[parent]
        setattr(parent_module, name.rpartition('.')[2], module)

I'd be okay if for these immutable module types they simply didn't have their children packages published on them.

A simple simulation of this is a package which replaces its self with an object which doesn't support adding arbitrary attributes:

import sys

class MyMod(object):
    __slots__ = ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
    def __init__(self):
        for attr in self.__slots__:
            setattr(self, attr, globals()[attr])

sys.modules['x'] = MyMod()

# Empty file

>>> from x import y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load_unlocked
AttributeError: 'MyMod' object has no attribute 'y'

There's a few different options I could see on how this could be supported:
    1) Simply handle the attribute error and allow things to continue
    2) Add ability for the modules loader to perform the set, and fallback to setattr if one isn't available.  Such as:
         getattr(parent_module, 'add_child_module', setattr)(parent_module, name.rpartition('.')[2], module)
    3) Add the ability for the module type to handle the setattr:
         getattr(type(parent_module), 'add_child_module', fallback)(parent_module, 
, name.rpartition('.')[2], module)
Date User Action Args
2020-01-14 21:33:31dino.viehlandsetrecipients: + dino.viehland
2020-01-14 21:33:31dino.viehlandsetmessageid: <>
2020-01-14 21:33:31dino.viehlandlinkissue39336 messages
2020-01-14 21:33:31dino.viehlandcreate