Skip to content

asdf.config

Methods for getting and setting asdf global configuration options.

Classes:

Name Description
AsdfConfig

Container for ASDF configuration options. Users are not intended to

Functions:

Name Description
config_context

Context manager that temporarily overrides asdf configuration.

get_config

Get the current config, which may have been altered by

AsdfConfig

AsdfConfig()

Bases: _IsSet

Container for ASDF configuration options. Users are not intended to construct this object directly; instead, use the asdf.get_config and asdf.config_context module methods.

Methods:

Name Description
__repr__
__setattr__
add_extension

Register a new extension. The new extension will

add_resource_mapping

Register a new resource mapping. The new mapping will

remove_extension

Remove a registered extension.

remove_resource_mapping

Remove a registered resource mapping.

reset_extensions

Reset extensions to the default list registered via entry points.

reset_resources

Reset registered resource mappings to the default list

Attributes:

Name Type Description
all_array_compression Compression

Override the compression type on all binary blocks in the

all_array_compression_kwargs dict[str, Any] | None

Dictionary of keyword arguments provided to the compressor during

all_array_storage ArrayStorage

Override the array storage type of all blocks

array_inline_threshold int | None

Get the threshold below which arrays are automatically written

default_array_save_base bool

Option to control if when saving arrays the base array should be

default_version str

Get the default ASDF core schemas version used for

extensions list[ExtensionProxy]

Get the list of registered extensions.

io_block_size int

Get the block size used when reading and writing

lazy_tree bool

Get configuration that controls if ASDF tree contents

legacy_fill_schema_defaults bool

Get the configuration that controls filling defaults

resource_manager ResourceManager

Get the asdf.resource.ResourceManager instance. Includes resources from

resource_mappings list[ResourceMappingProxy]

Get the list of registered resource mapping instances. Unless

validate_on_read bool

Get configuration that controls schema validation of

warn_on_failed_conversion bool

Get configuration that controls if errors during

Source code in asdf/config.py
def __init__(self):
    super().__init__()
    self._resource_mappings = None
    self._resource_manager = None
    self._extensions = None
    self._validate_on_read = DEFAULT_VALIDATE_ON_READ
    self._default_version = DEFAULT_DEFAULT_VERSION
    self._legacy_fill_schema_defaults = DEFAULT_LEGACY_FILL_SCHEMA_DEFAULTS
    self._io_block_size = DEFAULT_IO_BLOCK_SIZE
    self._array_inline_threshold: int | None = DEFAULT_ARRAY_INLINE_THRESHOLD
    self._all_array_storage: ArrayStorage | None = DEFAULT_ALL_ARRAY_STORAGE
    self._all_array_compression: str | None = DEFAULT_ALL_ARRAY_COMPRESSION
    self._all_array_compression_kwargs: dict[str, Any] | None = DEFAULT_ALL_ARRAY_COMPRESSION_KWARGS
    self._default_array_save_base = DEFAULT_DEFAULT_ARRAY_SAVE_BASE
    self._lazy_tree = DEFAULT_LAZY_TREE
    self._warn_on_failed_conversion = DEFAULT_WARN_ON_FAILED_CONVERSION

    self._lock = threading.RLock()

all_array_compression property writable

all_array_compression: Compression

Override the compression type on all binary blocks in the file. Must be one of the following strings, None or a label supported by a asdf.extension.Compressor:

  • '' or None: No compression.

  • zlib: Use zlib compression.

  • bzp2: Use bzip2 compression.

  • lz4: Use lz4 compression.

  • input: Use the same compression as in the file read. If there is no prior file, acts as None

all_array_compression_kwargs property writable

all_array_compression_kwargs: dict[str, Any] | None

Dictionary of keyword arguments provided to the compressor during block compression (or None for no keyword arguments)

all_array_storage property writable

all_array_storage: ArrayStorage

Override the array storage type of all blocks in the file immediately before writing. Must be one of the following strings or None:

  • internal: The default. The array data will be stored in a binary block in the same ASDF file.

  • external: Store the data in a binary block in a separate ASDF file.

  • inline: Store the data as YAML inline in the tree.

array_inline_threshold property writable

array_inline_threshold: int | None

Get the threshold below which arrays are automatically written as inline YAML literals instead of binary blocks. This number is compared to number of elements in the array.

Returns:

Type Description
int or None

Integer threshold, or None to disable automatic selection of the array storage type.

default_array_save_base property writable

default_array_save_base: bool

Option to control if when saving arrays the base array should be saved (so views of the same array will refer to offsets/strides of the same block).

default_version property writable

default_version: str

Get the default ASDF core schemas version used for new files.

Returns:

Type Description
str

extensions property

extensions: list[ExtensionProxy]

Get the list of registered extensions.

Returns:

Type Description
list of asdf.extension.ExtensionProxy

io_block_size property writable

io_block_size: int

Get the block size used when reading and writing files.

Returns:

Type Description
int

Block size, or -1 to use the filesystem’s preferred block size.

lazy_tree property writable

lazy_tree: bool

Get configuration that controls if ASDF tree contents are lazily converted to custom objects or if all custom objects are created when the file is opened. See the lazy_tree argument for asdf.open.

Returns:

Type Description
bool

legacy_fill_schema_defaults property writable

legacy_fill_schema_defaults: bool

Get the configuration that controls filling defaults from schemas for older ASDF core schemas versions. If True, missing default values will be filled from the schema when reading files from ASDF core schemas <= 1.5.0. Later versions of the core schemas do not support removing or filling schema defaults.

Returns:

Type Description
bool

resource_manager property

resource_manager: ResourceManager

Get the asdf.resource.ResourceManager instance. Includes resources from registered resource mappings and any mappings added at runtime.

Returns:

Type Description
`asdf.resource.ResourceManager`

resource_mappings property

resource_mappings: list[ResourceMappingProxy]

Get the list of registered resource mapping instances. Unless overridden by user configuration, this list contains every mapping registered with an entry point.

Returns:

Type Description
list of asdf.resource.ResourceMappingProxy

validate_on_read property writable

validate_on_read: bool

Get configuration that controls schema validation of ASDF files on read.

Returns:

Type Description
bool
Warnings

In a future release the default value will change from True to False. Currently, if a validation error occurs while loading a file and this field hasn’t been manually set then ASDF will emit an asdf.exceptions.AsdfFutureWarning before raising an exception. Manually set the field to either True or False to silence this warning.

warn_on_failed_conversion property writable

warn_on_failed_conversion: bool

Get configuration that controls if errors during conversion are converted to warnings.

Enabling this can be helpful when opening old files that contain tags that are no longer supported.

Returns:

Type Description
bool
Warnings

In a future release the default value will change from False to True. Currently, if a conversion fails and this field hasn’t been set then ASDF will emit an asdf.exceptions.AsdfFutureWarning before raising an exception. Manually set the field to either True or False to silence this warning.

__repr__

__repr__() -> str
Source code in asdf/config.py
def __repr__(self) -> str:
    return (
        "<AsdfConfig\n"
        f"  array_inline_threshold: {self.array_inline_threshold}\n"
        f"  all_array_storage: {self.all_array_storage}\n"
        f"  all_array_compression: {self.all_array_compression}\n"
        f"  all_array_compression_kwargs: {self.all_array_compression_kwargs}\n"
        f"  default_array_save_base: {self.default_array_save_base}\n"
        f"  default_version: {self.default_version}\n"
        f"  io_block_size: {self.io_block_size}\n"
        f"  legacy_fill_schema_defaults: {self.legacy_fill_schema_defaults}\n"
        f"  validate_on_read: {self.validate_on_read}\n"
        f"  lazy_tree: {self.lazy_tree}\n"
        f"  warn_on_failed_conversion: {self.warn_on_failed_conversion}\n"
        ">"
    )

__setattr__

__setattr__(name: str, value: Any) -> None
Source code in asdf/_helpers.py
def __setattr__(self, name: str, value: Any) -> None:
    if hasattr(self, name):
        self._is_set.add(name)

    super().__setattr__(name, value)

add_extension

add_extension(extension: ExtensionLike) -> None

Register a new extension. The new extension will take precedence over all previously registered extensions.

Parameters:

Name Type Description Default
extension Extension
required
Source code in asdf/config.py
def add_extension(self, extension: ExtensionLike) -> None:
    """
    Register a new extension.  The new extension will
    take precedence over all previously registered extensions.

    Parameters
    ----------
    extension : asdf.extension.Extension
    """
    with self._lock:
        extension = ExtensionProxy.maybe_wrap(extension)
        self._extensions = [extension] + [e for e in self.extensions if e != extension]

add_resource_mapping

add_resource_mapping(mapping: Mapping[str, str | bytes]) -> None

Register a new resource mapping. The new mapping will take precedence over all previously registered mappings.

Parameters:

Name Type Description Default
mapping Mapping

Map of str resource URI to bytes content

required
Source code in asdf/config.py
def add_resource_mapping(self, mapping: Mapping[str, str | bytes]) -> None:
    """
    Register a new resource mapping.  The new mapping will
    take precedence over all previously registered mappings.

    Parameters
    ----------
    mapping : collections.abc.Mapping
        Map of `str` resource URI to `bytes` content
    """
    with self._lock:
        mapping = ResourceMappingProxy.maybe_wrap(mapping)

        # Insert at the beginning of the list so that
        # ResourceManager uses the new mapping first.
        resource_mappings = [mapping] + [r for r in self.resource_mappings if r != mapping]
        self._resource_mappings = resource_mappings
        self._resource_manager = None

remove_extension

remove_extension(
    extension: ExtensionLike | str | None = None, *, package: str | None = None
) -> None

Remove a registered extension.

Parameters:

Name Type Description Default
extension Extension or str

An extension instance or URI pattern to remove.

None
package str

Remove only extensions provided by this package. If the extension argument is omitted, then all extensions from this package will be removed.

None
Source code in asdf/config.py
def remove_extension(self, extension: ExtensionLike | str | None = None, *, package: str | None = None) -> None:
    """
    Remove a registered extension.

    Parameters
    ----------
    extension : asdf.extension.Extension or str, optional
        An extension instance or URI pattern to remove.
    package : str, optional
        Remove only extensions provided by this package.  If the ``extension``
        argument is omitted, then all extensions from this package will
        be removed.
    """
    if extension is None and package is None:
        msg = "Must specify at least one of extension or package"
        raise ValueError(msg)

    if extension is not None and not isinstance(extension, str):
        extension = ExtensionProxy.maybe_wrap(extension)

    def _remove_condition(e):
        result = True

        if isinstance(extension, str):
            result = result and util.uri_match(extension, e.extension_uri)
        elif isinstance(extension, ExtensionProxy):
            result = result and e == extension

        if package is not None:
            result = result and e.package_name == package

        return result

    with self._lock:
        self._extensions = [e for e in self.extensions if not _remove_condition(e)]

remove_resource_mapping

remove_resource_mapping(
    mapping: Mapping[str, str | bytes] | None = None, *, package: str | None = None
) -> None

Remove a registered resource mapping.

Parameters:

Name Type Description Default
mapping Mapping

Mapping to remove.

None
package str

Remove only extensions provided by this package. If the mapping argument is omitted, then all mappings from this package will be removed.

None
Source code in asdf/config.py
def remove_resource_mapping(
    self, mapping: Mapping[str, str | bytes] | None = None, *, package: str | None = None
) -> None:
    """
    Remove a registered resource mapping.

    Parameters
    ----------
    mapping : collections.abc.Mapping, optional
        Mapping to remove.
    package : str, optional
        Remove only extensions provided by this package.  If the ``mapping``
        argument is omitted, then all mappings from this package will
        be removed.
    """
    if mapping is None and package is None:
        msg = "Must specify at least one of mapping or package"
        raise ValueError(msg)

    if mapping is not None:
        mapping = ResourceMappingProxy.maybe_wrap(mapping)

    def _remove_condition(m):
        result = True
        if mapping is not None:
            result = result and m == mapping
        if package is not None:
            result = result and m.package_name == package

        return result

    with self._lock:
        self._resource_mappings = [m for m in self.resource_mappings if not _remove_condition(m)]
        self._resource_manager = None

reset_extensions

reset_extensions() -> None

Reset extensions to the default list registered via entry points.

Source code in asdf/config.py
def reset_extensions(self) -> None:
    """
    Reset extensions to the default list registered via entry points.
    """
    with self._lock:
        self._extensions = None

reset_resources

reset_resources() -> None

Reset registered resource mappings to the default list provided as entry points.

Source code in asdf/config.py
def reset_resources(self) -> None:
    """
    Reset registered resource mappings to the default list
    provided as entry points.
    """
    with self._lock:
        self._resource_mappings = None
        self._resource_manager = None

config_context

config_context() -> Generator[AsdfConfig]

Context manager that temporarily overrides asdf configuration. The context yields an asdf.config.AsdfConfig instance that can be modified without affecting code outside of the context.

Source code in asdf/config.py
@contextmanager
def config_context() -> Generator[AsdfConfig]:
    """
    Context manager that temporarily overrides asdf configuration.
    The context yields an `asdf.config.AsdfConfig` instance that can be modified
    without affecting code outside of the context.
    """
    base_config = _global_config if len(_local.config_stack) == 0 else _local.config_stack[-1]

    config = copy.copy(base_config)
    _local.config_stack.append(config)

    try:
        yield config
    finally:
        _local.config_stack.pop()

get_config

get_config() -> AsdfConfig

Get the current config, which may have been altered by one or more surrounding calls to asdf.config_context.

Returns:

Type Description
AsdfConfig
Source code in asdf/config.py
def get_config() -> AsdfConfig:
    """
    Get the current config, which may have been altered by
    one or more surrounding calls to `asdf.config_context`.

    Returns
    -------
    asdf.config.AsdfConfig
    """
    if len(_local.config_stack) == 0:
        return _global_config

    return _local.config_stack[-1]