3

When doing module = types.ModuleType('mymodule'), we don't get any chance of doing further customization, and we can't override module.__dict__ since it's readonly...

The same seems to apply with all other importlib functions (module_from_spec alike)

Is there a way of doing it which is not too much dirty (like... sub-classing ModuleType, and creating a temporary module and copying the fields...) ?

1 Answer 1

0

You can create a proxy module that delegates attribute access to a separate mapping:

from types import ModuleType

def custom_mapping_module(name, mapping):
    class _CustomMappingModule(ModuleType):
        def __getattr__(self, name):
            return mapping[name]

        def __setattr__(self, name, value):
            mapping[name] = value

        def __delattr__(self, name):
            del mapping[name]

    return _CustomMappingModule(name)

so that as an example:

from collections import ChainMap

c = ChainMap({'a': 1}, {'b': 2})
m = custom_mapping_module('foo', c)
print(m.a) # outputs 1
print(m.b) # outputs 2
del m.a
m.b = 3
print(m.b) # outputs 3
print(c)   # outputs ChainMap({'b': 3}, {'b': 2})
print(m.__name__) # outputs foo
print(isinstance(m, ModuleType)) # outputs True

Demo: https://ideone.com/KrIxhB

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.