Filtering needs

The filtering of needs and need parts is supported consistently across numerous directives and roles, either by using filter options or by using a filter string.

Filter options

The following filter options are supported by directives:

On the two chart directives the options behave a little differently, because a chart evaluates one filter per content line rather than one filter per directive: there they select the needs each line is counted over, rather than the needs that are shown. See common filters and common filters.

Related to the used directive and its representation, the filter options create a list of needs, which match the filters for status, tags, types and filter.

For :status:, :tags: and :types: values are separated by “;”. :filter: gets evaluated.

The logic, if a need belongs to the final result list, is as followed:

status = (open OR in_progress) AND tags = (user OR login) AND types = (req OR spec) AND filter is true

status

Use the status option to filter needs by their status.

You can easily filter for multiple statuses by separating them by “;”. Example: open; in progress; reopen.

Show example

Example 1

.. needlist::
   :status: open
   :show_status:
R_2A9D0: Requirement A (open)
S_01A67: Specification B (open)

tags

tags allows to filter needs by one or multiple tags.

To search for multiple tags, simply separate them by using “;”.

Show example

Example 2

.. needlist::
   :tags: main_example
   :show_tags:

No needs passed the filters

types

For :types: the type itself or the human-readable type-title can be used as filter value.

Show example

Example 3

.. needtable::
   :types: test

ID

Title

Status

Outgoing

copy_3

test of specification and requirement

copy_4

test of current_need value

EXTRA_TEST_001

Test of requirements

LFM_TEST_1

Session tests

NEED-D

Recalculate hash and compare

T_0F2B7

Level 4

T_5CCAA

Test 1

T_C3893

Test for XY

implemented

T_EA5AF

Sub-Need on level 3

test_001

test a requirement

test_arch_001

Test Arch

test_flow_001

A test case

sort_by

Sorts the result list. Allowed values are status or any alphanumerical property.

A need whose value is unset (None) comes first, whatever the field’s type, as one with an empty string does. The other values are grouped, so that values of different types are never compared: booleans, then numbers, then text. Text is compared as it is (so "Z" comes before "a", unlike a needtable’s sort), a list as its values joined with ", ", and any other value as its text. Needs with equal values are ordered by id.

Changed in version 9.1.0: An unset value used to be compared as an empty string, which stopped the build beside a number; a list was compared item by item, and equal values kept the needs’ own order.

Show example

Example 4

.. needtable::
   :sort_by: id
   :status: open

ID

Title

Status

Outgoing

copy_1

copy-example

open

copy_2

copy-example implementation

open

df_1

my test requirement

open

EX_CARD_PROFILE

A specification with a picture

open

EX_CARD_SUMMARY

A requirement summarised on a card

open

EX_CLEAN

CLEAN layout

open

EX_CLEAN_L

CLEAN_L layout

open

EX_CLEAN_LP

CLEAN_LP layout

open

EX_CLEAN_R

CLEAN_R layout

open

EX_CLEAN_RP

CLEAN_RP layout

open

EX_COMPLETE

COMPLETE layout

open

EX_DEBUG

DEBUG layout

open

EX_FOCUS

FOCUS layout

open

EX_FOCUS_F

FOCUS_F layout

open

EX_FOCUS_L

FOCUS_L layout

open

EX_FOCUS_R

FOCUS_R layout

open

EX_REQ_1

A normal requirement

open

EX_REQ_2

A more complex and highlighted requirement

open

EX_REQ_3

A focused requirement

open

EX_REQ_4

A custom requirement with picture

open

EX_REQ_5

A requirement with a permalink

open

EX_ROW_2

Not implemented spec

open

EXAMPLE_1035

Error when building multiple latex documents

open

EXAMPLE_808

Duplicate labels in `.tex` output

open

extend_test_001

needextend Example 1

open

extend_test_002

needextend Example 2

open

extend_test_003

needextend Example 3

open

extend_test_004

needextend Example 4

open

extend_test_005

needextend Example 5

open

extend_test_006

needextend Example 6

open

ID123

User needs to login

open

IMAGE_EXAMPLE

My test spec

open

JINJAID125

Nested Spec Need

open

JINJAID126

First Spec Need

open

LFF_REQ_1

Open requirement

open

→ LFF_REQ_1.p1

→ open part

open

LFF_REQ_2

Another open requirement

open

LFF_SPEC_1

Collector of open needs

open

my_car_1

Car must be awesome

open

→ my_car_1.1

→ A top speed of 300 km/h

open

→ my_car_1.2

→ An acceleration of 200 m/s² or much much more

open

→ my_car_1.awesome_3

→ a turbo button

open

R_2A9D0

Requirement A

open

R_F4722

My first requirement

open

roles_req_1

Sliced Bread

open

S_01A67

Specification B

open

S_B4B62

Sub-Need on level 2 with status option set

open

SP_INT

Interfaces

open

STYLE_006

My automatically styled requirement

open

STYLE_EX_SERVICE

Order service

open

T_003

Unit test 3

open

T_004

Unit test 4

open

TEMPL_SPEC

My specification

open

xyz_123

My requirement with custom options

open

filter

The filter option allows the definition of a complex query string, which gets evaluated via eval() in Python. Please see Filter string for more details.

Filter string

The usage of a filter string is supported/required by:

The filter string must be a valid Python expression:

Example 5

:need_count:`type=='spec' and status != 'open'`

35

The filter of a needtable, needlist, needflow, needgantt, needpie or needbar, and of need_count, is evaluated on every need and, where needs_views_include_parts is true, on every need part, so a part the filter matches is listed, drawn or counted as an item of its own (a needflow draws a part only with its need). A needtable with show_parts lists it once: under its need when its need is a row, and on a row of its own when its need is not. Unset, the value is true in 9.x and false from 10.0: from 10.0 a view’s filter selects needs alone, and only a needtable and a needflow show parts, each with :show_parts: (a needtable those of the needs it lists, a needflow every part of each need it draws). links_from_filter, links_from_match and a derived links rule test the parts too where they are given include_parts, whatever the value says.

A need part answers its own id (the part’s id), id_complete (NEED.part), id_parent (its need’s id), is_part (true) and is_need (false), its text as both content and title, no outgoing links (every link type is empty), its own back links (<link type>_back, the links that name the part), and no parent_need and no parts. Every other name is its need’s: its type, status, tags and fields. So a filter can select parts by their need’s values; one meant for the parts of particular needs names them by id_parent, such as is_part and id_parent == "REQ_1".

The following filter counts the need parts of the needs tagged car, where needs_views_include_parts is true, as in this documentation:

Example 6

:need_count:`is_part and 'car' in tags`

3

Inside a filter string all the fields of NeedsInfoType can be used.

Note

If extra fields were specified using needs_fields then those will be available for use in filter expressions as well.

Finally, the following are available:

  • search, as Python function for performing searches with a regular expression

  • needs as NeedsAndPartsListView object, which contains what the filter is tested on: all needs, and their need parts where the filter tests them.

A filter is read for its truth: if your expression is valid and its value is true by Python’s rules, whatever its type, the related need is added to the filter result list – an empty string, an empty list, 0 and None are false, so tags selects the needs that have tags. If it is invalid or its value is false, the related need is not taken into account for the current filter. Leading spaces and tabs are read past, as Python’s eval reads them past, wherever the string is written: " status == 'open'" in needs_warnings or needs_builder_filter selects what "status == 'open'" does. A derived field’s where and test are the exception: a declared rule, which must parse as written, so a padded one is refused (needs.derive_invalid).

A filter that is a constant alone says nothing about a need, as its value is the same on every need: a literal (a string, bytes, a number with one sign or none, None or ...), a tuple, list, set or dict display that unpacks nothing, whatever it holds ([1], {1}, {}, and so the trailing-comma typo status == 'open',), a generator expression ((t for t in tags), which is true whatever it would yield), or an f-string with no placeholder, parenthesised or not, after any leading spaces and tabs. True and False are the exception: True selects every need, and False none. --5 and -True are arithmetic, and a display that unpacks ([*tags]), a list, set or dict comprehension or an f-string with a placeholder is read by its truth, as is a constant inside a larger filter (True and owner).

The directives and roles that list or count needs – needlist, needtable and the other views, need_count, a content line of needpie or needbar, needextend – and needs_warnings, needs_builder_filter, the filter() of needuml and the dynamic function copy(filter=...) refuse a constant before it is evaluated, with one needs.filter warning, and select nothing. needimport, a predicate of needs_fields, links_from_filter and links_from_match refuse it the same way, with the warning they give for a filter that fails. Anywhere else, a constant fails the way a filter that cannot be evaluated fails there.

Show example

Example 7: filter option

needs:

.. req:: Requirement A
   :tags: A; filter_example
   :status: open
   :hide:

.. req:: Requirement B
   :tags: B; filter_example
   :status: closed
   :hide:

.. spec:: Specification A
   :tags: A; filter_example
   :status: closed
   :hide:

.. spec:: Specification B
   :tags: B; filter_example
   :status: open
   :hide:

.. test:: Test 1
   :tags: filter_example
   :hide:

.. needlist::
   :filter: "filter_example" in tags and (("B" in tags or ("spec" == type and "closed" == status)) or "test" == type)

needs:

R_22EB2: Requirement B
S_D70B0: Specification A
S_01A67: Specification B
T_5CCAA: Test 1

Using variant data (var)

Added in version 8.2.0.

If needs_variant_data or needs_variant_data_file is configured, a var namespace is available in filter expressions, providing dot-access to nested structured data.

This is useful for switching build outputs based on external configuration (CPU architecture, debug/release mode, feature flags, etc.) without polluting the need field namespace.

The dot-access syntax mirrors Jinja2 template syntax, making it familiar to Sphinx users.

Examples:

.. needtable::
   :filter: var.cpu == "arm"

.. needlist::
   :filter: var.build.debug == True and var.build.optimization > 1

.. needtable::
   :filter: "feature_a" in var.build.features

Accessing a key that doesn’t exist raises an error, which helps catch typos:

.. needlist::
   :filter: var.typo == "x"
   .. this will raise AttributeError: Unknown variant key: var.typo

See needs_variant_data for configuration details and allowed data shapes.

Filtering for needs on the current page

Added in version 5.0.0.

Additionally, to common Filter string variables, the c.this_doc() function is for most directives, to filter for needs only in the same document as the directive.

Example 8

.. needtable::
   :filter: c.this_doc()
   :style: datatables

ID

Title

Status

Outgoing

IMPL_01

Implementation for specification

OWN_ID_123

Specification of a requirement

R_17EB4

Set admin e-mail to admin@mycompany.com

R_22EB2

Requirement B

closed

R_2A9D0

Requirement A

open

R_F4722

My first requirement

open

S_01A67

Specification B

open

S_D70B0

Specification A

closed

T_5CCAA

Test 1

T_C3893

Test for XY

implemented

It is available in the filters of the need-listing and diagram directives — including needsequence :filter:, needflow :highlight:, needgantt :milestone_filter: and, on needpie and needbar, both the filter lines and the scope :filter:. It is not available to filters configured in conf.py, such as needs_constraints and needs_warnings, since those are not written in any document; using it there raises this_doc can not be used in this context. It is likewise unavailable in needimport :filter:, which runs against needs imported from another project, and in needuml content filters.

Filtering for a type and the types inheriting from it

Added in version 9.2.0.

type == 'req' compares the type’s name: it selects the needs of type req and no other, not those of a type that inherits from req. c.is_a('req') follows inherits: it is true for a need whose type is req, or a type inheriting from req, directly or through other types. With these need types

[needs.types.sys_req]
title = "System requirement"
prefix = "SR_"
inherits = "req"

[needs.types.hw_req]
title = "Hardware requirement"
prefix = "HR_"
inherits = "sys_req"

c.is_a('req') selects the req, sys_req and hw_req needs, as type in ['req', 'sys_req', 'hw_req'] does, c.is_a('sys_req') the sys_req and hw_req ones, and c.is_a('hw_req') the hw_req ones alone; and

.. needtable::
   :filter: c.is_a('req') and not c.is_a('sys_req')

selects the req needs, and those of every other type inheriting from req, but not the sys_req and hw_req ones.

  • It reads the need’s type and the project’s need types, nothing else: no field of a need lists its types. A type whose inherits names no need type or is on a cycle inherits from none: that inherits is ignored, with a needs.type_inherits warning.

  • A name that is no need type is false on every need: c.is_a('rq') selects nothing, as type == 'rq' does. A type is named by its directive name, never its title. A string literal naming no need type is reported with a needs.filter_type warning naming the type it is the title of or is close to, once per filter and place it is written, at the places and as often as needs.namespaced_ids_off (Filtering by namespace (c.id, c.in_namespace)) is reported for a filter – a needflow :highlight: that no drawn need is tested on, and each of two needextends of one document with the same filter, included; a filter with no place of its own, such as a constraint, a derived field’s where or the filter of a dynamic function like calc_sum, once per filter string, and a needs_warnings filter once per entry, naming it: Filter "c.is_a('rq')" names 'rq', which is not a need type (did you mean 'req'?); c.is_a('rq') selects no need. A filter naming a type on purpose, such as one shared by projects that do not all declare it, is silenced with suppress_warnings = ["needs.filter_type"], which leaves the failures of filters (needs.filter) reported.

  • A need part has its need’s type.

  • Its argument is a string literal in the portable filter language: c.is_a(type) or c.is_a('req') == True is evaluated by eval, as c.this_doc() == True is.

  • It reads the need’s own type, never a needs_filter_data key named type.

  • c.is_a tests the need’s type; to follow a link type named is_a, as a project modelling an ontology may declare, use the link: 'REQ_001' in is_a.

Unlike c.this_doc() it reads the need alone, not the document the filter is written in, so it is available in the filters configured in conf.py, such as needs_warnings and needs_constraints, and in a derived field’s where (Derived fields), as well as in the filters of the need-listing and diagram directives, of needextend and of a link condition. Like c.this_doc(), it is not available in needimport :filter:, which runs against the records of the imported file, nor in the predicates of a needs_fields entry; using it there fails with name 'c' is not defined.

Beside c.this_doc() and c.is_a(), c.source holds the facets of where the need comes from (see Filtering by where a need comes from (c.source)), and c.id and c.in_namespace() read the need’s namespace (see Filtering by namespace (c.id, c.in_namespace)).

Filtering by where a need comes from (c.source)

Added in version 9.2.0.

c.source.<facet> reads where a need comes from: the file it is written in, the producer that made it, the code entity it is traced from. It selects the needs traced from code under ../src/, the needs from one test report, or the needs written in an included fragment:

.. needtable::
   :filter: c.source.path is not None and c.source.path.startswith("../src/")

.. needtable::
   :filter: "reports/unit.xml" in c.source.paths

.. needlist::
   :filter: c.source.path == "fragments/safety.rst"

A need records the places its text came through, innermost first (its hops, see Python API). Each facet reads a named position in them, never a producer, so a longer chain needs no new rule; c.source.kind also reads whether the need was imported or is external, as the need records it:

facet

what it reads

c.source.kind

The producer, from the whole chain and the need’s import and external flags; the first that applies: "import" (needimport, whatever the imported need was where it came from), "external" (an external need), "report" (a test report’s file, suite or case: sphinx-test-reports), "code" (traced from source code: sphinx-codelinks, a docstring autodoc reads), "generated" (a service), "page" (a directive in a document or in a file it includes), else None.

c.source.path

The innermost place, the file the need is written in: for a need in an included file, that file, where docname is the page it is included in; for a traced need, the code file; for a test file or suite, the report.

c.source.line

The need’s line in that file, 1-based, where the file holds the need there; None where c.source.path is.

c.source.paths

Every file the need came through that this build records, innermost first, each once: an included file, each file it was included through, then the page; a needs.json, then the page it is imported on; a report, then its page. It may gain entries (below), so test membership ('x' in c.source.paths).

c.source.symbol

The code entity a traced need is attached to, by the qualified name its producer gives it (Engine.start, ns::Widget::draw).

c.source.document

The placement: the document the need is placed on, the need’s docname.

c.source.sections

The placement: the sections the need is placed under, innermost first, or an external need’s sections on the other site, as its record gives them: the need’s sections.

A path is POSIX and relative to the Sphinx source directory, with .. for a file outside it: in a project whose documents are in docs/ and whose code is in src/, a traced need reads ../src/engine.py, whichever directory holds conf.py or ubproject.toml. A file outside the repository (a mount reached through a symbolic link, a module autodoc imports from an installed package) has a path that depends on where the checkout sits on the machine.

A facet is None where this build does not know the answer yet: c.source.path and c.source.line of an imported or an external need (its file is another project’s), of a service’s need, and of a test case, whose test file is relative to the test run’s root, which the build does not know (sphinx-test-reports’ case_file field holds it); c.source.paths of an external need is empty; c.source.symbol of a need written in a document, its domain object included. Later data only fills such a facet, so a positive test of its value (==, in, a method call) keeps selecting every need it selects today, and may gain those whose facet fills with a matching value, while a negated one (!=, not in) or a test for None (c.source.path is None, not c.source.symbol) may select fewer as the data fills. The kinds are open: a later producer adds one, so a negated test such as c.source.kind != 'page' may select more needs in a later release, where c.source.kind in ['import', 'external'] will not. c.source.paths is the exception to filling: it gains an entry wherever more of a chain is recorded – a test case’s test file once its root is known, the files a MyST {include} was included through (myst-parser logs no chain), a file included through a :parser: include on docutils 0.22 and later (which logs none) – and it differs between those docutils versions today. Test whether a file is in it, never its length or the position of an entry.

Guard a facet that can be None. c.source.path.startswith('src/') fails on a need with no path: that need is excluded and the filter reported (needs.filter). Write c.source.path is not None and c.source.path.startswith('src/'). ==, in and is None need no guard; a method, an order comparison (c.source.line > 5) and len() do. In a derived field’s where a failure is not reported at all: the candidate is excluded silently, so guard there too.

The location names a filter had before stay, each as it was:

name

and c.source

docname

c.source.document is an alias of the need’s docname (a needs_filter_data key named docname shadows the name in a filter, not the facet).

sections, section_name

c.source.sections is an alias of sections, innermost first; section_name is its first entry.

lineno

Kept as it was, and not an alias: the line the directive is written on, which for a need in an included file is a line of that file while docname is the page. An API need’s is the line its caller gives (the page’s parse count, where the caller passes its directive’s self.lineno). c.source.path and c.source.line are one file’s, a pair that always agrees.

is_import, is_external

is_import is c.source.kind == 'import'; is_external is c.source.kind == 'external' for a need that is not imported (an imported need is "import" whatever it was where it came from). Both kept.

signature

The bare name of the domain object a need is written in; c.source.symbol is a traced need’s qualified name, and does not read domain objects yet.

c is the need’s check context, as for c.this_doc() and c.is_a(): it is set over the need’s fields and the needs_filter_data keys, so a field named source (or c) is read as any other field and leaves the facets as they are.

The facets are available wherever a filter selects needs: the need-listing and diagram directives, needextend, needs_warnings, needs_constraints, needs_builder_filter, a link condition, copy(filter=...) and a derived field’s where. They are not available in the predicates of a needs_fields entry, which is evaluated as the need is created, in a needimport :filter:, which reads the imported record rather than a need of this build, nor in a variant condition: none has a check context, and a facet read there fails with name 'c' is not defined; the c.source facets are not available in a field predicate (or the place it is). The :columns: of a needtable and the :sort: and :sort_by: of the views do not read a facet yet. A filter on the facets is in the portable filter language, so it works in ubCode too.

Filtering by namespace (c.id, c.in_namespace)

Added in version 9.3.0.

With needs_namespaced_ids on, a need id holding :: names a namespace: nc::m2::REQ_1 is the local id REQ_1 in the namespace nc::m2 (Namespaced ids). Three names read it:

name

what it reads

c.id.ns

The need’s namespace, as text: "nc::m2"; "" for a need in no namespace.

c.id.local

The need’s local id: "REQ_1"; the whole id for a need in no namespace.

c.in_namespace("nc")

Whether the need’s namespace is nc or below it, compared by segments: true of nc::REQ_1 and nc::m2::REQ_1, false of ncx::REQ_1 and REQ_1.

.. needtable::
   :filter: c.in_namespace("nc") and type == "req"

.. needlist::
   :filter: c.id.ns == ""
  • id stays the full id, nc::m2::REQ_1. id.startswith("nc::") keeps working, but it is a text test: c.in_namespace("nc") is the namespace test.

  • A need part reads its need’s namespace and local id; its id is its own part id.

  • c.in_namespace(""), and an argument that is no namespace ("nc::", "a b"), is an error of the filter (needs.filter), never “every need”: a need in no namespace is c.id.ns == "". In a derived field’s where such a literal makes the rule invalid (needs.derive_invalid); in a needs_constraints check it is reported once and the check is not evaluated, as for any constraint filter that fails. A namespace no need is in selects nothing.

  • c.id holds the facets of the id, not the id: c.id == "nc::REQ_1" (or !=, or c.id in [...]) is an error of the filter; compare id, c.id.local or c.id.ns. c.id is not the id’s text: comparing it, testing membership with it, or using it as a set member or a key (c.id in {"nc::REQ_1"}) is an error, and text made from it (str(c.id)) is not the id: write id. c.in_namespace takes one argument, positionally.

  • The three are defined in every project: with needs_namespaced_ids off (the default until 10.0) every need is in no namespace, so c.id.ns is "", c.id.local is the whole id, and c.in_namespace selects nothing. Such a filter string is answered as written and reported, by its text, as needs.namespaced_ids_off: once per place it is written, and once per build where the place gives no location (a constraint, a derived field’s where, a calc_sum filter). A filter whose text shows it refused (c.in_namespace("") alone, say) keeps that refusal alone, unless evaluation happens not to raise it (c.id in [] or c.id.ns == "" compares nothing), which then gets neither; one whose refusal the text cannot settle (behind an and, say) may get both. A namespace value reached dynamically (getattr(c.id, "ns")) is not seen, nor is a filter function or filter code, which is Python rather than a filter string. A build with nothing changed reports a page’s filters only when it writes the page again, while needextend filters, link conditions, constraints, dynamic-function and derived-field filters, needs_warnings and needs_builder_filter are reported on every build.

  • c.in_namespace with a string literal is in the portable filter language, as are the two facets; any other argument (c.in_namespace(group)) is evaluated by eval, which gives the same answer. A name after c.id. that is no facet is an error naming the closest one (c.id.nss).

  • c is the check context: a field named ns, local_id, id_ns or id_local is read as any other field, and leaves these as they are.

They are available where c.is_a() is: the need-listing and diagram directives, needextend, needs_warnings, needs_constraints, needs_builder_filter, a link condition, copy(filter=...) and a derived field’s where (c.in_namespace with a string literal there). They are not available in the predicates of a needs_fields entry, in a needimport :filter: nor in a variant condition, which have no check context: name 'c' is not defined; the c.id facets are not available in a field predicate (or c.in_namespace() is not available in ...).

The names are experimental in this release: they may change before they are declared stable (What is public).

Filter string performance

Added in version 4.0.0.

Changed in version 9.1.0: The second tier compiles the whole portable filter language, and needs_debug_filters records which tier answered each filter.

The filter string is evaluated for each need and need part and, therefore, can become a performance bottleneck for projects with large numbers of needs. Sphinx-Needs answers a filter string with the first of three tiers that takes it, so writing filters the first two take is recommended:

  1. The index path. A few shapes are answered from indexes the needs keep, without evaluating the filter need by need:

    • is_external / is_external == True / is_external == False

    • id == 'value' / 'value' == id / id in ['value1', 'value2', ...]

    • type == 'value' / 'value' == type / type in ['value1', 'value2', ...]

    • status == 'value' / 'value' == status / status in ['value1', 'value2', ...]

    • 'value' in tags

    • True / False

    A filter of the form a and b and ... is split, and each of its parts of these shapes narrows the needs first: type == 'spec' and other == 'value' is filtered by type == 'spec' from the index, and only the remaining needs are evaluated for other == 'value'.

  2. The portable filter language. A string written in it is compiled once and evaluated need by need without Python’s eval, reading only the fields it names, which makes it five to six times faster than eval for the same string. A conformance corpus (tests/fixtures/filter_conformance.toml in the Sphinx-Needs repository) defines the language and pins every form’s answers; the language is also the one ubCode reads, so a filter written in it works there too. It has:

    • operands: a field (any field of the need, a needs_filter_data key, a variant data key such as var.build.debug, a facet of the need’s source such as c.source.path, see Filtering by where a need comes from (c.source), a facet of its id, c.id.ns or c.id.local, see Filtering by namespace (c.id, c.in_namespace)), len(field), field.lower() and field.upper();

    • literals: a string in single or double quotes, an integer or a float (-1, 2.5, 1e-3), True, False, None, and a list of those after in;

    • comparisons ==, !=, <, <=, >, >= between an operand and a literal, either way round (< and the others with a number literal only), or between two operands: status == 'open', 5 <= priority, owner == lead, len(tags) > 0;

    • membership: an operand in / not in a list of literals, and a literal in / not in an operand – an item of a list, a substring of a string: type in ['req', 'spec'], 'safety' in tags, 'login' not in title.lower();

    • x is None / x is not None;

    • x.startswith('...') / x.endswith('...') after an operand: id.lower().startswith('req');

    • search('pattern', x) (see search), with a plain string literal as the pattern;

    • c.this_doc() (see Filtering for needs on the current page), c.is_a('...') with a string literal (see Filtering for a type and the types inheriting from it), and c.in_namespace('...') with a string literal (see Filtering by namespace (c.id, c.in_namespace));

    • and, or, not, parentheses, and an operand alone, which is read by its truthiness.

    Not in it, and so evaluated by eval: a field in a field (sphinx_tag in tags), a list beside == or != (tags == ['a']; write len(tags) == 1 and 'a' in tags), arithmetic, subscripts (sections[0]), comprehensions, any other call or method (any(...), bool(x), x.strip()), is with anything but None, a chain of comparisons (1 < x < 5), a dotted name not under var., nor a c.source. or c.id. facet, a name after c.source. or c.id. that is no facet (c.source.pth, reported with the closest facet), and the names needs and current_need.

  3. Python’s eval, for every other string: it is evaluated need by need against a context holding every field of the need, which costs far more than the first two tiers, nearly all of it building that context. Its c.source computes a facet of the need’s source when the filter reads it.

The three tiers give the same answers, with three exceptions:

  • A field or needs_filter_data key named len: eval calls it in len(x), the portable language calls Python’s len.

  • The name of a Python builtin alone under not, and or or (filter and status == 'open'): eval reads the builtin, the portable language reports the name as undefined. As the whole filter (filter), the portable language reports it as undefined too, where eval would read the builtin, which is true.

  • search and the __dunder__ names (__name__, __debug__) compared with a literal, or alone (search == 'x', __name__ == 'builtins', __debug__): eval reads its own binding – the regular expression function, the builtins module’s attributes – and the portable language reports the name as undefined, as it did before 9.1.0. Beside a field (owner != search) the string falls to eval and answers as it does.

A few forms the second tier answers are older than the portable language and not part of it: < and the other orderings between a field and a literal that is no number (title < 'M', owner > True, owner < None), a tuple or a set after in, a constant the language has no literal for beside a field (status == b"x", status == ..., status == 1j), and not not x (write not (not x)). The second tier also reads a string’s syntax rather than its spelling, and puts no limit on its size, so it answers what the language leaves out for spelling or size alone: an integer outside the signed 64-bit range, more than 10 000 terms once the filter is expanded into alternatives of conjunctions, nesting deeper than 64, a string longer than 16 KiB, and spellings such as a parenthesised operand (len((tags)) > 0), a trailing comma, a comment, triple quotes, .5, 1e+5, -(1) or a name that is not ASCII. Each answers as eval answers it, and in search() look-around, backreferences and {,n} are Python’s own.

To see which tier answers each filter of a project’s view directives, and why one reaches eval, enable needs_debug_filters: every record says tier ("index", "fast" for the portable language, "eval", or "refused" for a constant) and, for "eval", fallback_reason, the construct that kept the string out of the portable language.

To guard against long running filters, the needs_filter_max_time configuration option can be used to set a maximum time limit for filter evaluation. Also see needs_uml_process_max_time, to guard against long running needuml / needarch processes containing filters.

To debug which filters are being used across your project, their run times and the tier answering each, you can enable the needs_debug_filters configuration option.

Deprecated since version 4.0.0: The directive option export_id was previously used to export filter information in the needs.json file. This is deprecated and will be removed in a future version. Instead use the above needs_debug_filters configuration option.

Note

Options accepted for ubCode compatibility. The ubCode editor extension supports a few directive options that Sphinx-Needs has no equivalent for:

Sphinx-Needs accepts all of these options and then ignores them, so that a document authored for ubCode also builds with Sphinx-Needs instead of failing with an unknown option error. They never reach the rendered output, the needs.json file, or any filter.

This includes width and height: a diagram is rendered at its usual size and no warning is emitted, so nothing reports that the requested size had no effect.

cypher on a chart is the one option whose no-op changes a rendered number: ubCode reads the query as the scope the content lines are counted over, whereas a Sphinx build ignores it, so the same chart can show different numbers here than in the ubCode preview. Write the same scope with :filter:, :status:, :tags: or :types: beside the query and both tools select the same needs; see common filters and common filters.

These options may gain native implementations in future Sphinx-Needs releases, in which case they would take effect here as well rather than being ignored. max_items was such a case: it is no longer ignored, but limits how many items a view shows, see needs_views_max_items.

Filter code

Added in version 0.5.3.

The content of a needlist, needtable or needflow can be used to define own filters with the help of Python.

The used code must define a variable results, which must be a list and contains the filtered needs.

The code also has access to a variable called needs, which is a NeedsAndPartsListView instance: every need, and every need part where needs_views_include_parts is true. Its results are matched to what it was handed, so with the value false a part the code builds itself (need.iter_part_items()) is dropped, unless needs_allow_unsafe_filters is set.

Example 10

.. needtable::
   :columns: id, title, type, links, links_back
   :style: table

   # Collect all requirements and specs,
   # which are linked to each other.

   results = []

   for need in needs.filter_types(["req"]):
      for links_id in need['links']:
         linked_need = needs.get_need(links_id)
         if linked_need and linked_need['type'] == 'spec':
            results.append(need)
            results.append(linked_need)

ID

Title

Type

Links

Links Back

R_3C95C

Result 4

req

R_D0791

Result 3

req

sum_input_1

Do this

spec

sum_input_3

Do too much

spec

This mechanism can also be a good alternative for complex filter strings to save performance. For example if a filter string is using list comprehensions to get access to linked needs.

If filter code is used, all other filter related options (like status or filters) are ignored.

Warning

This feature executes every given Python code. So be sure to trust the input/writers.

Filter function

Added in version 0.7.3.

Nearly same behavior as Filter code, but the code gets read from an external python file and a function must be referenced.

option name:

filter-func

default:

None

Usage inside a rst file:

.. needtable:: Filter function example
   :filter-func: filter_file.own_filter_code

The code of the referenced file filter_file.py with function own_filter_code:

def own_filter_code(needs, results, **kwargs):
    for need in needs:
        if need["type"] == "test":
            results.append(need)

The function gets executed by Sphinx-Needs and it must provide two keyword arguments: needs and results.

Also the given package/module must be importable by the used Python environment. So it must be part of the Python Path variable. To update this, add sys.path.insert(0, os.path.abspath("folder/to/filter_files")) to your conf.py file.

Arguments

Added in version 0.7.6.

Filter function are supporting arguments: filter_file.own_filter_code(value_1,value_2).

Please note, that the part between (...) is just a comma separated list and each element will be given as string to the function.

The functions get the values as part of **kwargs with the name is arg<pos>, starting from 1.

Example:

.. needtable:: Filter function example
   :filter-func: filter_file.own_filter_code(1,2.5,open)
def own_filter_code(needs, results, **kwargs):
    for need in needs:
        if int(need["price"]) > int(kwargs["arg1"]) or need["status"] == kwargs["arg3"]:
            results.append(need)

The function developer is responsible to perform any needed typecast.

Needpie

needpie also supports filter-code. But instead of needs, a list of resulting numbers must be returned.

Example:

.. needpie:: Filter code func pie
   :labels: new,done
   :filter-func: filter_code_func.my_pie_filter_code_args(new,done)
def my_pie_filter_code_args(needs, results, **kwargs):
    cnt_x = 0
    cnt_y = 0
    for need in needs:
        if need["status"] == kwargs['arg1']:
            cnt_x += 1
        if need["status"] == kwargs['arg2']:
            cnt_y += 1

   results.append(cnt_x)
   results.append(cnt_y)

Filter matches nothing

Depending on the directive used a filter that matches no needs may add text to inform that no needs are found.

The default text “No needs passed the filter”.

If this is not intended, add the option

filter_warning

Add specific text with this option or add no text to display nothing. The default text will not be shown.

The specified output could be styled with the css class needs_filter_warning

More Examples

Setup

Example 11

.. req:: My first requirement
   :status: open
   :tags: requirement; test; awesome

   This is my **first** requirement!!

   .. note:: You can use any rst code inside it :)

.. spec:: Specification of a requirement
   :id: OWN_ID_123
   :links: R_F4722

   Outgoing links of this spec: :need_outgoing:`OWN_ID_123`.

.. impl:: Implementation for specification
   :id: IMPL_01
   :links: OWN_ID_123

   Incoming links of this spec: :need_incoming:`IMPL_01`.

.. test:: Test for XY
   :status: implemented
   :tags: test; user_interface; python27
   :links: OWN_ID_123; IMPL_01

   This test checks :need:`IMPL_01` for :need:`OWN_ID_123` inside a
   Python 2.7 environment.
Requirement: My first requirement R_F4722
status: open
tags: requirement, test, awesome
links incoming: OWN_ID_123

This is my first requirement!!

Note

You can use any rst code inside it :)

Specification: Specification of a requirement OWN_ID_123
links outgoing: R_F4722
links incoming: IMPL_01, T_C3893

Outgoing links of this spec: R_F4722.

Implementation: Implementation for specification IMPL_01
links outgoing: OWN_ID_123
links incoming: T_C3893

Incoming links of this spec: T_C3893.

Test Case: Test for XY T_C3893
status: implemented
tags: test, user_interface, python27
links outgoing: IMPL_01, OWN_ID_123

This test checks Implementation for specific... (IMPL_01) for Specification of a requirement (OWN_ID_123) inside a Python 2.7 environment.

Example 12: Filter result as table

.. needtable::
   :tags: test
   :status: implemented; open

ID

Title

Status

Outgoing

df_1

my test requirement

open

R_F4722

My first requirement

open

T_C3893

Test for XY

implemented

Example 13: Filter result as diagram

.. needflow::
   :filter: "More Examples" == section_name

@startuml

' Nodes definition 

node "<size:12>Requirement</size>\n**My first**\n**requirement**\n<size:10>R_F4722</size>" as R_F4722 [[../filter.html#R_F4722]] #BFD8D2
node "<size:12>Specification</size>\n**Specification**\n**of a**\n**requirement**\n<size:10>OWN_ID_123</size>" as OWN_ID_123 [[../filter.html#OWN_ID_123]] #FEDCD2
node "<size:12>Implementation</size>\n**Implementation**\n**for**\n**specification**\n<size:10>IMPL_01</size>" as IMPL_01 [[../filter.html#IMPL_01]] #DF744A
node "<size:12>Test Case</size>\n**Test for XY**\n<size:10>T_C3893</size>" as T_C3893 [[../filter.html#T_C3893]] #DCB239
node "<size:12>Requirement</size>\n**A normal**\n**requirement**\n<size:10>EX_REQ_1</size>" as EX_REQ_1 [[../layout_styles.html#EX_REQ_1]] #BFD8D2
node "<size:12>Requirement</size>\n**A more complex**\n**and highlighted**\n**requirement**\n<size:10>EX_REQ_2</size>" as EX_REQ_2 [[../layout_styles.html#EX_REQ_2]] #BFD8D2
node "<size:12>Requirement</size>\n**A focused**\n**requirement**\n<size:10>EX_REQ_3</size>" as EX_REQ_3 [[../layout_styles.html#EX_REQ_3]] #BFD8D2
node "<size:12>Requirement</size>\n**A custom**\n**requirement**\n**with picture**\n<size:10>EX_REQ_4</size>" as EX_REQ_4 [[../layout_styles.html#EX_REQ_4]] #BFD8D2
node "<size:12>Requirement</size>\n**A requirement**\n**with a**\n**permalink**\n<size:10>EX_REQ_5</size>" as EX_REQ_5 [[../layout_styles.html#EX_REQ_5]] #BFD8D2

' Connection definition 

OWN_ID_123 --> R_F4722
IMPL_01 --> OWN_ID_123
T_C3893 --> IMPL_01
T_C3893 --> OWN_ID_123
EX_REQ_2 --> EX_REQ_1

@enduml