pytest-dev/pytest · error · TypeError

session or parent must be provided

Error message

session or parent must be provided

What it means

Node.__init__ requires either a parent node (session inherited from parent.session) or an explicit session object. Without one, hook routing and node identity break, so pytest raises TypeError. Relevant to plugin authors building custom nodes.

Source

Thrown at src/_pytest/nodes.py:176

        self.name: str = name

        #: The parent collector node.
        self.parent = parent

        if config:
            #: The pytest config object.
            self.config: Config = config
        else:
            if not parent:
                raise TypeError("config or parent must be provided")
            self.config = parent.config

        if session:
            #: The pytest session this node is part of.
            self.session: Session = session
        else:
            if not parent:
                raise TypeError("session or parent must be provided")
            self.session = parent.session

        if path is None:
            assert parent is not None
            path = parent.path
        #: Filesystem path where this node was collected from.
        self.path: pathlib.Path = path

        # The explicit annotation is to avoid publicly exposing NodeKeywords.
        #: Keywords/markers collected from all scopes.
        self.keywords: MutableMapping[str, Any] = NodeKeywords(self)

        #: The marker objects belonging to this node.
        self.own_markers: list[Mark] = []

        #: Allow adding of extra keywords to use for matching.
        self.extra_keyword_matches: set[str] = set()

View on GitHub (pinned to 98b357f69e)

Solutions

  1. Pass a parent node so session is inherited: MyNode(name, parent=parent_node)
  2. Otherwise pass session explicitly (and config and nodeid too)

Example fix

// before
node = MyNode('x', config=cfg)
// after
node = MyNode('x', parent=parent_node)
Defensive patterns

Strategy: validation

Validate before calling

def make_node(cls, name, *, parent=None, session=None, **kw):
    if parent is None and session is None:
        raise TypeError("provide parent or session")
    return cls(name, parent=parent, session=session, **kw)

Type guard

def has_parent_or_session(parent, session) -> bool:
    return parent is not None or session is not None

Prevention

When it happens

Trigger: Constructing a Node subclass with neither parent nor session, e.g. MyNode('name', config=cfg) but no session and no parent.

Common situations: Plugin code that supplies config but forgets session when there is no parent; partial refactor of a constructor.

Related errors


AI-assisted analysis of pytest-dev/pytest@98b357f69e (2026-08-04). Data as JSON: /data/errors/d2ccbefe110661f1.json. Report an issue: GitHub.