1

I am trying to build Electron (basically Chromium) on Fedora Rawhide. The distro (as of 2023) ships with Python 3.12. One of the scripts ran during build fails due to a missing imp module. The offending function is:

  def load_module(self, fullname):
    """Loads the module specified by |fullname| and returns the module."""
    if fullname in sys.modules:
      # Per PEP #302, if |fullname| is in sys.modules, it must be returned.
      return sys.modules[fullname]

    if (not fullname.startswith('google.protobuf.') or
        not self._module_exists(fullname)):
      # Per PEP #302, raise ImportError if the requested module/package
      # cannot be loaded. This should never get reached for this simple loader,
      # but is included for completeness.
      raise ImportError(fullname)

    filepath = self._fullname_to_filepath(fullname)
    return imp.load_source(fullname, filepath)

How can i replace this usage of imp using only libraries available on a Linux distro? (Bonus points if the solution is backward compatible — Chromium needs to be buildable with Python as old as 3.6, any patch requiring new features will be likely rejected by upstream)

1 Answer 1

4

I've fixed the same problem recently.

The possible answer is:

import importlib.util
import importlib.machinery

def load_source(modname, filename):
    loader = importlib.machinery.SourceFileLoader(modname, filename)
    spec = importlib.util.spec_from_file_location(modname, filename, loader=loader)
    module = importlib.util.module_from_spec(spec)
    # The module is always executed and not cached in sys.modules.
    # Uncomment the following line to cache the module.
    # sys.modules[module.__name__] = module
    loader.exec_module(module)
    return module

It's from official importlib documentation

In this official issue you can find different solutions.

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.