Skip to content

dynamod

Dynamic module creation and management utilities.

This module provides functions for dynamically creating Python modules from source code strings, storing them in a temporary directory, and importing them at runtime. It uses a global namespace variable to manage the module folder across process forks.

make_code_name(code)

Generate a deterministic module name from source code.

Computes a SHA1 hash of the code and returns a name like '_hashed.' truncated to _HASHNAME_LEN characters.

Parameters:

Name Type Description Default
code

The source code string to hash.

required

Returns:

Type Description

A string module name derived from the code hash.

Source code in py_misc_utils/dynamod.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def make_code_name(code):
  """Generate a deterministic module name from source code.

  Computes a SHA1 hash of the code and returns a name like '_hashed.<hash>'
  truncated to _HASHNAME_LEN characters.

  Args:
    code: The source code string to hash.

  Returns:
    A string module name derived from the code hash.
  """
  chash = hashlib.sha1(code.encode()).hexdigest()[:_HASHNAME_LEN]

  return f'_hashed._{chash}'

create_module(name, code, overwrite=None)

Create a dynamic Python module from source code.

Writes the given code to a .py file under the module folder using a dotted name as path components, then imports and returns the module. If the module already exists and overwrite is not allowed, raises RuntimeError. If overwrite is True and the file size hasn't changed, adds a comment hack to force reload (works around Python import subsystem issue #31772).

Parameters:

Name Type Description Default
name

Dotted module name (e.g. 'foo.bar' becomes foo/bar.py).

required
code

The source code string to write to the module file.

required
overwrite

If True, overwrite an existing module. If None or False, raise RuntimeError if the module already exists. Defaults to None.

None

Returns:

Type Description

The imported module object.

Raises:

Type Description
RuntimeError

If the module already exists and overwrite is not True.

Example
from py_misc_utils import dynamod as dm

mod = dm.create_module('mytool.tools', 'ANSWER = 42')

print(mod.ANSWER)  # 42

# Later runs can import it back by name:
print(dm.get_module('mytool.tools').ANSWER)  # 42
print(dm.module_name('mytool.tools'))  # _dynamod.mytool.tools
Source code in py_misc_utils/dynamod.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def create_module(name, code, overwrite=None):
  """Create a dynamic Python module from source code.

  Writes the given code to a .py file under the module folder using a dotted
  name as path components, then imports and returns the module. If the module
  already exists and overwrite is not allowed, raises RuntimeError. If overwrite
  is True and the file size hasn't changed, adds a comment hack to force reload
  (works around Python import subsystem issue #31772).

  Args:
    name: Dotted module name (e.g. 'foo.bar' becomes foo/bar.py).
    code: The source code string to write to the module file.
    overwrite: If True, overwrite an existing module. If None or False, raise
      RuntimeError if the module already exists. Defaults to None.

  Returns:
    The imported module object.

  Raises:
    RuntimeError: If the module already exists and overwrite is not True.

  Example:
    from py_misc_utils import dynamod as dm

    mod = dm.create_module('mytool.tools', 'ANSWER = 42')

    print(mod.ANSWER)  # 42

    # Later runs can import it back by name:
    print(dm.get_module('mytool.tools').ANSWER)  # 42
    print(dm.module_name('mytool.tools'))  # _dynamod.mytool.tools
  """
  path = gns.get(_MOD_FOLDER)
  mpath = os.path.join(path, *name.split('.')) + '.py'

  with _LOCK:
    reload = False
    if os.path.exists(mpath):
      if overwrite in (None, False):
        raise RuntimeError(f'Dynamic module "{name}" already exists: {mpath}')
      else:
        # Note that there exist an issue with Python import subsystem:
        #
        #   https://bugs.python.org/issue31772
        #
        # Such issue causes a module to not be reloaded if the size of the source file
        # has not changed.
        # So BIG HACK here to add an headline comment if that's the case!
        reload = True
        if os.stat(mpath).st_size == len(code):
          code = f'# Note: Added due to https://bugs.python.org/issue31772\n\n{code}'

    os.makedirs(os.path.dirname(mpath), exist_ok=True)
    with open(mpath, mode='w') as f:
      f.write(code)

    module = get_module(name)

    return importlib.reload(module) if reload else module

module_name(name)

Return the full importable name for a dynamic module.

Prepends _MODNAME to the given name with a dot separator.

Parameters:

Name Type Description Default
name

The module name (may contain dots).

required

Returns:

Type Description

The full importable module name string.

Source code in py_misc_utils/dynamod.py
184
185
186
187
188
189
190
191
192
193
194
195
def module_name(name):
  """Return the full importable name for a dynamic module.

  Prepends _MODNAME to the given name with a dot separator.

  Args:
    name: The module name (may contain dots).

  Returns:
    The full importable module name string.
  """
  return f'{_MODNAME}.{name}'

get_module(name)

Import and return a dynamic module by name.

Acquires the global lock and imports the module using module_name().

Parameters:

Name Type Description Default
name

The module name to import.

required

Returns:

Type Description

The imported module object.

Source code in py_misc_utils/dynamod.py
198
199
200
201
202
203
204
205
206
207
208
209
210
def get_module(name):
  """Import and return a dynamic module by name.

  Acquires the global lock and imports the module using module_name().

  Args:
    name: The module name to import.

  Returns:
    The imported module object.
  """
  with _LOCK:
    return importlib.import_module(module_name(name))