gws.lib.dynimport

Dynamic imports of Python code.

This package loads Python code at run time, either as a plain script or as a regular module:

  • load_file and load_string execute Python source and return its global namespace. Nothing is added to sys.modules. This is used, for example, for Python config files.

  • import_from_path imports a module from a file path and registers it in sys.modules. Paths inside the application directory are imported as part of the gws package. Other paths (plugins) are imported relative to the deepest parent directory that is not a package (has no __init__.py), so that the plugin’s own package structure is preserved.

Example:

import gws.lib.dynimport

fn = gws.lib.dynimport.load_file('/data/config.py').get('main')

mod = gws.lib.dynimport.import_from_path('gws/plugin/ows_client/wms/caps.py')

Source code: gws.lib.dynimport

Package Contents

exception gws.lib.dynimport.Error

Bases: gws.Error

Dynamic import error.

gws.lib.dynimport.import_from_path(path: str, base_dir: str = gws.c.APP_DIR)

Import a module from a file path.

If the path is a directory, its __init__.py is imported. If a module with the same name is already imported from the same file, it is returned as is.

Parameters:
  • path – Relative or absolute path to the module file or package directory.

  • base_dir – Base directory to resolve relative paths, the application directory by default.

Returns:

The imported module.

Raises:

Error – If the module file is not found, a base directory cannot be located, a module with the same name was imported from a different file, or the import fails.

gws.lib.dynimport.load_file(path: str) → dict

Execute a Python file and return its globals.

Parameters:

path – Path to the Python file.

Returns:

The global namespace of the executed code.

gws.lib.dynimport.load_string(text: str, path='') → dict

Execute a string as Python code and return its globals.

Parameters:
  • text – Python source code.

  • path – File path, used for __file__ and in error messages.

Returns:

The global namespace of the executed code.