user1179317
user1179317

Reputation: 2923

Python load tempfile as module

I can't seem to load a tempfile with contents using importlib. It works fine if I have the content saved under a python file (with .py extension), then provide that file path.

Is there a way to make the importlib work with a tempfile?

For reference, see the sample code below:

import importlib
import importlib.util
import tempfile


with tempfile.NamedTemporaryFile(mode="w", delete=False) as tf:
    tf.write("""
class Test:
    def __init__(self):
        pass
""")
    tf.seek(0)

    file_path = tf.name

    spec = importlib.util.spec_from_file_location("script", file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)

    t = getattr(module, "Test", None)
    print(t)

I get an error:

Traceback (most recent call last):
  File "test.py", line 17, in <module>
    module = importlib.util.module_from_spec(spec)
  File "<frozen importlib._bootstrap>", line 580, in module_from_spec
AttributeError: 'NoneType' object has no attribute 'loader'

Upvotes: 0

Views: 289

Answers (2)

loki
loki

Reputation: 1

Use NamedTemporaryFile(mode="w", suffix=".py", delete=False).

importlib.util.spec_from_file_location works for known file name extensions (.py, .so, ...), but not for others (.txt...)

Upvotes: 0

Carl_M
Carl_M

Reputation: 948

Note: spec = importlib.util.spec_from_file_location("script", file_path)
spec is None

import importlib
import importlib.util
import tempfile

with tempfile.NamedTemporaryFile(mode="w", delete=False) as tf:
    tf.write("""
class Test:
    def __init__(self):
        pass
""")
    tf.seek(0)

    file_path = tf.name

    spec = importlib.util.spec_from_file_location("script", file_path)
    print(f'{spec=}')
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)

    t = getattr(module, "Test", None)
    print(t)

Upvotes: 0

Related Questions