Python API

Sphinx-Needs provides an open API for other Sphinx-extensions to provide specific need-types, create needs or make usage of the filter possibilities.

The API allows the injection of extra configuration, but does not support manipulation of it (e.g remove need types), to keep the final configuration transparent for the Sphinx project authors.

Configuration

API to get or add specific sphinx needs configuration parameters.

All functions here are available under sphinx_needs.api.

add_dynamic_function(app: Sphinx, function: DynamicFunction, name: str | None = None) None

Registers a new dynamic function for sphinx-needs.

If name is not given, the name to call the function is automatically taken from the provided function. The used name must be unique.

Usage:

from sphinx_needs.api import add_dynamic_function

def my_function(app, need, needs, *args, **kwargs):
    # Do magic here
    return "some data"

add_dynamic_function(app, my_function)

Read Dynamic functions for details about how to use dynamic functions.

Parameters:
  • app – Sphinx application object

  • function – Function to register

  • name – Name of the dynamic function as string

Returns:

None

add_extra_option(app: Sphinx, name: str, *, description: str = 'Added by add_extra_option API', schema: ExtraOptionStringSchemaType | ExtraOptionBooleanSchemaType | ExtraOptionIntegerSchemaType | ExtraOptionNumberSchemaType | ExtraOptionMultiValueSchemaType | None = None, nullable: bool | None = None) None

Adds an extra option to the configuration. This option can then later be used inside needs or add_need.

Same impact as using needs_extra_options manually.

Usage:

from sphinx_needs.api import add_extra_option

add_extra_option(app, 'my_extra_option')
Parameters:
  • app – Sphinx application object

  • name – Name of the extra option

  • description – Description of the extra option

  • schema – Schema definition for the extra option

  • nullable – Whether the field allows unset values.

Returns:

None

add_need_type(app: Sphinx, directive: str, title: str, prefix: str, color: str = '#ffffff', style: str = 'node') None

Adds a new need_type to the configuration.

The given directive must no exist, otherwise NeedsApiConfigException gets raised.

Same impact as using needs_types manually.

Usage:

from sphinx_needs.api import add_need_type

add_need_type(app, 'awesome', 'Awesome', 'AW_', '#000000', 'cloud')
Parameters:
  • app – Sphinx application object

  • directive – Name of the directive, e.g. ‘story’

  • title – Long, human-readable title, e.g. ‘User-Story’

  • prefix – Prefix, if IDs get automatically generated. E.g.: 'US_'

  • color – Hex-color code used in needflow representation. Default: '#ffffff'

  • style – Plantuml-style for needflow representation. Default: ‘node’

Returns:

None

add_warning(app: Sphinx, name: str, function: Callable[[NeedItem, SphinxLoggerAdapter], bool] | None = None, filter_string: str | None = None) None

Registers a warning.

A warning can be based on the result of a given filter_string or an own defined function.

Parameters:
  • app – Sphinx app object

  • name – Name as string for the warning

  • function – function to execute to check the warning

  • filter_string – filter_string to use for the warning

Returns:

None

get_need_types(app: Sphinx) list[str]

Returns a list of directive-names from all configured need_types.

Usage:

from sphinx_needs.api import get_need_types

all_types = get_need_types(app)
Parameters:

app – Sphinx application object

Returns:

list of strings

class DynamicFunction(*args, **kwargs)

A protocol for a sphinx-needs dynamic function.

__call__(app: Sphinx, need: NeedItem | NeedPartItem | None, needs: NeedsView | NeedsMutable, *args: Any, **kwargs: Any) str | int | float | list[str] | list[int] | list[float] | None

Call self as a function.

Need

class DefaultContextData
add_external_need(app: Sphinx, need_type: str, title: str | None = None, id: str | None = None, need_source: NeedItemSourceProtocol | None = None, external_url: str | None = None, external_css: str = 'external_link', content: str = '', status: str | None = None, tags: str | list[str] | None = None, constraints: str | None = None, **kwargs: Any) list[Node]

Adds an external need from an external source. This need does not have any representation in the current documentation project. However, it can be linked and filtered. It’s reference will open a link to another, external sphinx documentation project.

It returns an empty list (without any nodes), so no nodes will be added to the document.

Parameters:
  • app – Sphinx application object.

  • need_type – Name of the need type to create.

  • title – String as title.

  • id – ID as string. If not given, a id will get generated.

  • external_url – URL as string, which shall be used as link to the original need source

  • content – Content as single string.

  • status – Status as string.

  • tags – A list of tags, or a comma separated string.

  • constraints – constraints as single, comma separated string.

  • external_css – CSS class name as string, which is set for the <a> tag.

Raises:

InvalidNeedException – If the need could not be added due to a validation issue.

add_need(app: Sphinx, state: None | RSTState = None, docname: None | str = None, lineno: None | int = None, need_type: str = '', title: str = '', *, need_source: NeedItemSourceProtocol | None = None, id: str | None = None, content: str | StringList = '', lineno_content: None | int = None, doctype: None | str = None, status: str | None = None, tags: None | str | list[str] = None, constraints: None | str | list[str] = None, parts: dict[str, NeedsPartType] | None = None, arch: dict[str, str] | None = None, signature: None | str = None, sections: list[str] | None = None, jinja_content: bool | None = None, hide: None | bool | str = None, collapse: None | bool | str = None, style: None | str = None, layout: None | str = None, template: None | str = None, pre_template: str | None = None, post_template: str | None = None, is_import: bool = False, is_external: bool = False, external_url: str | None = None, external_css: str = 'external_link', full_title: str | None = None, allow_type_coercion: bool = True, **kwargs: Any) list[Node]

Creates a new need and returns its node.

add_need allows to create needs programmatically and use its returned node to be integrated in any docutils based structure.

kwargs can contain options defined in needs_extra_options and needs_extra_links. If an entry is found in kwargs, which is not specified in the configuration or registered e.g. via add_extra_option, an exception is raised.

If is_external is set to True, no node will be created. Instead, the need is referencing an external url. Used mostly for needs_external_needs to integrate and reference needs from external documentation.

Raises:

InvalidNeedException – If the need could not be added due to a validation issue.

If the need is within the current project, i.e. not an external need, the following parameters are used to help provide source mapped warnings and errors:

Parameters:
  • docname – documentation identifier, for the referencing document.

  • lineno – line number of the top of the directive (1-indexed).

  • lineno_content – line number of the content start of the directive (1-indexed).

Otherwise, the following parameters are used:

Parameters:
  • is_external – Is true, no node is created and need is referencing external url

  • external_url – URL as string, which is used as target if is_external is True

  • external_css – CSS class name as string, which is set for the <a> tag.

Additional parameters:

Parameters:
  • app – Sphinx application object.

  • state – Current state object.

  • need_type – Name of the need type to create.

  • title – String as title.

  • full_title – This is given, if an auto-generated title was trimmed. It is used to auto-generate the ID, if required.

  • id – ID as string. If not given, an id will get generated.

  • content – Content of the need, either as a str or a StringList (a string with mapping to the source text).

  • status – Status as string.

  • tags – A list of tags, or a comma separated string.

  • constraints – Constraints as single, comma separated, string.

  • constraints_passed – Contains bool describing if all constraints have passed

  • hide – If True then the need is not rendered. None means that the value can be overriden by global defaults, else it is set to False.

  • collapse – If True, then hide the meta-data information of the need. None means that the value can be overriden by global defaults, else it is set to False.

  • style – String value of class attribute of node.

  • layout – String value of layout definition to use

  • template – Template name to use for the content of this need

  • pre_template – Template name to use for content added before need

  • post_template – Template name to use for the content added after need

  • allow_type_coercion – If true, values will be coerced to the expected type where possible.

Returns:

list of nodes

del_need(app: Sphinx, need_id: str) None

Deletes an existing need.

Parameters:
  • app – Sphinx application object.

  • need_id – Sphinx need id.

generate_need(needs_config: NeedsSphinxConfig, needs_schema: FieldsSchema, need_type: str, title: str, *, need_source: NeedItemSourceProtocol | None = None, docname: None | str = None, lineno: None | int = None, id: str | None = None, doctype: str = '.rst', content: str = '', lineno_content: None | int = None, status: str | None = None, tags: None | str | list[str] = None, constraints: None | str | list[str] = None, parts: dict[str, NeedsPartType] | None = None, arch: dict[str, str] | None = None, signature: None | str = None, sections: Sequence[str] | None = None, jinja_content: bool | None = None, hide: None | bool | str = None, collapse: None | bool | str = None, style: None | str = None, layout: None | str = None, template_root: Path | None = None, template: None | str = None, pre_template: str | None = None, post_template: str | None = None, is_import: bool = False, is_external: bool = False, external_url: str | None = None, external_css: str = 'external_link', full_title: str | None = None, allow_type_coercion: bool = True, **kwargs: Any) NeedItem

Creates a validated need data entry, without adding it to the project.

Important

This function does not parse or analyse the content, and so will not auto-populate the parts or arch fields of the need from the content.

It will also not validate that the ID is not already in use within the project.

Raises:

InvalidNeedException – If the data fails any validation issue.

kwargs can contain options defined in needs_extra_options and needs_extra_links. If an entry is found in kwargs, which is not specified in the configuration or registered e.g. via add_extra_option, an exception is raised.

If the need is within the current project, i.e. not an external need, the following parameters are used to help provide source mapped warnings and errors:

Parameters:
  • docname – documentation identifier, for the referencing document.

  • lineno – line number of the top of the directive (1-indexed).

  • lineno_content – line number of the content start of the directive (1-indexed).

Otherwise, the following parameters are used:

Parameters:
  • is_external – Is true, no node is created and need is referencing external url

  • external_url – URL as string, which is used as target if is_external is True

  • external_css – CSS class name as string, which is set for the <a> tag.

Additional parameters:

Parameters:
  • app – Sphinx application object.

  • state – Current state object.

  • need_type – Name of the need type to create.

  • title – String as title.

  • full_title – This is given, if an auto-generated title was trimmed. It is used to auto-generate the ID, if required.

  • id – ID as string. If not given, an id will get generated.

  • content – Content of the need

  • status – Status as string.

  • tags – A list of tags, or a comma separated string.

  • constraints – Constraint names as comma separated string or list of strings

  • constraints_passed – Contains bool describing if all constraints have passed

  • hide – If True then the need is not rendered. None means that the value can be overriden by global defaults, else it is set to False.

  • collapse – If True, then hide the meta-data information of the need. None means that the value can be overriden by global defaults, else it is set to False.

  • style – String value of class attribute of node.

  • layout – String value of layout definition to use

  • template_root – Root path for template files, only required if the template_path config is relative.

  • template – Template name to use for the content of this need

  • pre_template – Template name to use for content added before need

  • post_template – Template name to use for the content added after need

  • allow_type_coercion – If true, values will be coerced to the expected type where possible.

get_needs_view(app: Sphinx) NeedsView

Return a read-only view of all resolved needs.

Important

this should only be called within the write phase, after the needs have been fully collected. If not already done, this will ensure all needs are resolved (e.g. back links have been computed etc), and then lock the data to prevent further modification.

Exceptions

exception FunctionParsingException(message: str, name: str | None)

Called if parsing of given function string has not worked

exception InvalidNeedException(type_: Literal['invalid_kwargs', 'invalid_type', 'invalid_extra_option', 'invalid_link_option', 'missing_id', 'invalid_id', 'duplicate_id', 'invalid_title', 'invalid_status', 'invalid_tags', 'invalid_layout', 'invalid_style', 'invalid_value', 'invalid_constraints', 'invalid_jinja_content', 'invalid_template', 'global_option', 'failed_init'], message: str)

Raised when a need could not be created/added, due to a validation issue.

exception NeedsApiConfigException

A configuration changes collides with the already provided configuration by the user.

Example: An extension wants to add an already existing needs_type.

exception NeedsApiConfigWarning
exception NeedsConfigException
exception NeedsConstraintFailed
exception NeedsInvalidException
exception NeedsInvalidFilter
exception VariantParsingException(message: str)

Called if parsing of given function string has not worked

Data

class NeedConstraintResults(constraints: Mapping[str, tuple[tuple[str, bool, str | None], ...]])

A class representing the results of constraints on a need item.

all_passed() bool

Return True if all constraints passed, False otherwise.

first_error() str | None

Return the first error message found in the constraint results, or None if none found.

to_dict() dict[str, dict[str, bool]]

Convert the constraint results to a dictionary.

class NeedItem(*, source: NeedItemSourceProtocol | None, content: NeedsContent, core: NeedsInfoType, extras: dict[str, AllowedTypes | None], links: dict[str, list[str]], backlinks: dict[str, list[str]] | None = None, parts: Sequence[NeedPartData] = (), modifications: Sequence[NeedModification] = (), constraint_results: None | NeedConstraintResults = None, dynamic_fields: dict[str, FieldFunctionArray | LinksFunctionArray] | None = None, _validate: bool = True)

A class representing a single need item.

Add a backlink to the need.

add_modification(modification: NeedModification) None

Add a modification to the need item.

Parameters:

modification – The modification to add.

property constraint_results: None | NeedConstraintResults

Return the constraint results of the need item.

property content: NeedsContent

Return the content of the need item.

copy() NeedItem

Return a copy of the NeedItem.

get(key: str, default: Any = None) Any

Get an item by key with a default value.

Get backlink references by link_type key.

Raises:

KeyError – If the link_type is not a backlink type.

get_extra(key: str) AllowedTypes | None

Get an extra by key.

Raises:

KeyError – If the key is not an extra.

Get link references by link_type key.

Raises:

KeyError – If the link_type is not a link type.

get_part(part_id: str) NeedPartData | None

Get a part by its ID.

get_part_item(part_id: str) NeedPartItem | None

Get a part, merged with its parent need, by its ID.

property has_dynamic_fields: bool

Return True if the need item has dynamic fields, False otherwise.

property id: str

Return the ID of the need item.

items() Iterable[tuple[str, Any]]

Return the items of the need item.

Yield all backlinks as (link_type, references) pairs.

iter_core_items() Iterable[tuple[str, Any]]

Return the core items of the need item.

iter_extra_items() Iterable[tuple[str, AllowedTypes | None]]

Yield all extras as key-value pairs.

iter_extra_keys() Iterable[str]

Yield all extra keys.

Yield all links as (link_type, references) pairs.

Yield all link_type keys.

iter_part_items() Iterable[NeedPartItem]

Yield all parts, merged with the parent part, from a need.

keys() Iterable[str]

Return the keys of the need item.

property modifications: tuple[NeedModification, ...]

Return the modifications of the need item.

property parts: Iterable[NeedPartData]

Return the parts of the need item.

Reset all backlinks to empty lists (including parts).

set_constraint_results(constraint_results: None | NeedConstraintResults, *, _recompute: bool = True) None

Set the constraint results for the need item.

Parameters:

constraint_results – The constraint results to set.

set_content(content: NeedsContent) None

Replace the content of the need item.

Parameters:

new_content – The new content to set.

set_parts(parts: Sequence[NeedPartData], *, _recompute: bool = True) None

Set the parts of the need item.

Parameters:

parts – The parts to set.

property source: NeedItemSourceProtocol

Return the source of the need item.

values() Iterable[Any]

Return the values of the need item.

class NeedItemSourceProtocol(*args, **kwargs)

Protocol for need item source types.

property dict_repr: NeedsSourceInfoType

Return a dictionary representation of the source.

class NeedModification(*, docname: str | None = None, lineno: int | None = None)

A class representing a modification to a need item, by a needextend directive.

class NeedPartData(*, id: str, content: str, backlinks: dict[str, list[str]] = <factory>)

A class representing a part of a need, which is generally derived from :np: role within the parent need.

class NeedPartItem(need: NeedItem, part_id: str)

A class representing a part of a need, which is a sub-need, merged with the parent need.

Any data coming from the part will override the data from the parent need.

Note this is a read-only view into a need part. It does not allow modification of the underlying data.

copy() NeedPartItem

Return a copy of the NeedPartItem.

copy_for_needtable() NeedPartItem

Return a copy of the NeedPartItem with specific fields for needtable.

get(key: str, default: Any = None) Any

Get an item by key with a default value.

Get backlink references by link_type key.

Raises:

KeyError – If the link_type is not a backlink type.

get_extra(key: str) str

Get an extra by key.

Raises:

KeyError – If the key is not an extra.

Get link references by link_type key.

Raises:

KeyError – If the link_type is not a link type.

items() Iterable[tuple[str, Any]]

Return the items of the need item.

Yield all backlinks as (link_type, references) pairs.

iter_extra_items() Iterable[tuple[str, str]]

Yield all extras as key-value pairs.

iter_extra_keys() Iterable[str]

Yield all extra keys.

Yield all links as (link_type, references) pairs.

Yield all link_type keys.

keys() Iterable[str]

Return the keys of the need item.

property part_id: str

Return the part ID.

values() Iterable[Any]

Return the values of the need item.

class NeedsContent(*, doctype: str, content: str, pre_content: str | None = None, post_content: str | None = None, jinja_content: bool = False, template: str | None = None, pre_template: str | None = None, post_template: str | None = None)

A class representing the content of a need item.

Module to control access to sphinx-needs data, which is stored in the Sphinx environment.

class NeedsInfoComputedType

Data for a single need, that can be computed from existing data.

These fields are used for convenience in filters.

constraints_error: None | str

An error message set if any constraint failed, and error_message field is set in config.

constraints_passed: None | bool

True if all constraints passed, False if any failed, None if not yet checked.

constraints_results: None | Mapping[str, Mapping[str, bool]]

Mapping of constraint name, to check name, to result, None if not yet checked.

id_complete: str

<parent ID>.<self ID>, or <self ID> if not a part.

id_parent: str

<parent ID>, or <self ID> if not a part.

is_modified: bool

Whether the need was modified by needextend.

modifications: int

Number of modifications by needextend.

parent_need: None | str

Simply the first parent id.

parts: Mapping[str, NeedsPartType]

Mapping of parts, a.k.a. sub-needs, IDs to data that overrides the need’s data

section_name: None | str

Simply the first section.

class NeedsInfoType

Data for a single need.

arch: Mapping[str, str]

Mapping of uml key to uml content.

collapse: bool

Hide the meta-data information of the need.

constraints: list[str]

List of constraint names, which are defined for this need.

external_css: str

CSS class name, added to the external reference.

True if any links reference need ids that are not found in the need list.

True if any links reference need ids that are not found in the need list, and the link type does not allow dead links.

hide: bool

If true, the need is not rendered.

id: str

ID of the data.

layout: None | str

Key of the layout, which is used to render the need.

signature: None | str

Derived from a docutils desc_name node.

style: None | str

Comma-separated list of CSS classes (all appended by needs_style_).

title: str

Title of the need.

type: str

Type of the need.

type_color: str

Hexadecimal color code of the type.

class NeedsMutable

A mutable view of the needs, before resolution

alias of dict[str, NeedItem]

class NeedsPartType

Data for a single need part.

content: str

Content of the part.

id: str

ID of the part

class NeedsSourceInfoType

Data for the source of a single need.

docname: str | None

Name of the document where the need is defined (None if external).

external_url: None | str

URL of the need, if it is an external need.

is_external: bool

If true, no node is created and need is referencing external url.

is_import: bool

If true, the need was derived from an import.

lineno: int | None

Line number where the need is defined (None if external).

lineno_content: int | None

Line number on which the need content starts (None if external).

Views

These views are returned by certain functions, and injected into filters, but should not be instantiated directly.

class NeedsAndPartsListView(*, _indexes: _LazyIndexes, _selected_ids: dict[tuple[str, str | None], None] | None)

A read-only view of needs and parts, after resolution (e.g. back links have been computed etc)

The parts are created by creating a copy of the need for each item in parts, and then overwriting a subset of fields with the values from the part.

__iter__() Iterator[NeedItem | NeedPartItem]

Iterate over the needs and parts in the view.

__len__() int
filter_has_tag(values: list[str]) NeedsAndPartsListView

Create new view with only needs/parts that have at least one of these values in the tags field list.

filter_ids(values: Iterable[str]) NeedsAndPartsListView

Create new view with needs/parts filtered by the id field.

filter_is_external(value: bool) NeedsAndPartsListView

Create new view with only needs/parts where is_external field is true/false.

filter_statuses(values: list[str]) NeedsAndPartsListView

Create new view with only needs/parts that have certain status field values.

filter_types(values: list[str], or_type_names: bool = False) NeedsAndPartsListView

Create new view with only needs/parts that have certain type field values.

Parameters:
  • values – List of types to filter by.

  • or_type_names – If True, filter by both type and type_name field

get_need(id: str, part_id: str | None = None) NeedItem | NeedPartItem | None

Get a need by id, or return None if it does not exist.

If part_id is provided, return the part of the need with that id, or None if it does not exist.

class NeedsView(*, _indexes: _LazyIndexes, _selected_ids: dict[str, None] | None)

A read-only view of needs, mapping need ids to need data, with “fast” filtering methods.

The needs are read-only and fully resolved (e.g. dynamic values and back links have been computed etc)

__getitem__(key: str) NeedItem
__iter__() Iterator[str]
__len__() int
filter_has_tag(values: list[str]) NeedsView

Create new view with only needs that have at least one of these values in the tags field list.

filter_ids(values: Iterable[str]) NeedsView

Create new view with needs filtered by the id field.

filter_is_external(value: bool) NeedsView

Create new view with only needs where is_external field is true/false.

filter_statuses(values: list[str]) NeedsView

Create new view with only needs that have certain status field values.

filter_types(values: list[str], or_type_names: bool = False) NeedsView

Create new view with only needs that have certain type field values.

Parameters:
  • values – List of types to filter by.

  • or_type_names – If True, filter by both type and type_name field

to_list_with_parts() NeedsAndPartsListView

Create a new view with needs and parts.

Schema

AllowedTypes: TypeAlias = str | bool | int | float | list[str] | list[bool] | list[int] | list[float]

Type alias for all allowed types in need fields.

This includes scalar types (str, bool, int, float) and their corresponding list types.

class FieldFunctionArray(value: 'tuple[DynamicFunctionParsed | VariantFunctionParsed | str, ...] | tuple[DynamicFunctionParsed | VariantFunctionParsed | bool, ...] | tuple[DynamicFunctionParsed | VariantFunctionParsed | int, ...] | tuple[DynamicFunctionParsed | VariantFunctionParsed | float, ...]')
class FieldLiteralValue(value: 'AllowedTypes')
class FieldSchema(*, name: str, description: str = '', schema: ExtraOptionStringSchemaType | ExtraOptionBooleanSchemaType | ExtraOptionIntegerSchemaType | ExtraOptionNumberSchemaType | ExtraOptionMultiValueSchemaType, nullable: bool = False, directive_option: bool = False, allow_dynamic_functions: bool = False, allow_variant_functions: bool = False, allow_defaults: bool = False, allow_extend: bool = False, predicate_defaults: tuple[tuple[str, FieldLiteralValue | FieldFunctionArray], ...] = (), default: None | FieldLiteralValue | FieldFunctionArray = None)

Schema for a single field.

Raises:

ValueError – if any of the parameters are invalid

convert_directive_option(value: str) FieldLiteralValue | FieldFunctionArray

Convert a string to the correct type for this field.

Raises:
convert_or_type_check(value: Any, *, allow_coercion: bool) None | FieldLiteralValue | FieldFunctionArray

Convert a value to the correct type for this field, or check if it is of the correct type.

Parameters:
  • value – The value to convert or check.

  • allow_coercion – Whether to allow coercion of string values to the correct type. This will also allow dynamic and variant functions if the field allows them.

Returns:

True if the value is of the correct type, False otherwise.

Raises:
default: None | FieldLiteralValue | FieldFunctionArray

The default value for this field.

Used if the field has not been specifically set, and no predicate matches.

json_schema() dict[str, Any]

Return a JSON schema representation of this field.

predicate_defaults: tuple[tuple[str, FieldLiteralValue | FieldFunctionArray], ...]

List of (need filter, value) pairs for default predicate values.

Used if the field has not been specifically set.

The value from the first matching filter will be used, if any.

type_check(value: Any) bool

Check if a value is of the correct type for this field.

type_check_item(value: Any) bool

Check if a value is of the correct item type for this field.

For ‘array’ field types, this checks against the item_type. For other fields, returns False.

class FieldsSchema

A schema for the fields of a single need.

add_core_field(field: FieldSchema) None

Add a core field to the schema.

Raises:

ValueError – if a field with the same name already exists

add_extra_field(field: FieldSchema) None

Add an extra field to the schema.

Raises:

ValueError – if a field with the same name already exists

Add a link field to the schema.

Raises:

ValueError – if a field with the same name already exists

get_any_field(name: str) FieldSchema | LinkSchema | None

Get a field by name.

get_core_field(name: str) FieldSchema | None

Get a core field by name.

get_extra_field(name: str) FieldSchema | None

Get an extra field by name.

Get a link field by name.

iter_all_fields() Iterable[FieldSchema | LinkSchema]

Iterate over all fields in the schema.

iter_core_field_names() Iterable[str]

Iterate over all core field names in the schema.

iter_core_fields() Iterable[FieldSchema]

Iterate over all core fields in the schema.

iter_extra_field_names() Iterable[str]

Iterate over all extra field names in the schema.

iter_extra_fields() Iterable[FieldSchema]

Iterate over all extra fields in the schema.

Iterate over all link field names in the schema.

Iterate over all link fields in the schema.

class LinkSchema(*, name: str, description: str = '', directive_option: bool = False, allow_extend: bool = False, allow_dynamic_functions: bool = False, allow_variant_functions: bool = False, allow_defaults: bool = False, predicate_defaults: tuple[tuple[str, LinksLiteralValue | LinksFunctionArray], ...] = (), default: None | LinksLiteralValue | LinksFunctionArray = None)

Schema for a single link field.

convert_directive_option(value: str) LinksLiteralValue | LinksFunctionArray

Convert a string to the correct type for this field.

Raises:
convert_or_type_check(value: Any, *, allow_coercion: bool) LinksLiteralValue | LinksFunctionArray

Convert a value to the correct type for this field, or check if it is of the correct type.

Parameters:
  • value – The value to convert or check.

  • allow_coercion – Whether to allow coercion of string values to the correct type. This will also allow dynamic and variant functions if the field allows them.

Returns:

True if the value is of the correct type, False otherwise.

Raises:
default: None | LinksLiteralValue | LinksFunctionArray

The default value for this field.

Used if the field has not been specifically set, and no predicate matches.

json_schema() dict[str, Any]

Return a JSON schema representation of this field.

predicate_defaults: tuple[tuple[str, LinksLiteralValue | LinksFunctionArray], ...]

List of (need filter, value) pairs for default predicate values.

Used if the field has not been specifically set.

The value from the first matching filter will be used, if any.

type_check(value: Any) bool

Check if a value is of the correct type for this field.

type_check_item(value: Any) bool

Check if a value is of the correct item type for this field.

For ‘array’ fields, this checks the type of the array items. For other fields, this checks the type of the field itself.

class LinksFunctionArray(value: 'tuple[str | DynamicFunctionParsed | VariantFunctionParsed, ...]')
class LinksLiteralValue(value: 'list[str]')

Types and violations for schema validation.

There are 3 places the types are used: 1. In the extra option and extra links definition. 2. For the JSON schema coming from schema_definitions and schema_definitions_from_json configs. 3. For runtime type checking of the loaded JSON schema config.

All below types have the field ‘type’ set as required field. For case 1. this is important, as it is the primar type information source and users have to provide it. For 2. and 3. it is not required. If it is not given, it is injected before the type check occurs. If it is given, the types have to match what is provided in 1.

class ExtraOptionBooleanSchemaType

Boolean extra option schema.

A predefined set of truthy/falsy strings are accepted: - truthy = {“true”, “yes”, “y”, “on”, “1”} - falsy = {“false”, “no”, “n”, “off”, “0”}

For fixed values, the const field can be used. enum is not supported as const is functionally equivalent and less verbose.

const: NotRequired[bool]

A constant value that the integer must match.

type: Literal['boolean']

Extra option boolean type.

class ExtraOptionIntegerSchemaType

Integer extra option schema.

const: NotRequired[int]

A constant value that the integer must match.

enum: NotRequired[list[int]]

A list of allowed values.

exclusiveMaximum: NotRequired[int]

Exclusive maximum value.

exclusiveMinimum: NotRequired[int]

Exclusive minimum value.

maximum: NotRequired[int]

Maximum value.

minimum: NotRequired[int]

Minimum value.

multipleOf: NotRequired[int]

Restriction to multiple of a given integer, must be positive.

type: Literal['integer']

Extra option integer type.

class ExtraOptionMultiValueSchemaType

Multi value extra option such as a list of strings, integers, numbers, or booleans.

Current SN use case are tags.

contains: NotRequired[ExtraOptionStringSchemaType | ExtraOptionBooleanSchemaType | ExtraOptionIntegerSchemaType | ExtraOptionNumberSchemaType]

Schema constraints for some items.

maxContains: NotRequired[int]

Maximum number of contains items in the array.

maxItems: NotRequired[int]

Maximum number of items in the array.

minContains: NotRequired[int]

Minimum number of contains items in the array.

minItems: NotRequired[int]

Minimum number of items in the array.

type: Literal['array']

Multi value extra option such as a list of strings, integers, numbers, or booleans.

uniqueItems: NotRequired[bool]

Whether all items in the array must be unique.

class ExtraOptionNumberSchemaType

Float extra option schema.

Python reads in JSON numbers as floats. The jsonschema library handles precision issues with floats using a tolerance-based approach.

const: NotRequired[float]

A constant value that the number must match.

enum: NotRequired[list[float]]

A list of allowed values.

exclusiveMaximum: NotRequired[float]

Exclusive maximum value.

exclusiveMinimum: NotRequired[float]

Exclusive minimum value.

maximum: NotRequired[float]

Maximum value.

minimum: NotRequired[float]

Minimum value.

multipleOf: NotRequired[float]

Restriction to multiple of a given number, must be positive.

type: Literal['number']

Extra option integer type.

class ExtraOptionStringSchemaType

String extra option schema.

const: NotRequired[str]

A constant value that the string must match.

enum: NotRequired[list[str]]

A list of allowed values for the string.

format: NotRequired[Literal['date-time', 'date', 'time', 'duration', 'email', 'uri', 'uuid']]

A format string to validate against, e.g. ‘date-time’.

maxLength: NotRequired[int]

Maximum length of the string.

minLength: NotRequired[int]

Minimum length of the string.

pattern: NotRequired[str]

A regex pattern to validate against.

type: Literal['string']

Extra option string type.