Skip to content

Objects

IDFObject represents a single EnergyPlus object (e.g. a Zone or a Material). Fields are accessed as snake_case Python attributes.

IDFCollection is a name-indexed container of objects that share the same EnergyPlus type, providing O(1) lookup by name, iteration, and filtering.

Core object classes for IDF representation.

IDFObject: Thin wrapper around a dict with attribute access. IDFCollection: Indexed collection of IDFObjects with O(1) lookup.

GroupT_co = TypeVar('GroupT_co', bound=ExtensibleGroup, covariant=True) module-attribute

ExtensibleGroup

One row of an extensible array (e.g. a single vertex inside vertices).

Holds a back-reference to the owning IDFObject and the group's 1-based index so attribute reads/writes route into obj.data[wrapper_key][group_index - 1]. Equality compares against plain dicts; as_dict() snapshots the underlying values.

Source code in idfkit/objects.py
class ExtensibleGroup:
    """One row of an extensible array (e.g. a single vertex inside ``vertices``).

    Holds a back-reference to the owning [IDFObject][idfkit.objects.IDFObject] and the group's
    1-based index so attribute reads/writes route into
    ``obj.data[wrapper_key][group_index - 1]``. Equality compares against
    plain dicts; ``as_dict()`` snapshots the underlying values.
    """

    __slots__ = ("_group_index", "_inner_names", "_owner", "_wrapper_key")

    _owner: IDFObject
    _wrapper_key: str
    _group_index: int
    _inner_names: tuple[str, ...]

    def __init__(self, owner: IDFObject, wrapper_key: str, group_index: int, inner_names: tuple[str, ...]) -> None:
        object.__setattr__(self, "_owner", owner)
        object.__setattr__(self, "_wrapper_key", wrapper_key)
        object.__setattr__(self, "_group_index", group_index)
        object.__setattr__(self, "_inner_names", inner_names)

    @property
    def group_index(self) -> int:
        """1-based position of this group within the wrapper array."""
        return self._group_index

    def _slot(self) -> dict[str, Any]:
        """Return the underlying dict for this group, creating it if necessary."""
        items = self._owner.data.setdefault(self._wrapper_key, [])
        while len(items) < self._group_index:
            items.append({})
        return cast("dict[str, Any]", items[self._group_index - 1])

    def __getattr__(self, name: str) -> Any:
        """Read one key of the group; unset, ``None``.

        A key every supported release requires (``vertex_x_coordinate``) is typed as always set, so
        reading it unset raises [MissingRequiredFieldError][idfkit.exceptions.MissingRequiredFieldError], an
        ``AttributeError``; ``group.get(name)`` gives ``None`` for it instead.
        """
        if name.startswith("_"):
            raise AttributeError(name)
        # Inlined _stored(): every typed group read passes through here.
        if name not in self._inner_names:
            raise AttributeError(  # noqa: TRY003
                f"{name!r} is not an extensible field of {self._owner.obj_type}.{self._wrapper_key}"
            )
        items = self._owner.data.get(self._wrapper_key)
        if items and self._group_index <= len(items):
            value = cast("dict[str, Any]", items[self._group_index - 1]).get(name)
            if value is not None:
                return value
        # Only the miss path pays for the required-key lookup.
        required = _required_reads(self._owner.obj_type, group=True)
        if required is not None and name in required:
            raise self._missing(name)
        return None

    def _stored(self, name: str) -> Any:
        """The value stored under *name*, a known inner field, or ``None``; never raises for a missing one."""
        if name not in self._inner_names:
            raise AttributeError(  # noqa: TRY003
                f"{name!r} is not an extensible field of {self._owner.obj_type}.{self._wrapper_key}"
            )
        items = self._owner.data.get(self._wrapper_key)
        if not items or self._group_index > len(items):
            return None
        return cast("dict[str, Any]", items[self._group_index - 1]).get(name)

    def _missing(self, name: str) -> MissingRequiredFieldError:
        """The error for *name*, a key every release requires, which the group does not hold."""
        owner = self._owner
        return MissingRequiredFieldError(owner.obj_type, owner.name, name, group=(self._wrapper_key, self._group_index))

    def get(self, name: str, default: Any = None) -> Any:
        """The value of *name*, or *default* when it is unset.

        Unlike attribute access, this never raises for an unset required key, so it is the way to
        ask whether one is set. A name that is not a key of the group still raises
        ``AttributeError``.
        """
        value = self._stored(name)
        return default if value is None else value

    def __setattr__(self, name: str, value: Any) -> None:
        if name.startswith("_"):
            object.__setattr__(self, name, value)
            return
        if name not in self._inner_names:
            raise AttributeError(  # noqa: TRY003
                f"{name!r} is not an extensible field of {self._owner.obj_type}.{self._wrapper_key}"
            )
        assign_slot(self._slot(), name, self._owner._canonical_slot_value(name, value))  # pyright: ignore[reportPrivateUsage]
        self._owner._bump_version()  # pyright: ignore[reportPrivateUsage]

    def __getitem__(self, key: str) -> Any:
        return self.__getattr__(key)

    def __setitem__(self, key: str, value: Any) -> None:
        self.__setattr__(key, value)

    def __contains__(self, key: object) -> bool:
        return isinstance(key, str) and key in self._inner_names

    def __iter__(self) -> Iterator[str]:
        return iter(self._inner_names)

    def keys(self) -> tuple[str, ...]:
        """Return the inner field names defined by the schema for this group."""
        return self._inner_names

    def values(self) -> list[Any]:
        """Return the values for each inner field, in schema order (``None`` for an unset one)."""
        return [self._stored(n) for n in self._inner_names]

    def items(self) -> list[tuple[str, Any]]:
        """Return ``(field_name, value)`` pairs for the inner fields (``None`` for an unset one)."""
        return [(n, self._stored(n)) for n in self._inner_names]

    def _snapshot(self) -> dict[str, Any]:
        """The keys the group holds, as a new dict, whether or not it lacks a required one."""
        items = self._owner.data.get(self._wrapper_key)
        if not items or self._group_index > len(items):
            return {}
        return dict(cast("dict[str, Any]", items[self._group_index - 1]))

    def as_dict(self) -> dict[str, Any]:
        """Snapshot the group as a plain dict (does not track future mutations).

        The dict holds the keys that are set. A typed group gives its item ``TypedDict``, whose
        required keys (those every supported release requires) are always present: a group that
        lacks one raises [MissingRequiredFieldError][idfkit.exceptions.MissingRequiredFieldError] rather than give a
        dict that contradicts its type.
        """
        snapshot = self._snapshot()
        for name in _required_reads(self._owner.obj_type, group=True) or ():
            if name not in snapshot and name in self._inner_names:
                raise self._missing(name)
        return snapshot

    def update(self, *args: Any, **kwargs: Any) -> None:
        """Update one or more inner fields atomically (matches dict.update)."""
        if len(args) > 1:
            raise TypeError(f"update expected at most 1 positional argument, got {len(args)}")  # noqa: TRY003
        merged: dict[str, Any] = {}
        if args:
            src = args[0]
            if isinstance(src, dict):
                merged.update(cast("dict[str, Any]", src))
            else:
                for k, v in src:
                    merged[k] = v
        merged.update(kwargs)
        for k in merged:
            if k not in self._inner_names:
                raise AttributeError(  # noqa: TRY003
                    f"{k!r} is not an extensible field of {self._owner.obj_type}.{self._wrapper_key}"
                )
        for k, v in merged.items():
            if is_non_finite(v):
                raise self._owner._non_finite_error(f"{self._wrapper_key}[{self._group_index - 1}].{k}", v)  # pyright: ignore[reportPrivateUsage]
        slot = self._slot()
        for name, value in self._owner._canonical_slots(merged).items():  # pyright: ignore[reportPrivateUsage]
            assign_slot(slot, name, value)
        self._owner._bump_version()  # pyright: ignore[reportPrivateUsage]

    def __eq__(self, other: object) -> bool:
        if isinstance(other, ExtensibleGroup):
            return self._snapshot() == other._snapshot()
        if isinstance(other, dict):
            other_dict = cast("dict[str, Any]", other)
            return self._snapshot() == other_dict
        return NotImplemented

    def __hash__(self) -> int:
        return id(self)

    def __repr__(self) -> str:
        return f"ExtensibleGroup({self._owner.obj_type}.{self._wrapper_key}[{self._group_index - 1}], {self._snapshot()!r})"

group_index property

1-based position of this group within the wrapper array.

as_dict()

Snapshot the group as a plain dict (does not track future mutations).

The dict holds the keys that are set. A typed group gives its item TypedDict, whose required keys (those every supported release requires) are always present: a group that lacks one raises MissingRequiredFieldError rather than give a dict that contradicts its type.

Source code in idfkit/objects.py
def as_dict(self) -> dict[str, Any]:
    """Snapshot the group as a plain dict (does not track future mutations).

    The dict holds the keys that are set. A typed group gives its item ``TypedDict``, whose
    required keys (those every supported release requires) are always present: a group that
    lacks one raises [MissingRequiredFieldError][idfkit.exceptions.MissingRequiredFieldError] rather than give a
    dict that contradicts its type.
    """
    snapshot = self._snapshot()
    for name in _required_reads(self._owner.obj_type, group=True) or ():
        if name not in snapshot and name in self._inner_names:
            raise self._missing(name)
    return snapshot

get(name, default=None)

The value of name, or default when it is unset.

Unlike attribute access, this never raises for an unset required key, so it is the way to ask whether one is set. A name that is not a key of the group still raises AttributeError.

Source code in idfkit/objects.py
def get(self, name: str, default: Any = None) -> Any:
    """The value of *name*, or *default* when it is unset.

    Unlike attribute access, this never raises for an unset required key, so it is the way to
    ask whether one is set. A name that is not a key of the group still raises
    ``AttributeError``.
    """
    value = self._stored(name)
    return default if value is None else value

items()

Return (field_name, value) pairs for the inner fields (None for an unset one).

Source code in idfkit/objects.py
def items(self) -> list[tuple[str, Any]]:
    """Return ``(field_name, value)`` pairs for the inner fields (``None`` for an unset one)."""
    return [(n, self._stored(n)) for n in self._inner_names]

keys()

Return the inner field names defined by the schema for this group.

Source code in idfkit/objects.py
def keys(self) -> tuple[str, ...]:
    """Return the inner field names defined by the schema for this group."""
    return self._inner_names

update(*args, **kwargs)

Update one or more inner fields atomically (matches dict.update).

Source code in idfkit/objects.py
def update(self, *args: Any, **kwargs: Any) -> None:
    """Update one or more inner fields atomically (matches dict.update)."""
    if len(args) > 1:
        raise TypeError(f"update expected at most 1 positional argument, got {len(args)}")  # noqa: TRY003
    merged: dict[str, Any] = {}
    if args:
        src = args[0]
        if isinstance(src, dict):
            merged.update(cast("dict[str, Any]", src))
        else:
            for k, v in src:
                merged[k] = v
    merged.update(kwargs)
    for k in merged:
        if k not in self._inner_names:
            raise AttributeError(  # noqa: TRY003
                f"{k!r} is not an extensible field of {self._owner.obj_type}.{self._wrapper_key}"
            )
    for k, v in merged.items():
        if is_non_finite(v):
            raise self._owner._non_finite_error(f"{self._wrapper_key}[{self._group_index - 1}].{k}", v)  # pyright: ignore[reportPrivateUsage]
    slot = self._slot()
    for name, value in self._owner._canonical_slots(merged).items():  # pyright: ignore[reportPrivateUsage]
        assign_slot(slot, name, value)
    self._owner._bump_version()  # pyright: ignore[reportPrivateUsage]

values()

Return the values for each inner field, in schema order (None for an unset one).

Source code in idfkit/objects.py
def values(self) -> list[Any]:
    """Return the values for each inner field, in schema order (``None`` for an unset one)."""
    return [self._stored(n) for n in self._inner_names]

ExtensibleList

Bases: Generic[GroupT_co]

List-like view over the canonical wrapper array obj.data[wrapper_key].

Holds a reference to the owning IDFObject and the wrapper key; indexing, iteration, append, insert, delete, pop, clear, extend, equality, and bulk replace all operate on the canonical list of dicts. Items are yielded as ExtensibleGroup instances bound to the underlying dicts.

The Generic[GroupT_co] parameter lets generated stubs narrow the item type per object — e.g. surface.vertices is typed as ExtensibleList[BuildingSurfaceVertex] so IDEs autocomplete the inner vertex_x_coordinate etc. on each indexed item.

Mutations bump the owner's mutation version. Reference-graph notification for fields inside extensible groups is handled separately by the document when it walks ref_fields recursively.

Source code in idfkit/objects.py
class ExtensibleList(Generic[GroupT_co]):
    """List-like view over the canonical wrapper array ``obj.data[wrapper_key]``.

    Holds a reference to the owning [IDFObject][idfkit.objects.IDFObject] and the wrapper key;
    indexing, iteration, append, insert, delete, pop, clear, extend, equality,
    and bulk replace all operate on the canonical list of dicts. Items are
    yielded as [ExtensibleGroup][idfkit.objects.ExtensibleGroup] instances bound to the underlying dicts.

    The ``Generic[GroupT_co]`` parameter lets generated stubs narrow the item
    type per object — e.g. ``surface.vertices`` is typed as
    ``ExtensibleList[BuildingSurfaceVertex]`` so IDEs autocomplete the
    inner ``vertex_x_coordinate`` etc. on each indexed item.

    Mutations bump the owner's mutation version. Reference-graph notification
    for fields inside extensible groups is handled separately by the document
    when it walks ``ref_fields`` recursively.
    """

    __slots__ = ("_inner_names", "_owner", "_wrapper_key")

    _owner: IDFObject
    _wrapper_key: str
    _inner_names: tuple[str, ...]

    def __init__(self, owner: IDFObject, wrapper_key: str, inner_names: tuple[str, ...]) -> None:
        self._owner = owner
        self._wrapper_key = wrapper_key
        self._inner_names = inner_names

    def _items_or_empty(self) -> list[dict[str, Any]]:
        """Return the underlying canonical list (empty list if absent)."""
        return cast("list[dict[str, Any]]", self._owner.data.get(self._wrapper_key, []))

    def _items_for_write(self) -> list[dict[str, Any]]:
        """Return the underlying canonical list, creating it if absent."""
        return cast("list[dict[str, Any]]", self._owner.data.setdefault(self._wrapper_key, []))

    def __len__(self) -> int:
        return len(self._items_or_empty())

    def _resolve_index(self, index: int) -> int:
        n = len(self)
        if index < 0:
            index += n
        if index < 0 or index >= n:
            raise IndexError(f"{self._wrapper_key} index {index} out of range (length {n})")  # noqa: TRY003
        return index

    def __getitem__(self, index: int) -> GroupT_co:
        idx = self._resolve_index(index)
        return cast("GroupT_co", ExtensibleGroup(self._owner, self._wrapper_key, idx + 1, self._inner_names))

    def __iter__(self) -> Iterator[GroupT_co]:
        for i in range(len(self)):
            yield cast(
                "GroupT_co",
                ExtensibleGroup(self._owner, self._wrapper_key, i + 1, self._inner_names),
            )

    def __delitem__(self, index: int) -> None:
        idx = self._resolve_index(index)
        items = self._items_for_write()
        del items[idx]
        if not items:
            self._owner.data.pop(self._wrapper_key, None)
        self._owner._bump_version()  # pyright: ignore[reportPrivateUsage]

    def _coerce_item(
        self,
        item: Any,
        kwargs: dict[str, Any],
        tables: Mapping[str, ChoiceSpellings] | None = None,
        *,
        position: int,
    ) -> dict[str, Any]:
        """A new dict for one group: blank slots dropped, choices in their schema's spelling.

        *tables* are the owner's extensible choice tables, when the caller resolved them once for
        several groups. *position* is the index the group will have, which names a refused slot
        as ``wrapper[i].slot``.

        Raises:
            InvalidFieldError: A slot holds NaN or infinity.
        """
        if item is not None and kwargs:
            raise TypeError("pass either a dict/group OR keyword arguments, not both")  # noqa: TRY003
        if isinstance(item, ExtensibleGroup):
            group = without_blank_slots(item._snapshot())  # pyright: ignore[reportPrivateUsage]
        elif isinstance(item, dict):
            group = without_blank_slots(cast("dict[str, Any]", item))
        elif item is None:
            group = without_blank_slots(kwargs)
        else:
            raise TypeError(f"expected dict, ExtensibleGroup, or kwargs; got {type(item).__name__}")  # noqa: TRY003
        for slot, value in group.items():
            if is_non_finite(value):
                raise self._owner._non_finite_error(f"{self._wrapper_key}[{position}].{slot}", value)  # pyright: ignore[reportPrivateUsage]
        return self._owner._canonical_slots(group, tables, fresh=True)  # pyright: ignore[reportPrivateUsage]

    def _validate_inner(self, item: dict[str, Any]) -> None:
        unknown = [k for k in item if k not in self._inner_names]
        if unknown:
            raise ValueError(  # noqa: TRY003
                f"{self._owner.obj_type}.{self._wrapper_key}: unknown extensible field(s) "
                f"{unknown!r}; expected subset of {list(self._inner_names)}"
            )

    def append(self, item: Any = None, /, **kwargs: Any) -> GroupT_co:
        """Append a new group. Accepts a dict, another [ExtensibleGroup][idfkit.objects.ExtensibleGroup], or kwargs."""
        merged = self._coerce_item(item, kwargs, position=len(self))
        self._validate_inner(merged)
        items = self._items_for_write()
        items.append(merged)
        self._owner._bump_version()  # pyright: ignore[reportPrivateUsage]
        return cast("GroupT_co", ExtensibleGroup(self._owner, self._wrapper_key, len(items), self._inner_names))

    def insert(self, index: int, item: Any = None, /, **kwargs: Any) -> GroupT_co:
        """Insert a new group at *index*. Existing groups at and after *index* shift up."""
        n = len(self)
        if index < 0:
            index = max(0, n + index)
        index = min(index, n)
        merged = self._coerce_item(item, kwargs, position=index)
        self._validate_inner(merged)
        items = self._items_for_write()
        items.insert(index, merged)
        self._owner._bump_version()  # pyright: ignore[reportPrivateUsage]
        return cast(
            "GroupT_co",
            ExtensibleGroup(self._owner, self._wrapper_key, index + 1, self._inner_names),
        )

    def extend(self, items: Any) -> None:
        """Append every group from *items* (any iterable of dicts or groups)."""
        for it in items:
            self.append(it)

    def clear(self) -> None:
        """Remove all groups."""
        if self._wrapper_key in self._owner.data:
            del self._owner.data[self._wrapper_key]
            self._owner._bump_version()  # pyright: ignore[reportPrivateUsage]

    def pop(self, index: int = -1) -> dict[str, Any]:
        """Remove and return the group at *index* as a plain dict."""
        idx = self._resolve_index(index)
        items = self._items_for_write()
        snapshot = dict(items[idx])
        del items[idx]
        if not items:
            self._owner.data.pop(self._wrapper_key, None)
        self._owner._bump_version()  # pyright: ignore[reportPrivateUsage]
        return snapshot

    def _coerce_all(self, items: list[Any]) -> list[dict[str, Any]]:
        """Coerce and validate every group of a whole-list replacement, writing nothing.

        Raises ``TypeError`` for an item that is not a dict or group, ``ValueError`` for an
        unknown inner field and ``InvalidFieldError`` for a NaN or infinite slot, so a caller can
        reject the list before any write.
        """
        tables = self._owner._choice_tables(extensible=True)  # pyright: ignore[reportPrivateUsage]
        coerced = [self._coerce_item(it, {}, tables, position=i) for i, it in enumerate(items)]
        for it in coerced:
            self._validate_inner(it)
        return coerced

    def replace(self, items: list[Any]) -> None:
        """Replace the entire wrapper contents with *items* (each a dict or group)."""
        coerced = self._coerce_all(items)
        self.clear()
        for it in coerced:
            self.append(it)

    # Typed through the group class's as_dict(): a generated group gives its item TypedDict
    # (BuildingSurfaceDetailedVerticesItem), so the list passes back to add() and update() checked;
    # an untyped ExtensibleGroup gives dict[str, Any]. Python has no way to also say the element is
    # an ExtensibleGroup, as every list's element already is.
    def as_list(self: ExtensibleList[_Snapshot[_ItemT]]) -> list[_ItemT]:  # pyright: ignore[reportInvalidTypeArguments]
        """Snapshot the wrapper as a plain list of plain dicts.

        Each dict is the group's ``as_dict()``, so a group that lacks a key every supported release
        requires raises [MissingRequiredFieldError][idfkit.exceptions.MissingRequiredFieldError]. ``obj.data`` holds
        the stored groups as they are.
        """
        return [g.as_dict() for g in self]

    def _snapshots(self) -> list[dict[str, Any]]:
        """Each group as a new dict of the keys it holds, whether or not one lacks a required key."""
        return [dict(item) for item in self._items_or_empty()]

    def __eq__(self, other: object) -> bool:
        if isinstance(other, ExtensibleList):
            return self._snapshots() == cast("ExtensibleList[ExtensibleGroup]", other)._snapshots()
        if isinstance(other, list):
            return self._snapshots() == [
                (g._snapshot() if isinstance(g, ExtensibleGroup) else g)  # pyright: ignore[reportPrivateUsage]
                for g in cast("list[Any]", other)
            ]
        return NotImplemented

    def __hash__(self) -> int:
        return id(self)

    def __repr__(self) -> str:
        return f"ExtensibleList({self._owner.obj_type}.{self._wrapper_key}, {self._snapshots()!r})"

append(item=None, /, **kwargs)

Append a new group. Accepts a dict, another ExtensibleGroup, or kwargs.

Source code in idfkit/objects.py
def append(self, item: Any = None, /, **kwargs: Any) -> GroupT_co:
    """Append a new group. Accepts a dict, another [ExtensibleGroup][idfkit.objects.ExtensibleGroup], or kwargs."""
    merged = self._coerce_item(item, kwargs, position=len(self))
    self._validate_inner(merged)
    items = self._items_for_write()
    items.append(merged)
    self._owner._bump_version()  # pyright: ignore[reportPrivateUsage]
    return cast("GroupT_co", ExtensibleGroup(self._owner, self._wrapper_key, len(items), self._inner_names))

as_list()

Snapshot the wrapper as a plain list of plain dicts.

Each dict is the group's as_dict(), so a group that lacks a key every supported release requires raises MissingRequiredFieldError. obj.data holds the stored groups as they are.

Source code in idfkit/objects.py
def as_list(self: ExtensibleList[_Snapshot[_ItemT]]) -> list[_ItemT]:  # pyright: ignore[reportInvalidTypeArguments]
    """Snapshot the wrapper as a plain list of plain dicts.

    Each dict is the group's ``as_dict()``, so a group that lacks a key every supported release
    requires raises [MissingRequiredFieldError][idfkit.exceptions.MissingRequiredFieldError]. ``obj.data`` holds
    the stored groups as they are.
    """
    return [g.as_dict() for g in self]

clear()

Remove all groups.

Source code in idfkit/objects.py
def clear(self) -> None:
    """Remove all groups."""
    if self._wrapper_key in self._owner.data:
        del self._owner.data[self._wrapper_key]
        self._owner._bump_version()  # pyright: ignore[reportPrivateUsage]

extend(items)

Append every group from items (any iterable of dicts or groups).

Source code in idfkit/objects.py
def extend(self, items: Any) -> None:
    """Append every group from *items* (any iterable of dicts or groups)."""
    for it in items:
        self.append(it)

insert(index, item=None, /, **kwargs)

Insert a new group at index. Existing groups at and after index shift up.

Source code in idfkit/objects.py
def insert(self, index: int, item: Any = None, /, **kwargs: Any) -> GroupT_co:
    """Insert a new group at *index*. Existing groups at and after *index* shift up."""
    n = len(self)
    if index < 0:
        index = max(0, n + index)
    index = min(index, n)
    merged = self._coerce_item(item, kwargs, position=index)
    self._validate_inner(merged)
    items = self._items_for_write()
    items.insert(index, merged)
    self._owner._bump_version()  # pyright: ignore[reportPrivateUsage]
    return cast(
        "GroupT_co",
        ExtensibleGroup(self._owner, self._wrapper_key, index + 1, self._inner_names),
    )

pop(index=-1)

Remove and return the group at index as a plain dict.

Source code in idfkit/objects.py
def pop(self, index: int = -1) -> dict[str, Any]:
    """Remove and return the group at *index* as a plain dict."""
    idx = self._resolve_index(index)
    items = self._items_for_write()
    snapshot = dict(items[idx])
    del items[idx]
    if not items:
        self._owner.data.pop(self._wrapper_key, None)
    self._owner._bump_version()  # pyright: ignore[reportPrivateUsage]
    return snapshot

replace(items)

Replace the entire wrapper contents with items (each a dict or group).

Source code in idfkit/objects.py
def replace(self, items: list[Any]) -> None:
    """Replace the entire wrapper contents with *items* (each a dict or group)."""
    coerced = self._coerce_all(items)
    self.clear()
    for it in coerced:
        self.append(it)

IDFCollection

Bases: Generic[_T_co]

Indexed collection of IDFObjects with O(1) lookup by name.

Provides list-like iteration and dict-like access by name.

Examples:

>>> from idfkit import new_document
>>> model = new_document()
>>> model.add("Zone", "Perimeter_ZN_1")
Zone('Perimeter_ZN_1')
>>> model.add("Zone", "Core_ZN")
Zone('Core_ZN')
>>> zones = model["Zone"]
>>> len(zones)
2

O(1) lookup by name:

>>> zones["Perimeter_ZN_1"].name
'Perimeter_ZN_1'
>>> zones[0].name
'Perimeter_ZN_1'

Attributes:

Name Type Description
_type str

The object type this collection holds

_by_name dict[str, _T_co]

Dict mapping uppercase names to objects

_items list[_T_co]

Ordered list of objects

Source code in idfkit/objects.py
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
class IDFCollection(Generic[_T_co]):
    """
    Indexed collection of IDFObjects with O(1) lookup by name.

    Provides list-like iteration and dict-like access by name.

    Examples:
        >>> from idfkit import new_document
        >>> model = new_document()
        >>> model.add("Zone", "Perimeter_ZN_1")  # doctest: +ELLIPSIS
        Zone('Perimeter_ZN_1')
        >>> model.add("Zone", "Core_ZN")  # doctest: +ELLIPSIS
        Zone('Core_ZN')
        >>> zones = model["Zone"]
        >>> len(zones)
        2

        O(1) lookup by name:

        >>> zones["Perimeter_ZN_1"].name
        'Perimeter_ZN_1'
        >>> zones[0].name
        'Perimeter_ZN_1'

    Attributes:
        _type: The object type this collection holds
        _by_name: Dict mapping uppercase names to objects
        _items: Ordered list of objects
    """

    __slots__ = ("_by_name", "_document", "_items", "_type")

    _type: str
    _by_name: dict[str, _T_co]
    _items: list[_T_co]
    _document: _ObjectFactory | _FromOlderPickle | None

    def __init__(self, obj_type: str, document: AnyIDFDocument | _ObjectFactory | None = None) -> None:
        self._type = obj_type
        self._by_name: dict[str, _T_co] = {}
        self._items: list[_T_co] = []
        # The stub of IDFDocument does not declare the private hooks collections call.
        self._document = cast("_ObjectFactory | None", document)

    def __getstate__(self) -> tuple[dict[str, Any] | None, dict[str, Any]]:
        """The state pickle and ``copy`` save: the slots, and a subclass's ``__dict__`` if it has one.

        The empty collection read for a type with no objects is not stored in its document, so it
        is saved without the document: copying or pickling it on its own then copies one empty
        collection rather than the whole model. Restored, it has no document, as one built by
        hand has none.
        """
        slots: dict[str, Any] = {}
        for cls in type(self).__mro__:
            for name in cast("tuple[str, ...]", getattr(cls, "__slots__", ())):
                if name not in ("__dict__", "__weakref__") and hasattr(self, name):
                    slots[name] = getattr(self, name)
        document = slots.get("_document")
        if document is not None and not isinstance(document, _FromOlderPickle) and not document._holds(self):  # pyright: ignore[reportPrivateUsage]
            slots["_document"] = None
        return (getattr(self, "__dict__", None) or None, slots)

    def __setstate__(self, state: Any) -> None:
        """Restore a pickled or deep-copied collection.

        A collection pickled before ``_document`` existed has no such slot in its state. It is
        marked as such, and ``add()`` takes the document of the objects it holds when it is
        called. The objects are not read here, as one may not be restored yet: when an object is
        pickled before its document (``pickle.dumps(zone)``), pickle restores the object's
        collection while it is still reading that object's own state. A subclass's ``__dict__``
        is restored as well.
        """
        attrs: dict[str, Any] | None = None
        if isinstance(state, tuple):
            pair = cast("tuple[Any, Any]", state)
            attrs, slots = cast("dict[str, Any] | None", pair[0]), cast("dict[str, Any] | None", pair[1])
        else:
            slots = cast("dict[str, Any] | None", state)
        for key, value in (attrs or {}).items():
            object.__setattr__(self, key, value)
        for key, value in (slots or {}).items():
            object.__setattr__(self, key, value)
        if "_document" not in (slots or {}):
            object.__setattr__(self, "_document", _FROM_OLDER_PICKLE)

    @property
    def obj_type(self) -> str:
        """The object type this collection holds."""
        return self._type

    @property
    def by_name(self) -> dict[str, _T_co]:
        """Dict mapping uppercase names to objects."""
        return self._by_name

    def _append(self: IDFCollection[_ObjT], obj: _ObjT) -> _ObjT:
        """Append an existing object to the end of this collection, indexed by name, and nowhere else.

        The document's own filing step, after it has built, validated and indexed the object
        (``IDFDocument.add``, ``addidfobject``). It does not validate, link the object to a
        document, index its references, or check that the object is of this collection's type,
        and an object filed in the empty collection read for an absent type is not in the
        document; hence private. It is what the deprecated ``add(obj)`` does.

        Raises:
            DuplicateObjectError: If an object with the same name exists
        """
        from .exceptions import DuplicateObjectError

        key = obj.name.upper() if obj.name else ""
        if key and key in self._by_name:
            raise DuplicateObjectError(self._type, obj.name)

        if key:
            self._by_name[key] = obj
        self._items.append(obj)
        return obj

    # The self type names only what add() reads from the element class, its creation signature;
    # Python has no intersection type to also say the element is an IDFObject, which every
    # collection's element already is. The bound is checked where it matters, on IDFCollection[X].
    #
    # Type checkers read the declaration without a docstring, and run time, help() and doc tools
    # (griffe takes the last definition) the one under ``else``. pyright gives a call the docstring of
    # the creation signature it takes the parameters from only when the method has none of its own
    # (FunctionType.applyParamSpecValue), so an editor's hover and signature help show the object
    # type's, generated from the schema ("Create a new ``Schedule:Constant``...", its memo and its
    # docs page), rather than this generic one. Type checkers skip the body under ``else``, so it only
    # delegates to _add, which they check. Editors built on jedi (pylsp, IPython) read the declaration
    # under TYPE_CHECKING whatever the order, so they show no docstring for add(): the price of
    # pyright's per-type one.
    if TYPE_CHECKING:

        def add(
            self: IDFCollection[_Creatable[_P]],  # pyright: ignore[reportInvalidTypeArguments]
            /,
            *args: _P.args,
            **fields: _P.kwargs,
        ) -> _T_co: ...

    else:

        def add(
            self: IDFCollection[_Creatable[_P]],  # pyright: ignore[reportInvalidTypeArguments]
            /,
            *args: _P.args,
            **fields: _P.kwargs,
        ) -> _T_co:
            """Create an object of this collection's type and add it to the document.

            The typed form of [IDFDocument.add][idfkit.document.IDFDocument.add]: the same object,
            validated and indexed the same way, but the keywords are the object type's own fields,
            checked by the type checker, and the result is the collection's object class.
            ``doc["Zone"].add("Office", ceiling_height=3.0)`` returns a ``Zone``, and a misspelled
            field (``ceiling_hieght=``) or a value the field does not accept
            (``zone_inside_convection_algorithm="Bogus"``) is a type error, as it is on assignment.
            Through a document narrowed to a release (``IDFDocumentV9_4``) the fields are that
            release's, and through ``AnyIDFDocument`` only those every release accepts.

            The parameters are those of the object class's creation signature, generated from the
            schema, so an editor's signature help lists them: the name first, for a type with a Name
            field; then the fields the schema requires, with no default; then the others with their
            schema default (``thermal_absorptance: float | None = 0.9``), or ``...`` where the schema
            gives none (or one that is not a plain number or string). A shown default is the value EnergyPlus applies to a field left
            empty: ``add()`` stores only the fields passed. Leaving out a required field
            (``doc.materials.add("XPS")``) is a type error, as it is a ``ValidationFailedError`` at run
            time, and so is a name for a type without a Name field (``doc["Output:SQLite"].add("x")``),
            an ``InvalidFieldError``. Through ``AnyIDFDocument`` a field is required where any release
            requires it, so no release refuses a call that type-checks; where no call suits every
            release (a required field renamed between releases), the signature requires
            ``narrow_with_as_version_first``, which nothing satisfies: narrow the document with
            ``as_version`` first. A field whose key is not a Python name (``100_outdoor_air_in_cooling``)
            is not a keyword here; set it with ``IDFDocument.add`` or after creation.

            The object is validated unless ``validate=False`` is passed, as with ``IDFDocument.add``:
            then its values, required fields and ranges are not checked, which suits bulk loading of
            data already known good, but a key the schema does not name still raises
            ``InvalidFieldError``. This form is meant to replace the string-keyed
            ``doc.add(obj_type, ...)``, so it takes the same switch; it used to validate always.
            ``validate=False`` relaxes no required field for the type checker: a call that leaves
            one out is still a type error, as it is without the switch. (Type-checking a call does
            not stand in for validation: a value out of range, ``multiplier=-3``, type-checks.)
            Fields are passed by keyword only; extensible groups go under their wrapper
            key (``vertices=[{...}, ...]``), as with ``IDFDocument.add``.

            This method used to take an existing object and file it in the collection without
            validating it or linking it to the document. That form still runs, with a
            ``DeprecationWarning`` (and a ``TypeError`` for fields passed beside the object, which it
            would drop), and will be removed; file an existing object with
            ``IDFDocument.addidfobject``, which puts it in the document. Type checkers accept only the
            form above.

            A type with no objects yet is read as an empty collection that is not stored in the
            document (reading never adds to it). Adding through such a collection stores it, so it
            holds the new object: ``zones = doc["Zone"]; zones.add("A")`` leaves ``"A"`` in
            ``zones``. If the type was stored meanwhile through another path, the object goes to the
            document's collection.

            Args:
                *args: The object's name, the only positional argument; none for a type without a
                    Name field (``doc["Output:SQLite"].add(option_type="SimpleAndTabular")``).
                **fields: Field values, by their Python field names, and ``validate``: ``False`` to
                    skip validation as ``IDFDocument.add(..., validate=False)`` does (default
                    ``True``).

            Returns:
                The new object, typed as this collection's objects.

            Raises:
                TypeError: If the collection belongs to no document (one constructed directly), a
                    field is passed positionally, the name is passed as ``name=``, or ``validate`` is
                    not a bool.
                UnknownObjectTypeError: If the collection's type is in no schema
                    (``doc.get_collection("Zoen")``).
                ValidationFailedError: If validation fails (missing required fields, invalid values).
                InvalidFieldError: If a name is passed for a type without a Name field, or a field
                    is not one of the type's (naming the closest field), in either mode.
                DuplicateObjectError: If an object of the type already has the name, or the type is
                    a singleton that already has one.

            Examples:
                >>> from idfkit import new_document
                >>> model = new_document()
                >>> office = model["Zone"].add("Office", ceiling_height=3.0)
                >>> office.ceiling_height
                3.0
                >>> model.zones.add("Lab").name
                'Lab'
                >>> [zone.name for zone in model["Zone"]]
                ['Office', 'Lab']
            """
            return self._add(args, fields)

    def _add(self, args: tuple[object, ...], fields: dict[str, Any]) -> Any:
        """The run-time body of [add][idfkit.objects.IDFCollection.add], here so that type checkers check it (see the
        note there)."""
        first = args[0] if args else None
        if isinstance(first, IDFObject):
            if len(args) > 1 or fields:
                # It files the object as it is: fields beside it would be dropped without a word.
                msg = "add(obj) takes the object alone; set its fields on the object, or create one with add(name, **fields)"
                raise TypeError(msg)
            return self._append_deprecated(first)
        legacy = fields.get("obj") if not args and len(fields) == 1 else None
        if isinstance(legacy, IDFObject):
            # add(obj=...), the keyword spelling of the deprecated form.
            return self._append_deprecated(legacy)
        validate = fields.pop("validate", True)
        if not isinstance(validate, bool):
            msg = f"add() takes validate=True or validate=False, not {validate!r}"
            raise TypeError(msg)
        if "name" in fields:
            msg = f"add() takes the object's name positionally: add({fields['name']!r}, ...), not add(name=...)"
            raise TypeError(msg)
        document = self._owner()
        if document is None:
            msg = (
                f"IDFCollection({self._type}) belongs to no document (constructed directly, or an empty "
                "collection unpickled from an idfkit release before 1.3); use IDFDocument.add"
            )
            raise TypeError(msg)
        if len(args) > 1:
            msg = f"add() takes 1 positional argument (the name) but {len(args)} were given; pass fields by keyword"
            raise TypeError(msg)
        name = cast("str", first) if args else ""
        return document._create_in(self, name, fields, validate)  # pyright: ignore[reportPrivateUsage]

    def _append_deprecated(self, obj: IDFObject) -> Any:
        """The deprecated ``add(obj)``: file an existing object as ``add`` used to, with a warning."""
        warnings.warn(
            "IDFCollection.add(obj) is deprecated: it files the object in the collection without validating "
            "it or adding it to the document. Use doc.addidfobject(obj) to add an existing object, or "
            "collection.add(name, **fields) to create one.",
            DeprecationWarning,
            stacklevel=4,  # _append_deprecated <- _add <- add <- the caller
        )
        return cast("IDFCollection[IDFObject]", self)._append(obj)

    def _owner(self) -> _ObjectFactory | None:
        """The document this collection belongs to, or ``None`` for one built by hand."""
        document = self._document
        if isinstance(document, _FromOlderPickle):
            # Unpickled from a release before collections held their document; its objects do.
            items = cast("list[IDFObject]", self._items)
            document = cast("_ObjectFactory | None", items[0]._document) if items else None  # pyright: ignore[reportPrivateUsage]
            self._document = document
        return document

    def remove(self, obj: IDFObject) -> None:
        """Remove an object from the collection and from the document that holds it.

        In a document this is [removeidfobject][idfkit.document.IDFDocument.removeidfobject]:
        the object also leaves the reference graph, so ``get_referencing()`` no longer reports
        it and renaming an object it pointed at no longer edits it. An object not in the
        collection is ignored.

        Examples:
            >>> from idfkit import new_document
            >>> model = new_document()
            >>> zone = model.add("Zone", "Core_ZN")
            >>> people = model.add("People", "Core People", zone_or_zonelist_or_space_or_spacelist_name="Core_ZN",
            ...                    validate=False)
            >>> model["People"].remove(people)
            >>> model.get_referencing("Core_ZN")
            set()
        """
        if not any(item is obj for item in self._items):
            return
        document = self._owner()
        if document is not None and document._holds(self):  # pyright: ignore[reportPrivateUsage]
            document._remove_from(self, obj)  # pyright: ignore[reportPrivateUsage]
        else:
            self._discard(obj)

    def _discard(self, obj: IDFObject) -> None:
        """Drop *obj* from this collection's list and name index, and nowhere else."""
        # By identity, not equality: two objects of a type with no Name field
        # compare equal when their fields match, and list.remove would take
        # whichever comes first.
        key = obj.name.upper() if obj.name else ""
        if self._by_name.get(key) is obj:
            del self._by_name[key]
        for i, item in enumerate(self._items):
            if item is obj:
                del self._items[i]
                break

    def __getitem__(self, key: str | int) -> _T_co:
        """Get object by name or index."""
        # String lookup is the overwhelmingly common case; route it first so
        # callers don't pay the negative isinstance check on every name lookup
        # (~12% saving on the hot path, measured 85 → 75 ns/call).
        if not isinstance(key, str):
            return self._items[key]
        if not key:
            # Unnamed/singleton objects are not indexed in _by_name;
            # fall back to the first item in the ordered list.
            if self._items:
                return self._items[0]
            raise object_not_found(self, key)
        result = self._by_name.get(key.upper())
        if result is None:
            raise object_not_found(self, key)
        return result

    def __iter__(self) -> Iterator[_T_co]:
        return iter(self._items)

    def __len__(self) -> int:
        return len(self._items)

    def __contains__(self, key: str | _T_co) -> bool:
        if isinstance(key, IDFObject):
            return key in self._items
        if not key:
            # Unnamed/singleton objects: check if any items exist
            return len(self._items) > 0
        return key.upper() in self._by_name

    def __bool__(self) -> bool:
        return len(self._items) > 0

    def __repr__(self) -> str:
        return f"IDFCollection({self._type}, count={len(self._items)})"

    @overload
    def get(self, name: str) -> _T_co | None: ...

    @overload
    def get(self, name: str, default: _D) -> _T_co | _D: ...

    def get(self, name: str, default: _D | None = None) -> _T_co | _D | None:
        """Get object by name with default.

        For unnamed/singleton object types (e.g. SimulationControl), pass an
        empty string to retrieve the first object in the collection.

        Examples:
            >>> from idfkit import new_document
            >>> model = new_document()
            >>> model.add("Zone", "Perimeter_ZN_1")  # doctest: +ELLIPSIS
            Zone('Perimeter_ZN_1')
            >>> model["Zone"].get("Perimeter_ZN_1").name
            'Perimeter_ZN_1'
            >>> model["Zone"].get("NonExistent") is None
            True
            >>> model["SimulationControl"].get("") is not None
            True
        """
        if not name:
            return self._items[0] if self._items else default
        return self._by_name.get(name.upper(), default)

    def referencing(self, target: str | IDFObject) -> list[_T_co]:
        """The objects of this collection's type that reference *target*.

        The typed form of [IDFDocument.get_referencing][idfkit.document.IDFDocument.get_referencing]:
        the same reference-graph lookup, kept to this collection's type, and typed as its objects.
        Read through ``model["BuildingSurface:Detailed"]`` the result is a list of
        ``BuildingSurfaceDetailed`` for the latest release, and of that release's class through a
        versioned document such as ``IDFDocumentV9_4``. Through ``AnyIDFDocument`` it is a list of
        ``AnyBuildingSurfaceDetailed`` or of ``BuildingSurfaceDetailed``, whose items read as
        ``AnyBuildingSurfaceDetailed``. Either way ``surface.zone_name`` is checked without a
        second lookup.

        It costs what ``get_referencing`` costs: the objects referencing the name are found in the
        graph and each is kept or dropped on its type, so neither this collection nor the model is
        scanned.

        Args:
            target: The referenced name (matched case-insensitively, as EnergyPlus does) or the
                referenced object, whose name is used. References are by name only, so two
                objects sharing a name in different object lists are not told apart.

        Returns:
            The referencing objects held by this collection, each once however many of its fields
            name *target*, in no particular order (as ``get_referencing``'s set has none). Empty
            when the collection's objects belong to no document, as nothing tracks their
            references.

        A name is matched in any reference field, so ``referencing("Office")`` on surfaces also
        returns another zone's interzone wall whose ``outside_boundary_condition_object`` is
        ``"Office"``. For the surfaces that belong to a zone use
        [get_zone_surfaces][idfkit.document.IDFDocument.get_zone_surfaces], which keeps only those
        whose ``zone_name`` names it.

        Examples:
            Find the surfaces that name a zone, then each surface's windows:

            >>> from idfkit import new_document
            >>> model = new_document()
            >>> zone = model.add("Zone", "Perimeter_ZN_1")
            >>> wall = model.add("BuildingSurface:Detailed", "South_Wall",
            ...     surface_type="Wall", construction_name="",
            ...     zone_name="Perimeter_ZN_1",
            ...     outside_boundary_condition="Outdoors",
            ...     sun_exposure="SunExposed", wind_exposure="WindExposed",
            ...     validate=False)
            >>> model.add("Lights", "Perimeter_ZN_1_Lights",
            ...     zone_or_zonelist_or_space_or_spacelist_name="Perimeter_ZN_1",
            ...     validate=False)  # doctest: +ELLIPSIS
            Lights('Perimeter_ZN_1_Lights')
            >>> [s.name for s in model["BuildingSurface:Detailed"].referencing(zone)]
            ['South_Wall']
            >>> model["FenestrationSurface:Detailed"].referencing(wall)
            []
        """
        name = target if isinstance(target, str) else target.name
        if not name or not self._items:
            return []
        # Every object of a collection belongs to the same document, which owns the graph. Nothing
        # is stored for it here, so a collection unpickled from any idfkit version can answer.
        doc = self._items[0].theidf
        if doc is None:
            return []
        obj_type = self._type
        type_upper = obj_type.upper()
        # The document files each object under its own type, so when this is the document's own
        # collection a referrer of exactly its type is a member. Any other collection (a subset
        # built by hand) is asked by identity.
        owned = doc.collections.get(obj_type) is self
        found: list[IDFObject] = []
        for obj in doc.references.get_referencing(name):
            other_type = obj.obj_type
            if other_type == obj_type and owned:
                found.append(obj)
            elif other_type.upper() == type_upper and self._holds(obj):
                # Also an object added under another spelling (addidfobject keeps it as given).
                found.append(obj)
        return cast("list[_T_co]", found)

    def _holds(self, obj: IDFObject) -> bool:
        """Whether *obj* itself is filed in this collection, by identity."""
        obj_name = obj.name
        if obj_name:
            return self._by_name.get(obj_name.upper()) is obj
        # Unnamed objects are not indexed by name.
        return any(item is obj for item in self._items)

    def first(self) -> _T_co | None:
        """Get the first object or None.

        Examples:
            Quickly grab a singleton like Building or SimulationControl:

            >>> from idfkit import new_document
            >>> model = new_document()
            >>> model.add("Zone", "Core_ZN")  # doctest: +ELLIPSIS
            Zone('Core_ZN')
            >>> model["Zone"].first().name
            'Core_ZN'
            >>> model["Material"].first() is None
            True
        """
        return self._items[0] if self._items else None

    def to_list(self) -> list[_T_co]:
        """Convert to list.

        Examples:
            >>> from idfkit import new_document
            >>> model = new_document()
            >>> model.add("Zone", "Perimeter_ZN_1")  # doctest: +ELLIPSIS
            Zone('Perimeter_ZN_1')
            >>> model.add("Zone", "Core_ZN")  # doctest: +ELLIPSIS
            Zone('Core_ZN')
            >>> [z.name for z in model["Zone"].to_list()]
            ['Perimeter_ZN_1', 'Core_ZN']
        """
        return list(self._items)

    def to_dict(self) -> list[dict[str, Any]]:
        """Convert all objects to list of dicts (eppy compatibility).

        Useful for feeding zone/material data into pandas or other
        analysis tools.

        Examples:
            >>> from idfkit import new_document
            >>> model = new_document()
            >>> model.add("Zone", "Perimeter_ZN_1", x_origin=0.0)  # doctest: +ELLIPSIS
            Zone('Perimeter_ZN_1')
            >>> dicts = model["Zone"].to_dict()
            >>> dicts[0]["name"]
            'Perimeter_ZN_1'
        """
        return [obj.to_dict() for obj in self._items]

    def filter(self, predicate: Callable[[_T_co], bool]) -> list[_T_co]:
        """Filter objects by predicate function.

        Examples:
            Find zones on upper floors of a multi-story building:

            >>> from idfkit import new_document
            >>> model = new_document()
            >>> model.add("Zone", "Ground_Office", z_origin=0.0)  # doctest: +ELLIPSIS
            Zone('Ground_Office')
            >>> model.add("Zone", "Floor2_Office", z_origin=3.5)  # doctest: +ELLIPSIS
            Zone('Floor2_Office')
            >>> upper = model["Zone"].filter(lambda z: (z.z_origin or 0) > 0)
            >>> [z.name for z in upper]
            ['Floor2_Office']
        """
        return [obj for obj in self._items if predicate(obj)]

by_name property

Dict mapping uppercase names to objects.

obj_type property

The object type this collection holds.

add(*args, **fields)

Create an object of this collection's type and add it to the document.

The typed form of IDFDocument.add: the same object, validated and indexed the same way, but the keywords are the object type's own fields, checked by the type checker, and the result is the collection's object class. doc["Zone"].add("Office", ceiling_height=3.0) returns a Zone, and a misspelled field (ceiling_hieght=) or a value the field does not accept (zone_inside_convection_algorithm="Bogus") is a type error, as it is on assignment. Through a document narrowed to a release (IDFDocumentV9_4) the fields are that release's, and through AnyIDFDocument only those every release accepts.

The parameters are those of the object class's creation signature, generated from the schema, so an editor's signature help lists them: the name first, for a type with a Name field; then the fields the schema requires, with no default; then the others with their schema default (thermal_absorptance: float | None = 0.9), or ... where the schema gives none (or one that is not a plain number or string). A shown default is the value EnergyPlus applies to a field left empty: add() stores only the fields passed. Leaving out a required field (doc.materials.add("XPS")) is a type error, as it is a ValidationFailedError at run time, and so is a name for a type without a Name field (doc["Output:SQLite"].add("x")), an InvalidFieldError. Through AnyIDFDocument a field is required where any release requires it, so no release refuses a call that type-checks; where no call suits every release (a required field renamed between releases), the signature requires narrow_with_as_version_first, which nothing satisfies: narrow the document with as_version first. A field whose key is not a Python name (100_outdoor_air_in_cooling) is not a keyword here; set it with IDFDocument.add or after creation.

The object is validated unless validate=False is passed, as with IDFDocument.add: then its values, required fields and ranges are not checked, which suits bulk loading of data already known good, but a key the schema does not name still raises InvalidFieldError. This form is meant to replace the string-keyed doc.add(obj_type, ...), so it takes the same switch; it used to validate always. validate=False relaxes no required field for the type checker: a call that leaves one out is still a type error, as it is without the switch. (Type-checking a call does not stand in for validation: a value out of range, multiplier=-3, type-checks.) Fields are passed by keyword only; extensible groups go under their wrapper key (vertices=[{...}, ...]), as with IDFDocument.add.

This method used to take an existing object and file it in the collection without validating it or linking it to the document. That form still runs, with a DeprecationWarning (and a TypeError for fields passed beside the object, which it would drop), and will be removed; file an existing object with IDFDocument.addidfobject, which puts it in the document. Type checkers accept only the form above.

A type with no objects yet is read as an empty collection that is not stored in the document (reading never adds to it). Adding through such a collection stores it, so it holds the new object: zones = doc["Zone"]; zones.add("A") leaves "A" in zones. If the type was stored meanwhile through another path, the object goes to the document's collection.

Parameters:

Name Type Description Default
*args args

The object's name, the only positional argument; none for a type without a Name field (doc["Output:SQLite"].add(option_type="SimpleAndTabular")).

()
**fields kwargs

Field values, by their Python field names, and validate: False to skip validation as IDFDocument.add(..., validate=False) does (default True).

{}

Returns:

Type Description
_T_co

The new object, typed as this collection's objects.

Raises:

Type Description
TypeError

If the collection belongs to no document (one constructed directly), a field is passed positionally, the name is passed as name=, or validate is not a bool.

UnknownObjectTypeError

If the collection's type is in no schema (doc.get_collection("Zoen")).

ValidationFailedError

If validation fails (missing required fields, invalid values).

InvalidFieldError

If a name is passed for a type without a Name field, or a field is not one of the type's (naming the closest field), in either mode.

DuplicateObjectError

If an object of the type already has the name, or the type is a singleton that already has one.

Examples:

>>> from idfkit import new_document
>>> model = new_document()
>>> office = model["Zone"].add("Office", ceiling_height=3.0)
>>> office.ceiling_height
3.0
>>> model.zones.add("Lab").name
'Lab'
>>> [zone.name for zone in model["Zone"]]
['Office', 'Lab']
Source code in idfkit/objects.py
def add(
    self: IDFCollection[_Creatable[_P]],  # pyright: ignore[reportInvalidTypeArguments]
    /,
    *args: _P.args,
    **fields: _P.kwargs,
) -> _T_co:
    """Create an object of this collection's type and add it to the document.

    The typed form of [IDFDocument.add][idfkit.document.IDFDocument.add]: the same object,
    validated and indexed the same way, but the keywords are the object type's own fields,
    checked by the type checker, and the result is the collection's object class.
    ``doc["Zone"].add("Office", ceiling_height=3.0)`` returns a ``Zone``, and a misspelled
    field (``ceiling_hieght=``) or a value the field does not accept
    (``zone_inside_convection_algorithm="Bogus"``) is a type error, as it is on assignment.
    Through a document narrowed to a release (``IDFDocumentV9_4``) the fields are that
    release's, and through ``AnyIDFDocument`` only those every release accepts.

    The parameters are those of the object class's creation signature, generated from the
    schema, so an editor's signature help lists them: the name first, for a type with a Name
    field; then the fields the schema requires, with no default; then the others with their
    schema default (``thermal_absorptance: float | None = 0.9``), or ``...`` where the schema
    gives none (or one that is not a plain number or string). A shown default is the value EnergyPlus applies to a field left
    empty: ``add()`` stores only the fields passed. Leaving out a required field
    (``doc.materials.add("XPS")``) is a type error, as it is a ``ValidationFailedError`` at run
    time, and so is a name for a type without a Name field (``doc["Output:SQLite"].add("x")``),
    an ``InvalidFieldError``. Through ``AnyIDFDocument`` a field is required where any release
    requires it, so no release refuses a call that type-checks; where no call suits every
    release (a required field renamed between releases), the signature requires
    ``narrow_with_as_version_first``, which nothing satisfies: narrow the document with
    ``as_version`` first. A field whose key is not a Python name (``100_outdoor_air_in_cooling``)
    is not a keyword here; set it with ``IDFDocument.add`` or after creation.

    The object is validated unless ``validate=False`` is passed, as with ``IDFDocument.add``:
    then its values, required fields and ranges are not checked, which suits bulk loading of
    data already known good, but a key the schema does not name still raises
    ``InvalidFieldError``. This form is meant to replace the string-keyed
    ``doc.add(obj_type, ...)``, so it takes the same switch; it used to validate always.
    ``validate=False`` relaxes no required field for the type checker: a call that leaves
    one out is still a type error, as it is without the switch. (Type-checking a call does
    not stand in for validation: a value out of range, ``multiplier=-3``, type-checks.)
    Fields are passed by keyword only; extensible groups go under their wrapper
    key (``vertices=[{...}, ...]``), as with ``IDFDocument.add``.

    This method used to take an existing object and file it in the collection without
    validating it or linking it to the document. That form still runs, with a
    ``DeprecationWarning`` (and a ``TypeError`` for fields passed beside the object, which it
    would drop), and will be removed; file an existing object with
    ``IDFDocument.addidfobject``, which puts it in the document. Type checkers accept only the
    form above.

    A type with no objects yet is read as an empty collection that is not stored in the
    document (reading never adds to it). Adding through such a collection stores it, so it
    holds the new object: ``zones = doc["Zone"]; zones.add("A")`` leaves ``"A"`` in
    ``zones``. If the type was stored meanwhile through another path, the object goes to the
    document's collection.

    Args:
        *args: The object's name, the only positional argument; none for a type without a
            Name field (``doc["Output:SQLite"].add(option_type="SimpleAndTabular")``).
        **fields: Field values, by their Python field names, and ``validate``: ``False`` to
            skip validation as ``IDFDocument.add(..., validate=False)`` does (default
            ``True``).

    Returns:
        The new object, typed as this collection's objects.

    Raises:
        TypeError: If the collection belongs to no document (one constructed directly), a
            field is passed positionally, the name is passed as ``name=``, or ``validate`` is
            not a bool.
        UnknownObjectTypeError: If the collection's type is in no schema
            (``doc.get_collection("Zoen")``).
        ValidationFailedError: If validation fails (missing required fields, invalid values).
        InvalidFieldError: If a name is passed for a type without a Name field, or a field
            is not one of the type's (naming the closest field), in either mode.
        DuplicateObjectError: If an object of the type already has the name, or the type is
            a singleton that already has one.

    Examples:
        >>> from idfkit import new_document
        >>> model = new_document()
        >>> office = model["Zone"].add("Office", ceiling_height=3.0)
        >>> office.ceiling_height
        3.0
        >>> model.zones.add("Lab").name
        'Lab'
        >>> [zone.name for zone in model["Zone"]]
        ['Office', 'Lab']
    """
    return self._add(args, fields)

filter(predicate)

Filter objects by predicate function.

Examples:

Find zones on upper floors of a multi-story building:

>>> from idfkit import new_document
>>> model = new_document()
>>> model.add("Zone", "Ground_Office", z_origin=0.0)
Zone('Ground_Office')
>>> model.add("Zone", "Floor2_Office", z_origin=3.5)
Zone('Floor2_Office')
>>> upper = model["Zone"].filter(lambda z: (z.z_origin or 0) > 0)
>>> [z.name for z in upper]
['Floor2_Office']
Source code in idfkit/objects.py
def filter(self, predicate: Callable[[_T_co], bool]) -> list[_T_co]:
    """Filter objects by predicate function.

    Examples:
        Find zones on upper floors of a multi-story building:

        >>> from idfkit import new_document
        >>> model = new_document()
        >>> model.add("Zone", "Ground_Office", z_origin=0.0)  # doctest: +ELLIPSIS
        Zone('Ground_Office')
        >>> model.add("Zone", "Floor2_Office", z_origin=3.5)  # doctest: +ELLIPSIS
        Zone('Floor2_Office')
        >>> upper = model["Zone"].filter(lambda z: (z.z_origin or 0) > 0)
        >>> [z.name for z in upper]
        ['Floor2_Office']
    """
    return [obj for obj in self._items if predicate(obj)]

first()

Get the first object or None.

Examples:

Quickly grab a singleton like Building or SimulationControl:

>>> from idfkit import new_document
>>> model = new_document()
>>> model.add("Zone", "Core_ZN")
Zone('Core_ZN')
>>> model["Zone"].first().name
'Core_ZN'
>>> model["Material"].first() is None
True
Source code in idfkit/objects.py
def first(self) -> _T_co | None:
    """Get the first object or None.

    Examples:
        Quickly grab a singleton like Building or SimulationControl:

        >>> from idfkit import new_document
        >>> model = new_document()
        >>> model.add("Zone", "Core_ZN")  # doctest: +ELLIPSIS
        Zone('Core_ZN')
        >>> model["Zone"].first().name
        'Core_ZN'
        >>> model["Material"].first() is None
        True
    """
    return self._items[0] if self._items else None

get(name, default=None)

get(name: str) -> _T_co | None
get(name: str, default: _D) -> _T_co | _D

Get object by name with default.

For unnamed/singleton object types (e.g. SimulationControl), pass an empty string to retrieve the first object in the collection.

Examples:

>>> from idfkit import new_document
>>> model = new_document()
>>> model.add("Zone", "Perimeter_ZN_1")
Zone('Perimeter_ZN_1')
>>> model["Zone"].get("Perimeter_ZN_1").name
'Perimeter_ZN_1'
>>> model["Zone"].get("NonExistent") is None
True
>>> model["SimulationControl"].get("") is not None
True
Source code in idfkit/objects.py
def get(self, name: str, default: _D | None = None) -> _T_co | _D | None:
    """Get object by name with default.

    For unnamed/singleton object types (e.g. SimulationControl), pass an
    empty string to retrieve the first object in the collection.

    Examples:
        >>> from idfkit import new_document
        >>> model = new_document()
        >>> model.add("Zone", "Perimeter_ZN_1")  # doctest: +ELLIPSIS
        Zone('Perimeter_ZN_1')
        >>> model["Zone"].get("Perimeter_ZN_1").name
        'Perimeter_ZN_1'
        >>> model["Zone"].get("NonExistent") is None
        True
        >>> model["SimulationControl"].get("") is not None
        True
    """
    if not name:
        return self._items[0] if self._items else default
    return self._by_name.get(name.upper(), default)

referencing(target)

The objects of this collection's type that reference target.

The typed form of IDFDocument.get_referencing: the same reference-graph lookup, kept to this collection's type, and typed as its objects. Read through model["BuildingSurface:Detailed"] the result is a list of BuildingSurfaceDetailed for the latest release, and of that release's class through a versioned document such as IDFDocumentV9_4. Through AnyIDFDocument it is a list of AnyBuildingSurfaceDetailed or of BuildingSurfaceDetailed, whose items read as AnyBuildingSurfaceDetailed. Either way surface.zone_name is checked without a second lookup.

It costs what get_referencing costs: the objects referencing the name are found in the graph and each is kept or dropped on its type, so neither this collection nor the model is scanned.

Parameters:

Name Type Description Default
target str | IDFObject

The referenced name (matched case-insensitively, as EnergyPlus does) or the referenced object, whose name is used. References are by name only, so two objects sharing a name in different object lists are not told apart.

required

Returns:

Type Description
list[_T_co]

The referencing objects held by this collection, each once however many of its fields

list[_T_co]

name target, in no particular order (as get_referencing's set has none). Empty

list[_T_co]

when the collection's objects belong to no document, as nothing tracks their

list[_T_co]

references.

A name is matched in any reference field, so referencing("Office") on surfaces also returns another zone's interzone wall whose outside_boundary_condition_object is "Office". For the surfaces that belong to a zone use get_zone_surfaces, which keeps only those whose zone_name names it.

Examples:

Find the surfaces that name a zone, then each surface's windows:

>>> from idfkit import new_document
>>> model = new_document()
>>> zone = model.add("Zone", "Perimeter_ZN_1")
>>> wall = model.add("BuildingSurface:Detailed", "South_Wall",
...     surface_type="Wall", construction_name="",
...     zone_name="Perimeter_ZN_1",
...     outside_boundary_condition="Outdoors",
...     sun_exposure="SunExposed", wind_exposure="WindExposed",
...     validate=False)
>>> model.add("Lights", "Perimeter_ZN_1_Lights",
...     zone_or_zonelist_or_space_or_spacelist_name="Perimeter_ZN_1",
...     validate=False)
Lights('Perimeter_ZN_1_Lights')
>>> [s.name for s in model["BuildingSurface:Detailed"].referencing(zone)]
['South_Wall']
>>> model["FenestrationSurface:Detailed"].referencing(wall)
[]
Source code in idfkit/objects.py
def referencing(self, target: str | IDFObject) -> list[_T_co]:
    """The objects of this collection's type that reference *target*.

    The typed form of [IDFDocument.get_referencing][idfkit.document.IDFDocument.get_referencing]:
    the same reference-graph lookup, kept to this collection's type, and typed as its objects.
    Read through ``model["BuildingSurface:Detailed"]`` the result is a list of
    ``BuildingSurfaceDetailed`` for the latest release, and of that release's class through a
    versioned document such as ``IDFDocumentV9_4``. Through ``AnyIDFDocument`` it is a list of
    ``AnyBuildingSurfaceDetailed`` or of ``BuildingSurfaceDetailed``, whose items read as
    ``AnyBuildingSurfaceDetailed``. Either way ``surface.zone_name`` is checked without a
    second lookup.

    It costs what ``get_referencing`` costs: the objects referencing the name are found in the
    graph and each is kept or dropped on its type, so neither this collection nor the model is
    scanned.

    Args:
        target: The referenced name (matched case-insensitively, as EnergyPlus does) or the
            referenced object, whose name is used. References are by name only, so two
            objects sharing a name in different object lists are not told apart.

    Returns:
        The referencing objects held by this collection, each once however many of its fields
        name *target*, in no particular order (as ``get_referencing``'s set has none). Empty
        when the collection's objects belong to no document, as nothing tracks their
        references.

    A name is matched in any reference field, so ``referencing("Office")`` on surfaces also
    returns another zone's interzone wall whose ``outside_boundary_condition_object`` is
    ``"Office"``. For the surfaces that belong to a zone use
    [get_zone_surfaces][idfkit.document.IDFDocument.get_zone_surfaces], which keeps only those
    whose ``zone_name`` names it.

    Examples:
        Find the surfaces that name a zone, then each surface's windows:

        >>> from idfkit import new_document
        >>> model = new_document()
        >>> zone = model.add("Zone", "Perimeter_ZN_1")
        >>> wall = model.add("BuildingSurface:Detailed", "South_Wall",
        ...     surface_type="Wall", construction_name="",
        ...     zone_name="Perimeter_ZN_1",
        ...     outside_boundary_condition="Outdoors",
        ...     sun_exposure="SunExposed", wind_exposure="WindExposed",
        ...     validate=False)
        >>> model.add("Lights", "Perimeter_ZN_1_Lights",
        ...     zone_or_zonelist_or_space_or_spacelist_name="Perimeter_ZN_1",
        ...     validate=False)  # doctest: +ELLIPSIS
        Lights('Perimeter_ZN_1_Lights')
        >>> [s.name for s in model["BuildingSurface:Detailed"].referencing(zone)]
        ['South_Wall']
        >>> model["FenestrationSurface:Detailed"].referencing(wall)
        []
    """
    name = target if isinstance(target, str) else target.name
    if not name or not self._items:
        return []
    # Every object of a collection belongs to the same document, which owns the graph. Nothing
    # is stored for it here, so a collection unpickled from any idfkit version can answer.
    doc = self._items[0].theidf
    if doc is None:
        return []
    obj_type = self._type
    type_upper = obj_type.upper()
    # The document files each object under its own type, so when this is the document's own
    # collection a referrer of exactly its type is a member. Any other collection (a subset
    # built by hand) is asked by identity.
    owned = doc.collections.get(obj_type) is self
    found: list[IDFObject] = []
    for obj in doc.references.get_referencing(name):
        other_type = obj.obj_type
        if other_type == obj_type and owned:
            found.append(obj)
        elif other_type.upper() == type_upper and self._holds(obj):
            # Also an object added under another spelling (addidfobject keeps it as given).
            found.append(obj)
    return cast("list[_T_co]", found)

remove(obj)

Remove an object from the collection and from the document that holds it.

In a document this is removeidfobject: the object also leaves the reference graph, so get_referencing() no longer reports it and renaming an object it pointed at no longer edits it. An object not in the collection is ignored.

Examples:

>>> from idfkit import new_document
>>> model = new_document()
>>> zone = model.add("Zone", "Core_ZN")
>>> people = model.add("People", "Core People", zone_or_zonelist_or_space_or_spacelist_name="Core_ZN",
...                    validate=False)
>>> model["People"].remove(people)
>>> model.get_referencing("Core_ZN")
set()
Source code in idfkit/objects.py
def remove(self, obj: IDFObject) -> None:
    """Remove an object from the collection and from the document that holds it.

    In a document this is [removeidfobject][idfkit.document.IDFDocument.removeidfobject]:
    the object also leaves the reference graph, so ``get_referencing()`` no longer reports
    it and renaming an object it pointed at no longer edits it. An object not in the
    collection is ignored.

    Examples:
        >>> from idfkit import new_document
        >>> model = new_document()
        >>> zone = model.add("Zone", "Core_ZN")
        >>> people = model.add("People", "Core People", zone_or_zonelist_or_space_or_spacelist_name="Core_ZN",
        ...                    validate=False)
        >>> model["People"].remove(people)
        >>> model.get_referencing("Core_ZN")
        set()
    """
    if not any(item is obj for item in self._items):
        return
    document = self._owner()
    if document is not None and document._holds(self):  # pyright: ignore[reportPrivateUsage]
        document._remove_from(self, obj)  # pyright: ignore[reportPrivateUsage]
    else:
        self._discard(obj)

to_dict()

Convert all objects to list of dicts (eppy compatibility).

Useful for feeding zone/material data into pandas or other analysis tools.

Examples:

>>> from idfkit import new_document
>>> model = new_document()
>>> model.add("Zone", "Perimeter_ZN_1", x_origin=0.0)
Zone('Perimeter_ZN_1')
>>> dicts = model["Zone"].to_dict()
>>> dicts[0]["name"]
'Perimeter_ZN_1'
Source code in idfkit/objects.py
def to_dict(self) -> list[dict[str, Any]]:
    """Convert all objects to list of dicts (eppy compatibility).

    Useful for feeding zone/material data into pandas or other
    analysis tools.

    Examples:
        >>> from idfkit import new_document
        >>> model = new_document()
        >>> model.add("Zone", "Perimeter_ZN_1", x_origin=0.0)  # doctest: +ELLIPSIS
        Zone('Perimeter_ZN_1')
        >>> dicts = model["Zone"].to_dict()
        >>> dicts[0]["name"]
        'Perimeter_ZN_1'
    """
    return [obj.to_dict() for obj in self._items]

to_list()

Convert to list.

Examples:

>>> from idfkit import new_document
>>> model = new_document()
>>> model.add("Zone", "Perimeter_ZN_1")
Zone('Perimeter_ZN_1')
>>> model.add("Zone", "Core_ZN")
Zone('Core_ZN')
>>> [z.name for z in model["Zone"].to_list()]
['Perimeter_ZN_1', 'Core_ZN']
Source code in idfkit/objects.py
def to_list(self) -> list[_T_co]:
    """Convert to list.

    Examples:
        >>> from idfkit import new_document
        >>> model = new_document()
        >>> model.add("Zone", "Perimeter_ZN_1")  # doctest: +ELLIPSIS
        Zone('Perimeter_ZN_1')
        >>> model.add("Zone", "Core_ZN")  # doctest: +ELLIPSIS
        Zone('Core_ZN')
        >>> [z.name for z in model["Zone"].to_list()]
        ['Perimeter_ZN_1', 'Core_ZN']
    """
    return list(self._items)

IDFObject

Bases: EppyObjectMixin

Lightweight wrapper around a dict representing an EnergyPlus object.

Uses slots for memory efficiency - each object is ~200 bytes. Provides attribute access to fields via getattr/setattr.

Examples:

Create a rigid insulation material and access its properties:

>>> from idfkit import new_document
>>> model = new_document()
>>> insulation = model.add("Material", "XPS_50mm",
...     roughness="Rough", thickness=0.05,
...     conductivity=0.034, density=35.0, specific_heat=1400.0)

Read thermal properties as attributes:

>>> insulation.conductivity
0.034
>>> insulation.thickness
0.05

Modify for parametric analysis (double the insulation):

>>> insulation.thickness = 0.1
>>> insulation.thickness
0.1

Export to a dictionary for use with external tools:

>>> d = insulation.to_dict()
>>> d["conductivity"]
0.034

Attributes:

Name Type Description
_type str

The IDF object type (e.g., "Zone", "Material")

_name str

The object's name (first field)

_data dict[str, Any]

Dict of field_name -> value

_schema dict[str, Any] | None

Optional schema dict for validation

_document AnyIDFDocument[bool] | None

Reference to parent document (for reference resolution)

_field_order list[str] | None

Ordered list of field names from schema

_aliases Mapping[str, str]

Spellings of trailing-underscore fields to their keys (shared per type)

Source code in idfkit/objects.py
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
class IDFObject(EppyObjectMixin):
    """
    Lightweight wrapper around a dict representing an EnergyPlus object.

    Uses __slots__ for memory efficiency - each object is ~200 bytes.
    Provides attribute access to fields via __getattr__/__setattr__.

    Examples:
        Create a rigid insulation material and access its properties:

        >>> from idfkit import new_document
        >>> model = new_document()
        >>> insulation = model.add("Material", "XPS_50mm",
        ...     roughness="Rough", thickness=0.05,
        ...     conductivity=0.034, density=35.0, specific_heat=1400.0)

        Read thermal properties as attributes:

        >>> insulation.conductivity
        0.034
        >>> insulation.thickness
        0.05

        Modify for parametric analysis (double the insulation):

        >>> insulation.thickness = 0.1
        >>> insulation.thickness
        0.1

        Export to a dictionary for use with external tools:

        >>> d = insulation.to_dict()
        >>> d["conductivity"]
        0.034

    Attributes:
        _type: The IDF object type (e.g., "Zone", "Material")
        _name: The object's name (first field)
        _data: Dict of field_name -> value
        _schema: Optional schema dict for validation
        _document: Reference to parent document (for reference resolution)
        _field_order: Ordered list of field names from schema
        _aliases: Spellings of trailing-underscore fields to their keys (shared per type)
    """

    __slots__ = (
        "__weakref__",
        "_aliases",
        "_data",
        "_document",
        "_ext_inner_names",
        "_extensibles",
        "_field_order",
        "_name",
        "_ref_fields",
        "_schema",
        "_source_text",
        "_type",
        "_version",
        "_wrapper_key",
    )

    _type: str
    _name: str
    _data: dict[str, Any]
    _schema: dict[str, Any] | None
    _document: AnyIDFDocument[bool] | None
    _field_order: list[str] | None
    _ref_fields: frozenset[str] | None
    _source_text: str | None
    _wrapper_key: str | None
    _ext_inner_names: tuple[str, ...]
    _extensibles: frozenset[str]
    _version: int
    _aliases: Mapping[str, str]

    def __init__(
        self,
        obj_type: str,
        name: str,
        data: dict[str, Any] | None = None,
        schema: dict[str, Any] | None = None,
        document: AnyIDFDocument[bool] | None = None,
        field_order: list[str] | None = None,
        ref_fields: frozenset[str] | None = None,
        source_text: str | None = None,
        extensibles: frozenset[str] | None = None,
        wrapper_key: str | None = None,
        ext_inner_names: tuple[str, ...] = (),
        aliases: Mapping[str, str] | None = None,
    ) -> None:
        object.__setattr__(self, "_type", obj_type)
        object.__setattr__(self, "_name", name)
        object.__setattr__(self, "_data", data if data is not None else {})
        object.__setattr__(self, "_schema", schema)
        object.__setattr__(self, "_document", document)
        # Invariant: extensible metadata must be passed as a complete bundle.
        # Having ext_field_names without a wrapper_key/inner_names trio means
        # obj.<wrapper_key> falls back to returning the raw list of dicts
        # instead of an ExtensibleList — a silent foot-gun that surfaces
        # later as 'dict' object has no attribute '<inner_field>'.
        ext_set = extensibles or frozenset()
        if ext_set and (wrapper_key is None or not ext_inner_names):
            raise ValueError(  # noqa: TRY003
                f"{obj_type}: inconsistent extensible metadata — "
                f"extensibles={sorted(ext_set)!r} requires both "
                f"wrapper_key (got {wrapper_key!r}) and ext_inner_names (got {ext_inner_names!r})"
            )
        object.__setattr__(self, "_extensibles", ext_set)
        object.__setattr__(self, "_field_order", field_order)
        object.__setattr__(self, "_ref_fields", ref_fields)
        object.__setattr__(self, "_source_text", source_text)
        object.__setattr__(self, "_version", 0)
        object.__setattr__(self, "_wrapper_key", wrapper_key)
        object.__setattr__(self, "_ext_inner_names", ext_inner_names)
        # The document passes its schema's per-type map; anything else derives it once here.
        if aliases is None:
            aliases = trailing_underscore_aliases(field_order) if field_order else {}
        object.__setattr__(self, "_aliases", aliases)

    def __setstate__(self, state: Any) -> None:
        """Restore a pickled or deep-copied object.

        An object pickled before ``_aliases`` existed has no such slot in its state; it gets
        the map from its field order, as a constructed object without ``aliases`` does.
        """
        slots = cast("dict[str, Any]", (state[1] if isinstance(state, tuple) else state) or {})
        for key, value in slots.items():
            object.__setattr__(self, key, value)
        if "_aliases" not in slots:
            field_order = cast("list[str] | None", slots.get("_field_order"))
            object.__setattr__(self, "_aliases", trailing_underscore_aliases(field_order) if field_order else {})

    @property
    def obj_type(self) -> str:
        """The IDF object type (e.g., 'Zone', 'Material')."""
        return self._type

    @property
    def mutation_version(self) -> int:
        """Monotonically increasing counter bumped on every field write.

        Useful for caches that need to detect whether an object has been
        modified since a cached value was computed.
        """
        return self._version

    @property
    def data(self) -> dict[str, Any]:
        """The field data dictionary."""
        return self._data

    @property
    def schema_dict(self) -> dict[str, Any] | None:
        """The schema dict for this object type."""
        return self._schema

    @property
    def source_text(self) -> str | None:
        """Original source text from parsing, or ``None`` if the object was mutated or created programmatically."""
        return self._source_text

    @property
    def field_order(self) -> list[str] | None:
        """Ordered list of field names from schema."""
        return self._field_order

    def extensible_items(self, wrapper_key: str | None = None) -> list[dict[str, Any]]:
        """Return the canonical list of extensible items (empty if absent).

        For an extensible type (e.g. ``BuildingSurface:Detailed``) this
        returns ``obj.data[wrapper_key]`` typed as ``list[dict[str, Any]]``.
        If *wrapper_key* is omitted, the schema's wrapper key is used.
        Returns an empty list if the wrapper isn't present or the type
        isn't extensible — never ``None``.
        """
        key = wrapper_key if wrapper_key is not None else self._wrapper_key
        if key is None:
            return []
        items = self._data.get(key)
        if not isinstance(items, list):
            return []
        return cast("list[dict[str, Any]]", items)

    def _field_key(self, key: str) -> str:
        """Resolve an attribute or [update][idfkit.objects.IDFObject.update] key to the data key it names.

        Normally this is [to_python_name][idfkit.objects.to_python_name]. A field whose epJSON key ends in ``_``
        (``cond_flag_is_the_basement_conditioned_``) is reached by that key and by the spelling
        without the underscore, which is what [to_python_name][idfkit.objects.to_python_name] makes of either; both
        resolve to the key, so the value is stored and written under the name EnergyPlus reads.
        The lookup is in a per-type map that is empty for nearly every type
        ([trailing_underscore_aliases][idfkit.schema.trailing_underscore_aliases]).
        """
        aliases = self._aliases
        if not aliases:
            return to_python_name(key)
        exact = aliases.get(key)
        if exact is not None:
            return exact
        python_key = to_python_name(key)
        return aliases.get(python_key, python_key)

    def _flat_extensible(self, python_key: str) -> tuple[str | None, int]:
        """Classify *python_key* as a legacy flat extensible spelling, never one of the fixed fields.

        Without a field order (an object built by hand), the schema's legacy field list stands in.
        """
        fixed: Container[str] | None = self._field_order
        if fixed is None:
            fixed = cast("list[str]", (self._schema or {}).get("legacy_idd", {}).get("fields", ()))
        return parse_extensible_index(python_key, self._extensibles, fixed)

    def _eppy_aliases(self) -> Mapping[str, str]:
        """eppy's spellings of this type's fields to their keys (``ParsingCache.eppy_aliases``)."""
        doc = self._document
        schema = doc.schema if doc is not None else None
        pc = schema.get_parsing_cache(self._type) if schema is not None else None
        if pc is not None:
            return pc.eppy_aliases
        return eppy_field_aliases(self._schema)

    def _eppy_key(self, python_key: str) -> str | None:
        """The key eppy's spelling *python_key* (``vertex_1_xcoordinate``) names, or ``None``.

        See ``resolve_eppy_key``; a numbered extensible field resolves to its
        flat spelling, which the legacy flat-extensible path then routes to its group.
        """
        return resolve_eppy_key(python_key, self._eppy_aliases(), self._extensibles)

    def _resolve_key(self, key: str) -> str:
        """``_field_key``, then eppy's punctuation-free spelling of a field (``Vertex_1_Xcoordinate``)."""
        python_key = self._field_key(key)
        if python_key in self._data:
            return python_key
        return self._eppy_key(python_key) or python_key

    def _unknown_field_hint(self, key: str) -> str | None:
        """The pointer an unknown-field error carries: the idfkit way to an eppy-only attribute, else the groups."""
        eppy_hint = self._eppy_attribute_hint(key)
        if eppy_hint is not None:
            return eppy_hint
        wrapper_key = self._wrapper_key
        if wrapper_key is None or not self._ext_inner_names:
            return None
        # A wrapper key that is also an attribute of every object (Schedule:Compact's ``data``) is
        # reached by item access only.
        view = f"obj[{wrapper_key!r}]" if hasattr(IDFObject, wrapper_key) else f"obj.{wrapper_key}"
        return f"Reach a group's fields as {view}[0].{self._ext_inner_names[0]}"

    def _is_known_field(self, python_key: str, field_order: list[str]) -> bool:
        """Check whether *python_key* is a valid field name for this object.

        Returns ``True`` if the key is in *field_order* OR if it is a
        legacy flat-extensible alias (``vertex_3_x_coordinate``,
        ``vertex_x_coordinate_3``, ``field_42``) for one of this type's
        extensible fields.
        """
        if python_key in field_order:
            return True
        extensibles = self._extensibles
        if not extensibles:
            return False
        base, _ = parse_extensible_index(python_key, extensibles)
        return base is not None

    def _is_own_field(self, python_key: str) -> bool:
        """Whether *python_key* is a fixed field of this object's release.

        An object built by hand and added with ``addidfobject`` has no field order of its own; its
        document's schema says which fields its type has.
        """
        field_order = self._field_order
        if field_order is not None:
            return python_key in field_order
        doc = self._document
        schema = doc.schema if doc is not None else None
        pc = schema.get_parsing_cache(self._type) if schema is not None else None
        return pc is not None and python_key in pc.field_names

    @property
    def name(self) -> str:
        """The object's name."""
        return self._name

    @name.setter
    def name(self, value: str) -> None:
        """Set the object's name."""
        self._set_name(value)

    def __getattr__(self, key: str) -> Any:  # noqa: C901
        """Get field value by attribute name.

        An unset field reads ``None``, except a field that every supported release
        requires with no default (``Material.thickness``): its type says it always has
        a value, so reading it unset raises
        [MissingRequiredFieldError][idfkit.exceptions.MissingRequiredFieldError], an ``AttributeError``.
        ``obj.get(field)`` and ``getattr(obj, field, None)`` give ``None`` for it instead.

        When the parent document has ``strict=True``, accessing a field
        name that is neither present in the data dict nor recognised by
        the schema raises ``AttributeError`` instead of returning
        ``None``.  This catches typos during migration.
        """
        # Hot path: every field read passes through here. Slice-compare
        # is ~10% faster than ``key.startswith("_")`` for the underscore
        # guard, and direct slot access (``self._x``) is ~50% faster
        # than ``object.__getattribute__`` since slots are unconditionally
        # initialised by ``__init__``.
        if key[:1] == "_":
            raise AttributeError(key)

        # Canonical extensible-wrapper access (e.g. surface.vertices,
        # schedule.data, branchlist.branches). Must be checked before the
        # raw-data match: data[wrapper_key] holds the underlying list, but
        # callers expect a typed ExtensibleList view.
        wrapper_key = self._wrapper_key
        if wrapper_key is not None and (key == wrapper_key or to_python_name(key) == wrapper_key):
            return ExtensibleList[ExtensibleGroup](self, wrapper_key, self._ext_inner_names)

        # Try exact match first
        data = self._data
        if key in data:
            return data[key]

        # Try lowercase version
        key_lower = key.lower()
        if key_lower in data:
            return data[key_lower]

        # Try python name conversion, then eppy's punctuation-free spelling (Vertex_1_Xcoordinate)
        python_key = self._resolve_key(key)
        if python_key in data:
            return data[python_key]

        # Eppy-compat: legacy flat extensible field access
        # (vertex_3_x_coordinate, vertex_x_coordinate_3, time_2, ...).
        # Translates to the canonical wrapper position with a deprecation
        # warning. Scheduled for removal in a future release.
        extensibles = self._extensibles
        if extensibles:
            base, group_idx = self._flat_extensible(python_key)
            if base is not None and wrapper_key is not None:
                items_any: Any = data.get(wrapper_key)
                if isinstance(items_any, list):
                    items_typed = cast("list[dict[str, Any]]", items_any)
                    if 0 < group_idx <= len(items_typed):
                        warnings.warn(
                            f"{key!r} flat-extensible access is deprecated; "
                            f"use {self._type}.{wrapper_key}[{group_idx - 1}].{base}",
                            DeprecationWarning,
                            stacklevel=2,
                        )
                        return items_typed[group_idx - 1].get(base)

        # Eppy-compat: a surface's geometry (surf.area, surf.coords, ...), never a field of its type.
        if key in EPPY_SURFACE_ATTRIBUTES and python_key not in (self._field_order or ()):
            found, value = self._eppy_surface_attr(key)
            if found:
                return value

        # Field not found — check strict mode
        doc = self._document
        if doc is not None and getattr(doc, "_strict", False):
            # In strict mode, only allow known schema fields
            field_order = self._field_order
            if field_order is not None and not self._is_known_field(python_key, field_order):
                ver: tuple[int, int, int] | None = doc.version
                raise InvalidFieldError(
                    self._type,
                    key,
                    available_fields=list(field_order),
                    version=ver,
                    extensible_fields=extensibles,
                    hint=self._unknown_field_hint(key),
                )

        # A field every release requires reads as its value type: absent, it is an error rather
        # than a None its type says cannot occur. Only the miss path pays for the lookup. The table
        # spans every release, so the field must also be one of this object's own: a lax document
        # reads a field its release lacks (a name from another release) as None, as any unknown name.
        required = _required_reads(self._type, group=False)
        if required is not None and python_key in required and self._is_own_field(python_key):
            raise MissingRequiredFieldError(self._type, self._name, python_key)

        # Default: return None (eppy behaviour)
        return None

    def __setattr__(self, key: str, value: Any) -> None:
        """Set field value by attribute name.

        In a strict document, a value the schema refuses (wrong type, unlisted
        choice, out of range) raises [ValidationFailedError][idfkit.exceptions.ValidationFailedError]
        and the field keeps its value, as ``add()`` refuses it.

        Assigning the schema's wrapper key (e.g. ``surface.vertices = [...]``)
        replaces the canonical extensible array. Legacy eppy-style flat
        extensible writes (``surface.vertex_3_x_coordinate = 5.0``) are
        routed to the canonical slot with a ``DeprecationWarning``.
        """
        if key[:1] == "_":
            object.__setattr__(self, key, value)
            return
        if key.lower() == "name":
            self._set_name(value)
            return
        # Canonical extensible-wrapper bulk replace (e.g. surface.vertices = [...]).
        wrapper_key = self._wrapper_key
        if wrapper_key is not None and (key == wrapper_key or to_python_name(key) == wrapper_key):
            if not isinstance(value, list):
                raise TypeError(  # noqa: TRY003
                    f"{self._type}.{wrapper_key} must be a list of dicts; got {type(value).__name__}"
                )
            view = ExtensibleList[ExtensibleGroup](self, wrapper_key, self._ext_inner_names)
            view.replace(cast("list[Any]", value))
            return
        # Normalize key to python style, eppy's punctuation-free spelling included
        python_key = self._resolve_key(key)

        # Eppy-compat: legacy flat extensible field write
        # (surface.vertex_3_x_coordinate = 5.0). Routes to the canonical
        # wrapper slot with a deprecation warning.
        if self._extensibles:
            base, group_idx = self._flat_extensible(python_key)
            if base is not None and self._wrapper_key is not None:
                warnings.warn(
                    f"{key!r} flat-extensible assignment is deprecated; "
                    f"use {self._type}.{self._wrapper_key}[{group_idx - 1}].{base} = ...",
                    DeprecationWarning,
                    stacklevel=2,
                )
                items = self._data.setdefault(self._wrapper_key, [])
                while len(items) < group_idx:
                    items.append({})
                assign_slot(
                    cast("list[dict[str, Any]]", items)[group_idx - 1], base, self._canonical_slot_value(base, value)
                )
                self._bump_version()
                return

        # Validate in strict mode
        doc = self._document
        if doc is not None and getattr(doc, "_strict", False):
            field_order = self._field_order
            if field_order is not None and not self._is_known_field(python_key, field_order):
                ver: tuple[int, int, int] | None = object.__getattribute__(doc, "version")
                raise InvalidFieldError(
                    self._type,
                    key,
                    available_fields=list(field_order),
                    version=ver,
                    extensible_fields=self._extensibles,
                    hint=self._unknown_field_hint(key),
                )
            self._refuse_invalid_values([(python_key, value)])
        self._set_field(python_key, value)

    def _value_errors(self, entries: Iterable[tuple[str, Any]]) -> list[ValidationError]:
        """The findings ``add()`` would raise for these ``(field, value)`` writes, in a strict document.

        A lax document (``strict=False``), a detached object and a document without a schema check
        nothing, so a value can still be written there for ``validate_document()`` to report.
        """
        doc = self._document
        if doc is None or not doc.strict:
            return []
        schema = doc.schema
        if schema is None:
            return []
        from .validation import field_value_error

        return [error for key, value in entries if (error := field_value_error(self, key, value, schema)) is not None]

    def _refuse_invalid_values(self, entries: Iterable[tuple[str, Any]]) -> None:
        """Raise [ValidationFailedError][idfkit.exceptions.ValidationFailedError] if a strict document's schema refuses
        any of *entries*.

        NaN and infinity are refused first, with the [InvalidFieldError][idfkit.exceptions.InvalidFieldError] every
        document raises for them, so a range check never reports one as merely out of range.
        """
        entries = list(entries)
        for key, value in entries:
            if is_non_finite(value):
                raise self._non_finite_error(key, value)
        errors = self._value_errors(entries)
        if errors:
            raise ValidationFailedError(errors)

    def __getitem__(self, key: str | int) -> Any:
        """Get field value by name or index.

        For the schema's extensible wrapper key (``"vertices"``, ``"data"``,
        ``"branches"``, …), returns an [ExtensibleList][idfkit.objects.ExtensibleList] view of the
        wrapper. This is the only access path for types whose wrapper key
        collides with the ``data`` property (Schedule:Day:Interval,
        Schedule:Compact); for other types it is equivalent to attribute
        access.
        """
        if isinstance(key, int):
            if key == 0:
                return self._name
            if self._field_order and 0 < key <= len(self._field_order):
                field_name = self._field_order[key - 1]
                return self._data.get(field_name)
            raise IndexError(f"Field index {key} out of range")  # noqa: TRY003
        if self._wrapper_key is not None and key == self._wrapper_key:
            return ExtensibleList[ExtensibleGroup](self, self._wrapper_key, self._ext_inner_names)
        return getattr(self, key)

    def __setitem__(self, key: str | int, value: Any) -> None:
        """Set field value by name or index.

        For the schema's extensible wrapper key, *value* must be a list of
        dicts (or [ExtensibleGroup][idfkit.objects.ExtensibleGroup] instances) and replaces the entire
        wrapper contents.
        """
        if isinstance(key, int):
            if key == 0:
                self._set_name(value)
            elif self._field_order and 0 < key <= len(self._field_order):
                field_name = self._field_order[key - 1]
                self._refuse_invalid_values([(field_name, value)])
                self._set_field(field_name, value)
            else:
                raise IndexError(f"Field index {key} out of range")  # noqa: TRY003
            return
        if self._wrapper_key is not None and key == self._wrapper_key:
            if not isinstance(value, list):
                raise TypeError(  # noqa: TRY003
                    f"{self._type}[{key!r}] must be a list of dicts; got {type(value).__name__}"
                )
            ExtensibleList[ExtensibleGroup](self, self._wrapper_key, self._ext_inner_names).replace(
                cast("list[Any]", value)
            )
            return
        setattr(self, key, value)

    def _identifying_fields(self) -> str:
        """``zone_name='B'``: the first set field of an object whose type has no Name field.

        A first value of ``"*"`` (``Output:Variable``'s every-key wildcard) names nothing, so the
        next set field follows it. ``""`` for an object that has a name, whose type has a Name
        field, or whose type is unknown: those read by their name, even an empty one.
        """
        if self._name or self._schema is None or "name" in self._schema:
            return ""
        parts: list[str] = []
        keys = self._field_order if self._field_order is not None else list(self._data)
        for key in keys:
            value = self._data.get(key)
            if value is None or value == "" or isinstance(value, (list, dict)):
                continue
            parts.append(f"{key}={value!r}")
            if value != "*" or len(parts) == 2:
                break
        return ", ".join(parts)

    def __repr__(self) -> str:
        fields = self._identifying_fields()
        if fields:
            return f"{self._type}({fields})"
        return f"{self._type}('{self._name}')"

    def __str__(self) -> str:
        return f"{self._type}: {self._identifying_fields() or self._name}"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, IDFObject):
            return NotImplemented
        return self._type == other._type and self._name == other._name and self._data == other._data

    def __hash__(self) -> int:
        return id(self)

    def _set_name(self, value: str) -> None:
        """Centralized name-change logic with document notification.

        Raises:
            InvalidFieldError: If *value* is not empty and the object's type has no Name field
                (``Output:Meter``, ``Timestep``, ...): the name would be dropped on write.
            ValidationFailedError: If, in a strict document, *value* is blank and the object's
                type requires a name, as ``add()`` refuses it.
        """
        old = self._name
        if old == value:
            return
        refuse_name_for_nameless_type(self._type, value, self._schema)
        self._refuse_blank_name(value)
        object.__setattr__(self, "_name", value)
        object.__setattr__(self, "_version", self._version + 1)
        object.__setattr__(self, "_source_text", None)
        doc = self._document
        if doc is not None:
            doc.notify_name_change(self, old, value)

    def _refuse_blank_name(self, value: str) -> None:
        """Raise [ValidationFailedError][idfkit.exceptions.ValidationFailedError] if a strict document's schema requires
        a name and *value* is blank."""
        if value.strip():
            return
        doc = self._document
        if doc is None or not doc.strict:
            return
        schema = doc.schema
        if schema is None:
            return
        from .validation import name_error

        error = name_error(self, value, schema)
        if error is not None:
            raise ValidationFailedError([error])

    def _bump_version(self) -> None:
        """Mark the object as mutated.

        Bumps [mutation_version][idfkit.objects.IDFObject.mutation_version] and invalidates the cached IDF source
        text so the writer regenerates output for this object. Used by
        [ExtensibleList][idfkit.objects.ExtensibleList]/[ExtensibleGroup][idfkit.objects.ExtensibleGroup] after mutating
        the canonical wrapper array directly (without going through
        ``_set_field``).
        """
        object.__setattr__(self, "_version", self._version + 1)
        object.__setattr__(self, "_source_text", None)
        self._reindex_extensible_references()

    def _reindex_extensible_references(self) -> None:
        """Refresh the reference graph after an extensible group was mutated.

        ``ExtensibleGroup``/``ExtensibleList`` write into ``data[wrapper_key]`` directly
        instead of going through ``_set_field``, so the per-field hook that keeps
        top-level reference edges current never fires for them. Re-indexing the wrapper is
        the equivalent for group edits; it is a no-op for the overwhelming majority of
        extensible types, whose inner fields (vertices, coefficients, ...) reference nothing.
        """
        ref_fields = self._ref_fields
        if not ref_fields:
            return
        ext_ref_fields = ref_fields & self._extensibles
        if not ext_ref_fields:
            return
        doc = self._document
        wrapper_key = self._wrapper_key
        if doc is None or wrapper_key is None:
            return
        doc.references.reindex_extensible(self, wrapper_key, ext_ref_fields)

    def _choice_tables(self, *, extensible: bool) -> Mapping[str, ChoiceSpellings]:
        """The choice spelling tables writes to this object are normalized with, keyed by field.

        Empty unless the object belongs to a document that normalizes choices and has a schema for
        its type: a detached object has no document to say which spelling is canonical.
        """
        doc = self._document
        if doc is None or not doc.normalize_choices:
            return NO_CHOICE_SPELLINGS
        schema = doc.schema
        pc = schema.get_parsing_cache(self._type) if schema is not None else None
        if pc is None:
            return NO_CHOICE_SPELLINGS
        return pc.ext_choice_spellings if extensible else pc.choice_spellings

    def _canonical_slot_value(self, name: str, value: Any) -> Any:
        """*value* for the extensible slot *name*, in its schema's spelling when it is a choice.

        Raises:
            InvalidFieldError: *value* is NaN or infinity, which no field takes.
        """
        if not isinstance(value, str):
            if is_non_finite(value):
                raise self._non_finite_error(name, value)
            return value
        return canonical_choice(self._choice_tables(extensible=True).get(name), value)

    def _canonical_slots(
        self,
        slots: Mapping[str, Any],
        tables: Mapping[str, ChoiceSpellings] | None = None,
        *,
        fresh: bool = False,
    ) -> dict[str, Any]:
        """A copy of one extensible group's *slots*, each choice in its schema's spelling.

        The tables are resolved once for the whole group rather than once per slot, or passed in as
        *tables* by a caller coercing several groups. With *fresh*, *slots* is a dict the caller
        just built, returned as it is when no choice needs rewriting.
        """
        if tables is None:
            tables = self._choice_tables(extensible=True)
        if not tables:
            return cast("dict[str, Any]", slots) if fresh else dict(slots)
        return {name: canonical_choice(tables.get(name), value) for name, value in slots.items()}

    def _non_finite_error(self, field_name: str, value: float) -> InvalidFieldError:
        """The error for writing NaN or infinity into *field_name*, before anything is stored."""
        where = f"{self._type} {self._name!r}" if self._name else self._type
        return InvalidFieldError(self._type, field_name, message=non_finite_message(where, field_name, value))

    def _set_field(self, python_key: str, value: Any) -> None:
        """Centralized data-field write with reference graph notification.

        A write of the value already held is not a change and is not recorded as
        one. ``_set_name`` has compared before acting since it was written; this
        is the same guard on its sibling, and without it a preserving writer
        reformats an object nobody edited: writing ``3.0`` over the ``3.0`` a file
        already said turns ``3.000`` into ``3`` in the output (FR-004).

        The comparison is on the value the field holds, not on the whole object,
        so it costs one lookup on a path that was already reading the field for
        the reference graph.

        A blank value (``None`` or ``""``) clears the field rather than storing a
        placeholder, as the parser leaves a blank field absent (idfkit#183) and as
        [assign_slot][idfkit.objects.assign_slot] clears an extensible slot (idfkit#182). Writing a blank
        over a field that is already unset is therefore not a change either, so
        ``obj.f = obj.f`` on a blank field leaves the object untouched.
        """
        if isinstance(value, str):
            value = canonical_choice(self._choice_tables(extensible=False).get(python_key), value)
        elif is_non_finite(value):
            raise self._non_finite_error(python_key, value)
        data = self._data
        blank = is_blank_slot(value)
        if python_key in data:
            current = data[python_key]
            if current == value:
                return
        elif blank:
            return
        else:
            current = None

        if blank:
            del data[python_key]
        else:
            data[python_key] = value

        doc = self._document
        ref_fields = self._ref_fields
        if doc is not None and ref_fields is not None and python_key in ref_fields:
            doc.notify_reference_change(self, python_key, current, value)

        object.__setattr__(self, "_version", self._version + 1)
        object.__setattr__(self, "_source_text", None)

    def to_dict(self) -> dict[str, Any]:
        """Convert to dictionary representation.

        Useful for serializing EnergyPlus objects to JSON, CSV, or
        DataFrames for post-processing.

        Examples:
            >>> from idfkit import new_document
            >>> model = new_document()
            >>> mat = model.add("Material", "Concrete_200mm",
            ...     roughness="MediumRough", thickness=0.2,
            ...     conductivity=1.4, density=2240.0, specific_heat=900.0)
            >>> d = mat.to_dict()
            >>> d["name"], d["thickness"], d["conductivity"]
            ('Concrete_200mm', 0.2, 1.4)
        """
        return {"name": self._name, **self._data}

    def get(self, key: str, default: Any = None) -> Any:
        """Get field value with default.

        *default* when the field is unset or holds ``None``. Unlike attribute access, this never
        raises for an unset required field, so it is the way to ask whether one is set.

        Examples:
            >>> from idfkit import new_document
            >>> model = new_document()
            >>> mat = model.add("Material", "Concrete_200mm",
            ...     roughness="MediumRough", thickness=0.2,
            ...     conductivity=1.4, density=2240.0, specific_heat=900.0)
            >>> mat.get("conductivity")
            1.4
            >>> mat.get("thermal_absorptance", 0.9)
            0.9
        """
        try:
            value = getattr(self, key)
        except MissingRequiredFieldError:
            # The untyped read: an absent required field is a missing value here, not an error.
            return default
        return value if value is not None else default

    def update(self, values: Mapping[str, Any] | None = None, /, **kwargs: Any) -> None:
        """Set several fields in one call, all or nothing.

        The group is a mapping, keyword arguments, or both; where both name the same field,
        the keyword wins, as with ``dict.update``. Field names are accepted exactly as single
        assignment accepts them, and ``None`` clears a field.

        Every entry is examined before any is applied. If one is refused, no field changes and
        the error lists every refused entry, not only the first. An entry is refused when its
        name is not a field of the type, when it is ``name`` (use
        [IDFDocument.rename][idfkit.document.IDFDocument.rename], which also updates the
        objects that refer to this one), when it is a legacy flat extensible name such as
        ``vertex_3_x_coordinate``, or when it gives the extensible wrapper key (such as
        ``vertices``) a value that single assignment would reject: something other than a list,
        or a list holding an item that is not a dict or group, or a group with an unknown field.

        Unknown names are refused even in a document opened with ``strict=False``, where
        single assignment would store them. An object without a schema field order, such as
        one constructed detached, accepts any name, as single assignment does. Accepted
        entries are applied in order by ordinary attribute assignment, so reference tracking
        and change tracking are exactly those of consecutive single assignments.

        Raises:
            InvalidFieldError: An entry is unknown, is ``name``, or is a legacy flat
                extensible name. ``field_name`` is the first entry refused for its name, and
                ``refused`` holds every refused entry, including any refused for its value.
            TypeError: Every refused entry gives the wrapper key a value it rejects.
            ValidationFailedError: In a strict document, the schema refuses a value as ``add()``
                would (wrong type, unlisted choice, out of range); ``errors`` lists every one.
                Names are examined first, so this is raised only when every name is accepted.

        Examples:
            >>> from idfkit import new_document
            >>> model = new_document()
            >>> zone = model.add("Zone", "Office")
            >>> zone.update(x_origin=10.0, y_origin=5.0)
            >>> zone.x_origin, zone.y_origin
            (10.0, 5.0)
            >>> zone.update(x_origin=0.0, x_orign=0.0)
            Traceback (most recent call last):
                ...
            idfkit.exceptions.InvalidFieldError: Update of object type 'Zone' refused; no field was changed:
              - x_orign: unknown (not a field of Zone)
            ...
            >>> zone.x_origin
            10.0
        """
        # Keyed by the name single assignment resolves, so ``"X Origin"`` and ``x_origin`` are one
        # entry and a keyword overrides a mapping entry however either is spelled.
        group: dict[str, tuple[str, Any]] = {}
        for source in (values if values is not None else {}, kwargs):
            for key, value in source.items():
                group[key if key[:1] == "_" else self._resolve_key(key)] = (key, value)
        refused = [entry for key, value in group.values() if (entry := self._examine(key, value)) is not None]
        if refused:
            self._refuse(refused)
        # Every value is checked before any is written, so a refused value leaves the object as it was.
        self._refuse_invalid_values(
            (python_key, value) for python_key, (_, value) in group.items() if python_key != self._wrapper_key
        )
        for key, value in group.values():
            setattr(self, key, value)

    if TYPE_CHECKING:
        # What IDFCollection.add takes to create an object of this class (stub-only): here any name
        # and fields, which the run-time validator checks, for the collections a type checker cannot
        # narrow. Each generated class declares its own, from the schema: the name only for a type
        # with a Name field, the required fields without a default, the others with their schema
        # default. Editors show the docstring of the one a call takes its parameters from.
        def _creation_signature(self, name: str = "", /, **fields: Any) -> None:
            """Create an object of this collection's type and add it to the document.

            The object type is not known to the type checker here (``doc.get_collection(obj_type)``),
            so any name and fields are accepted, and validated at run time. ``doc["Zone"]`` and
            ``doc.zones`` type the fields of their object type.
            """

    def _examine(self, key: str, value: Any) -> RefusedEntry | None:
        """Classify one [update][idfkit.objects.IDFObject.update] entry with the tests ``__setattr__`` applies to it."""
        if key[:1] == "_":
            return RefusedEntry(key, "unknown", "private attribute, not a field")
        python_key = self._resolve_key(key)
        if key.lower() == "name" or python_key == "name":
            return RefusedEntry(key, "name", "use rename() to change an object's name")
        wrapper_key = self._wrapper_key
        if wrapper_key is not None and (key == wrapper_key or python_key == wrapper_key):
            return self._examine_wrapper(key, wrapper_key, value)
        if self._extensibles and wrapper_key is not None:
            base, group_idx = self._flat_extensible(python_key)
            if base is not None:
                return RefusedEntry(key, "legacy-flat", f"use {wrapper_key}[{group_idx - 1}].{base}")
        field_order = self._field_order
        if field_order is not None and not self._is_known_field(python_key, field_order):
            return RefusedEntry(key, "unknown", f"not a field of {self._type}")
        # Last, so a key that is not a field is refused as that, whatever its value.
        if is_non_finite(value):
            return RefusedEntry(key, "non-finite", NON_FINITE_DETAIL)
        return None

    def _examine_wrapper(self, key: str, wrapper_key: str, value: Any) -> RefusedEntry | None:
        """Classify an [update][idfkit.objects.IDFObject.update] entry for the extensible wrapper: its whole list of
        groups."""
        if not isinstance(value, list):
            return RefusedEntry(key, "wrapper-value", f"expected a list, got {type(value).__name__}")
        view = ExtensibleList[ExtensibleGroup](self, wrapper_key, self._ext_inner_names)
        try:
            view._coerce_all(cast("list[Any]", value))  # pyright: ignore[reportPrivateUsage]
        except InvalidFieldError as exc:
            return RefusedEntry(exc.field_name, "non-finite", NON_FINITE_DETAIL)
        except (TypeError, ValueError) as exc:
            return RefusedEntry(key, "wrapper-value", str(exc))
        return None

    def _refuse(self, refused: list[RefusedEntry], operation: Literal["update", "add"] = "update") -> None:
        """Raise the error for a refused [update][idfkit.objects.IDFObject.update] group or ``add()`` call, before
        anything is written."""
        named = [entry for entry in refused if entry.reason != "wrapper-value"]
        if not named:
            raise TypeError(format_refused(self._type, refused, operation))
        doc = self._document
        field_order = self._field_order
        available: list[str] | None = None
        if field_order is not None:
            # The legacy field order omits the wrapper key, the spelling the groups must use.
            wrapper_key = self._wrapper_key
            available = list(field_order)
            if wrapper_key is not None and wrapper_key not in available:
                available.append(wrapper_key)
        raise InvalidFieldError(
            self._type,
            named[0].name,
            available_fields=available,
            version=object.__getattribute__(doc, "version") if doc is not None else None,
            extensible_fields=self._extensibles,
            refused=refused,
            operation=operation,
        )

    def copy(self) -> IDFObject:
        """Create a copy of this object."""
        return IDFObject(
            obj_type=self._type,
            name=self._name,
            data=deepcopy(self._data),
            schema=self._schema,
            document=None,  # Don't copy document reference
            field_order=list(self._field_order) if self._field_order is not None else None,
            ref_fields=self._ref_fields,
            source_text=None,  # copy is a new object; don't carry over verbatim text
            extensibles=self._extensibles,
            wrapper_key=self._wrapper_key,
            ext_inner_names=self._ext_inner_names,
            aliases=self._aliases,
        )

    def __dir__(self) -> list[str]:
        """Return attributes for tab completion (includes schema field names)."""
        attrs = [
            "obj_type",
            "name",
            "data",
            "key",
            "Name",
            "fieldnames",
            "fieldvalues",
            "theidf",
            "schema_dict",
            "field_order",
            "to_dict",
            "get",
            "copy",
            "get_field_idd",
            "get_referenced_object",
            "getfieldidd",
            "getfieldidd_item",
            "getrange",
            "checkrange",
            "getreferingobjs",
        ]
        field_order = object.__getattribute__(self, "_field_order")
        if field_order:
            attrs.extend(field_order)
        else:
            data = object.__getattribute__(self, "_data")
            attrs.extend(data.keys())
        return attrs

    def _repr_svg_(self) -> str | None:
        """Return SVG representation for Jupyter/IPython display.

        Currently supports Construction objects, rendering a cross-section
        diagram showing layer sequence, thicknesses, and thermal properties.

        Returns:
            SVG string for Construction objects, None for other types.
        """
        if self._type != "Construction":
            return None

        if self._document is None:
            # Need document to resolve material references
            return None

        try:
            from .visualization.svg import construction_to_svg

            return construction_to_svg(self)
        except Exception:
            # Fail gracefully - fall back to text repr
            return None

data property

The field data dictionary.

field_order property

Ordered list of field names from schema.

mutation_version property

Monotonically increasing counter bumped on every field write.

Useful for caches that need to detect whether an object has been modified since a cached value was computed.

name property writable

The object's name.

obj_type property

The IDF object type (e.g., 'Zone', 'Material').

schema_dict property

The schema dict for this object type.

source_text property

Original source text from parsing, or None if the object was mutated or created programmatically.

copy()

Create a copy of this object.

Source code in idfkit/objects.py
def copy(self) -> IDFObject:
    """Create a copy of this object."""
    return IDFObject(
        obj_type=self._type,
        name=self._name,
        data=deepcopy(self._data),
        schema=self._schema,
        document=None,  # Don't copy document reference
        field_order=list(self._field_order) if self._field_order is not None else None,
        ref_fields=self._ref_fields,
        source_text=None,  # copy is a new object; don't carry over verbatim text
        extensibles=self._extensibles,
        wrapper_key=self._wrapper_key,
        ext_inner_names=self._ext_inner_names,
        aliases=self._aliases,
    )

extensible_items(wrapper_key=None)

Return the canonical list of extensible items (empty if absent).

For an extensible type (e.g. BuildingSurface:Detailed) this returns obj.data[wrapper_key] typed as list[dict[str, Any]]. If wrapper_key is omitted, the schema's wrapper key is used. Returns an empty list if the wrapper isn't present or the type isn't extensible — never None.

Source code in idfkit/objects.py
def extensible_items(self, wrapper_key: str | None = None) -> list[dict[str, Any]]:
    """Return the canonical list of extensible items (empty if absent).

    For an extensible type (e.g. ``BuildingSurface:Detailed``) this
    returns ``obj.data[wrapper_key]`` typed as ``list[dict[str, Any]]``.
    If *wrapper_key* is omitted, the schema's wrapper key is used.
    Returns an empty list if the wrapper isn't present or the type
    isn't extensible — never ``None``.
    """
    key = wrapper_key if wrapper_key is not None else self._wrapper_key
    if key is None:
        return []
    items = self._data.get(key)
    if not isinstance(items, list):
        return []
    return cast("list[dict[str, Any]]", items)

get(key, default=None)

Get field value with default.

default when the field is unset or holds None. Unlike attribute access, this never raises for an unset required field, so it is the way to ask whether one is set.

Examples:

>>> from idfkit import new_document
>>> model = new_document()
>>> mat = model.add("Material", "Concrete_200mm",
...     roughness="MediumRough", thickness=0.2,
...     conductivity=1.4, density=2240.0, specific_heat=900.0)
>>> mat.get("conductivity")
1.4
>>> mat.get("thermal_absorptance", 0.9)
0.9
Source code in idfkit/objects.py
def get(self, key: str, default: Any = None) -> Any:
    """Get field value with default.

    *default* when the field is unset or holds ``None``. Unlike attribute access, this never
    raises for an unset required field, so it is the way to ask whether one is set.

    Examples:
        >>> from idfkit import new_document
        >>> model = new_document()
        >>> mat = model.add("Material", "Concrete_200mm",
        ...     roughness="MediumRough", thickness=0.2,
        ...     conductivity=1.4, density=2240.0, specific_heat=900.0)
        >>> mat.get("conductivity")
        1.4
        >>> mat.get("thermal_absorptance", 0.9)
        0.9
    """
    try:
        value = getattr(self, key)
    except MissingRequiredFieldError:
        # The untyped read: an absent required field is a missing value here, not an error.
        return default
    return value if value is not None else default

to_dict()

Convert to dictionary representation.

Useful for serializing EnergyPlus objects to JSON, CSV, or DataFrames for post-processing.

Examples:

>>> from idfkit import new_document
>>> model = new_document()
>>> mat = model.add("Material", "Concrete_200mm",
...     roughness="MediumRough", thickness=0.2,
...     conductivity=1.4, density=2240.0, specific_heat=900.0)
>>> d = mat.to_dict()
>>> d["name"], d["thickness"], d["conductivity"]
('Concrete_200mm', 0.2, 1.4)
Source code in idfkit/objects.py
def to_dict(self) -> dict[str, Any]:
    """Convert to dictionary representation.

    Useful for serializing EnergyPlus objects to JSON, CSV, or
    DataFrames for post-processing.

    Examples:
        >>> from idfkit import new_document
        >>> model = new_document()
        >>> mat = model.add("Material", "Concrete_200mm",
        ...     roughness="MediumRough", thickness=0.2,
        ...     conductivity=1.4, density=2240.0, specific_heat=900.0)
        >>> d = mat.to_dict()
        >>> d["name"], d["thickness"], d["conductivity"]
        ('Concrete_200mm', 0.2, 1.4)
    """
    return {"name": self._name, **self._data}

update(values=None, /, **kwargs)

Set several fields in one call, all or nothing.

The group is a mapping, keyword arguments, or both; where both name the same field, the keyword wins, as with dict.update. Field names are accepted exactly as single assignment accepts them, and None clears a field.

Every entry is examined before any is applied. If one is refused, no field changes and the error lists every refused entry, not only the first. An entry is refused when its name is not a field of the type, when it is name (use IDFDocument.rename, which also updates the objects that refer to this one), when it is a legacy flat extensible name such as vertex_3_x_coordinate, or when it gives the extensible wrapper key (such as vertices) a value that single assignment would reject: something other than a list, or a list holding an item that is not a dict or group, or a group with an unknown field.

Unknown names are refused even in a document opened with strict=False, where single assignment would store them. An object without a schema field order, such as one constructed detached, accepts any name, as single assignment does. Accepted entries are applied in order by ordinary attribute assignment, so reference tracking and change tracking are exactly those of consecutive single assignments.

Raises:

Type Description
InvalidFieldError

An entry is unknown, is name, or is a legacy flat extensible name. field_name is the first entry refused for its name, and refused holds every refused entry, including any refused for its value.

TypeError

Every refused entry gives the wrapper key a value it rejects.

ValidationFailedError

In a strict document, the schema refuses a value as add() would (wrong type, unlisted choice, out of range); errors lists every one. Names are examined first, so this is raised only when every name is accepted.

Examples:

>>> from idfkit import new_document
>>> model = new_document()
>>> zone = model.add("Zone", "Office")
>>> zone.update(x_origin=10.0, y_origin=5.0)
>>> zone.x_origin, zone.y_origin
(10.0, 5.0)
>>> zone.update(x_origin=0.0, x_orign=0.0)
Traceback (most recent call last):
    ...
idfkit.exceptions.InvalidFieldError: Update of object type 'Zone' refused; no field was changed:
  - x_orign: unknown (not a field of Zone)
...
>>> zone.x_origin
10.0
Source code in idfkit/objects.py
def update(self, values: Mapping[str, Any] | None = None, /, **kwargs: Any) -> None:
    """Set several fields in one call, all or nothing.

    The group is a mapping, keyword arguments, or both; where both name the same field,
    the keyword wins, as with ``dict.update``. Field names are accepted exactly as single
    assignment accepts them, and ``None`` clears a field.

    Every entry is examined before any is applied. If one is refused, no field changes and
    the error lists every refused entry, not only the first. An entry is refused when its
    name is not a field of the type, when it is ``name`` (use
    [IDFDocument.rename][idfkit.document.IDFDocument.rename], which also updates the
    objects that refer to this one), when it is a legacy flat extensible name such as
    ``vertex_3_x_coordinate``, or when it gives the extensible wrapper key (such as
    ``vertices``) a value that single assignment would reject: something other than a list,
    or a list holding an item that is not a dict or group, or a group with an unknown field.

    Unknown names are refused even in a document opened with ``strict=False``, where
    single assignment would store them. An object without a schema field order, such as
    one constructed detached, accepts any name, as single assignment does. Accepted
    entries are applied in order by ordinary attribute assignment, so reference tracking
    and change tracking are exactly those of consecutive single assignments.

    Raises:
        InvalidFieldError: An entry is unknown, is ``name``, or is a legacy flat
            extensible name. ``field_name`` is the first entry refused for its name, and
            ``refused`` holds every refused entry, including any refused for its value.
        TypeError: Every refused entry gives the wrapper key a value it rejects.
        ValidationFailedError: In a strict document, the schema refuses a value as ``add()``
            would (wrong type, unlisted choice, out of range); ``errors`` lists every one.
            Names are examined first, so this is raised only when every name is accepted.

    Examples:
        >>> from idfkit import new_document
        >>> model = new_document()
        >>> zone = model.add("Zone", "Office")
        >>> zone.update(x_origin=10.0, y_origin=5.0)
        >>> zone.x_origin, zone.y_origin
        (10.0, 5.0)
        >>> zone.update(x_origin=0.0, x_orign=0.0)
        Traceback (most recent call last):
            ...
        idfkit.exceptions.InvalidFieldError: Update of object type 'Zone' refused; no field was changed:
          - x_orign: unknown (not a field of Zone)
        ...
        >>> zone.x_origin
        10.0
    """
    # Keyed by the name single assignment resolves, so ``"X Origin"`` and ``x_origin`` are one
    # entry and a keyword overrides a mapping entry however either is spelled.
    group: dict[str, tuple[str, Any]] = {}
    for source in (values if values is not None else {}, kwargs):
        for key, value in source.items():
            group[key if key[:1] == "_" else self._resolve_key(key)] = (key, value)
    refused = [entry for key, value in group.values() if (entry := self._examine(key, value)) is not None]
    if refused:
        self._refuse(refused)
    # Every value is checked before any is written, so a refused value leaves the object as it was.
    self._refuse_invalid_values(
        (python_key, value) for python_key, (_, value) in group.items() if python_key != self._wrapper_key
    )
    for key, value in group.values():
        setattr(self, key, value)

assign_slot(slot, name, value)

Set name in an extensible group's slot, or clear it when value is blank (idfkit#182).

Source code in idfkit/objects.py
def assign_slot(slot: dict[str, Any], name: str, value: Any) -> None:
    """Set *name* in an extensible group's *slot*, or clear it when *value* is blank (idfkit#182)."""
    if is_blank_slot(value):
        slot.pop(name, None)
    else:
        slot[name] = value

drop_blank_group_slots(fields, wrapper_key)

fields without the unset slots of its extensible groups, nor any group left empty (idfkit#182).

Returns fields itself when there is nothing to drop, and a shallow copy otherwise.

Source code in idfkit/objects.py
def drop_blank_group_slots(fields: dict[str, Any], wrapper_key: str) -> dict[str, Any]:
    """*fields* without the unset slots of its extensible groups, nor any group left empty (idfkit#182).

    Returns *fields* itself when there is nothing to drop, and a shallow copy otherwise.
    """
    groups = fields.get(wrapper_key)
    if not isinstance(groups, list):
        return fields
    items = cast("list[Any]", groups)

    def needs_cleaning(group: Any) -> bool:
        return isinstance(group, dict) and (
            not group or any(map(is_blank_slot, cast("dict[str, Any]", group).values()))
        )

    if not any(map(needs_cleaning, items)):
        return fields
    cleaned = [without_blank_slots(cast("dict[str, Any]", g)) if isinstance(g, dict) else g for g in items]
    return {**fields, wrapper_key: [g for g in cleaned if g != {}]}

is_blank_slot(value)

Whether value leaves an extensible slot unset: None or the empty string (idfkit#182).

Source code in idfkit/objects.py
def is_blank_slot(value: Any) -> bool:
    """Whether *value* leaves an extensible slot unset: ``None`` or the empty string (idfkit#182)."""
    return value is None or value == ""

object_not_found(collection, name)

The error for a lookup of name in collection, suggesting the closest existing names.

Shared by collection[name], doc.rename() and the dotted doc.update(), so a misspelt object name gets the same "did you mean" wherever it is looked up.

Source code in idfkit/objects.py
def object_not_found(collection: IDFCollection[IDFObject], name: str) -> ObjectNotFoundError:
    """The error for a lookup of *name* in *collection*, suggesting the closest existing names.

    Shared by ``collection[name]``, ``doc.rename()`` and the dotted ``doc.update()``, so a
    misspelt object name gets the same "did you mean" wherever it is looked up.
    """
    # The names are listed lazily, when the message is read: a miss caught as ``KeyError`` (the
    # try/except membership idiom) must stay O(1) however large the collection is.
    return ObjectNotFoundError(
        collection.obj_type,
        name,
        lambda: [obj.name for obj in collection if obj.name],
        object_count=len(collection),
    )

parse_extensible_index(field_name, extensibles, fixed=())

Extract the base name and 1-based group index from an extensible field name.

Handles both naming conventions: - field_1 / field_2 (user style, base field) - vertex_1_x_coordinate / vertex_2_x_coordinate (user style) - field / field_2 (schema style, first group has no number) - vertex_x_coordinate / vertex_x_coordinate_2 (schema style)

A name in fixed (the type's fixed properties) is never extensible, even when it fits a pattern: MaterialProperty:GlazingSpectralData has fixed wavelength_1 beside an extensible wavelength, and Site:SpectrumData has a fixed wavelength of the same name as one.

Group numbers start at 1. A 0 (vertex_0_x_coordinate), a leading zero or a non-ASCII digit names no group, so such a name is not extensible either.

Returns (base_name, group_index) or (None, 0) if not extensible.

Source code in idfkit/objects.py
def parse_extensible_index(
    field_name: str, extensibles: frozenset[str], fixed: Container[str] = ()
) -> tuple[str | None, int]:
    """Extract the base name and 1-based group index from an extensible field name.

    Handles both naming conventions:
    - ``field_1`` / ``field_2`` (user style, base ``field``)
    - ``vertex_1_x_coordinate`` / ``vertex_2_x_coordinate`` (user style)
    - ``field`` / ``field_2`` (schema style, first group has no number)
    - ``vertex_x_coordinate`` / ``vertex_x_coordinate_2`` (schema style)

    A name in *fixed* (the type's fixed properties) is never extensible, even when it fits a pattern:
    ``MaterialProperty:GlazingSpectralData`` has fixed ``wavelength_1`` beside an extensible
    ``wavelength``, and ``Site:SpectrumData`` has a fixed ``wavelength`` of the same name as one.

    Group numbers start at 1. A ``0`` (``vertex_0_x_coordinate``), a leading zero or a non-ASCII
    digit names no group, so such a name is not extensible either.

    Returns ``(base_name, group_index)`` or ``(None, 0)`` if not extensible.
    """
    if field_name in fixed:
        return None, 0
    if field_name in extensibles:
        return field_name, 1

    last_underscore = field_name.rfind("_")
    if last_underscore > 0 and _GROUP_NUMBER_PATTERN.fullmatch(field_name, last_underscore + 1):
        base = field_name[:last_underscore]
        if base in extensibles:
            return base, int(field_name[last_underscore + 1 :])

    m = _EXTENSIBLE_NUMBER_PATTERN.match(field_name)
    if m:
        base = f"{m.group(1)}_{m.group(3)}"
        if base in extensibles:
            return base, int(m.group(2))

    return None, 0

refuse_name_for_nameless_type(obj_type, name, obj_schema)

Raise InvalidFieldError when name is given to a type without a Name field.

165 of the 880 types in the 26.2 schema (Output:Meter, Output:SQLite, Timestep, SimulationControl, ...) have no Name field: their first IDF field is an ordinary field. A name stored on one of them is dropped by both writers, so add("Output:SQLite", "SimpleAndTabular") writes Output:SQLite, and EnergyPlus produces no .sql file. The value is not moved into the first field either: for most of these types that field is an option or a number, and guessing a value is worse than refusing.

"" and None mean no name. An unknown type (obj_schema is None) is not checked.

Source code in idfkit/objects.py
def refuse_name_for_nameless_type(obj_type: str, name: object, obj_schema: Mapping[str, Any] | None) -> None:
    """Raise [InvalidFieldError][idfkit.exceptions.InvalidFieldError] when *name* is given to a type without a Name
    field.

    165 of the 880 types in the 26.2 schema (``Output:Meter``, ``Output:SQLite``, ``Timestep``,
    ``SimulationControl``, ...) have no Name field: their first IDF field is an ordinary field.
    A name stored on one of them is dropped by both writers, so ``add("Output:SQLite",
    "SimpleAndTabular")`` writes ``Output:SQLite,`` and EnergyPlus produces no ``.sql`` file.
    The value is not moved into the first field either: for most of these types that field is
    an option or a number, and guessing a value is worse than refusing.

    ``""`` and ``None`` mean no name. An unknown type (*obj_schema* is ``None``) is not checked.
    """
    if not name or obj_schema is None or "name" in obj_schema:
        return
    legacy: Mapping[str, Any] = obj_schema.get("legacy_idd", {})
    fields: Sequence[str] = legacy.get("fields", [])
    if fields:
        hint = f'Pass it as a field instead: {fields[0]}="{name}".'
    else:
        hint = "The type has no fields to carry it; leave the name empty."
    msg = f'{obj_type} has no Name field, so "{name}" would be dropped on write. {hint}'
    raise InvalidFieldError(obj_type, "name", message=msg)

refuse_unknown_fields_for_add(obj, pc)

Refuse what IDFDocument.add must not store, as IDFObject.update refuses it.

Runs on the new object before it joins the document, so a refusal leaves nothing behind.

Parameters:

Name Type Description Default
obj IDFObject

The object add() built, not yet in any collection.

required
pc ParsingCache

Its type's parsing cache.

required

Raises:

Type Description
InvalidFieldError

A key is not a field of the type, is name (which belongs in the name argument), or is not spelled as the field ("X Origin" for x_origin).

TypeError

The only problem is the wrapper value: not a list, an item that is not a dict or group, or a group with a key the group does not name.

Source code in idfkit/objects.py
def refuse_unknown_fields_for_add(obj: IDFObject, pc: ParsingCache) -> None:
    """Refuse what ``IDFDocument.add`` must not store, as [IDFObject.update][idfkit.objects.IDFObject.update] refuses
    it.

    Runs on the new object before it joins the document, so a refusal leaves nothing behind.

    Args:
        obj: The object ``add()`` built, not yet in any collection.
        pc: Its type's parsing cache.

    Raises:
        InvalidFieldError: A key is not a field of the type, is ``name`` (which belongs in the
            ``name`` argument), or is not spelled as the field (``"X Origin"`` for ``x_origin``).
        TypeError: The only problem is the wrapper value: not a list, an item that is not a dict
            or group, or a group with a key the group does not name.
    """
    data = obj.data
    wrapper_key = pc.ext_wrapper_key
    refused: list[RefusedEntry] = []
    known = pc.known_keys
    # Fast path: every key known. The refusal tests below run only when one is not.
    if not data.keys() <= known:
        for key, value in data.items():
            if key == wrapper_key or key in known:
                continue
            python_key = to_python_name(key)
            if key.lower() == "name" or python_key == "name":
                refused.append(RefusedEntry(key, "name", "pass the object's name as add()'s name argument"))
            elif (entry := obj._examine(key, value)) is not None and entry.reason != "non-finite":  # pyright: ignore[reportPrivateUsage]
                refused.append(entry)
            elif python_key != key:
                # update() resolves display spellings such as "X Origin"; add() stores keys as given.
                refused.append(RefusedEntry(key, "unknown", f"spell it {python_key!r}"))
    if wrapper_key is not None and wrapper_key in data:
        groups = data[wrapper_key]
        inner = pc.ext_inner_props.keys()
        plain = type(groups) is list and all(
            type(group) is dict and group.keys() <= inner for group in cast("list[Any]", groups)
        )
        if not plain and (entry := obj._examine(wrapper_key, groups)) is not None:  # pyright: ignore[reportPrivateUsage]
            refused.append(entry)
    # A key refused above is refused once, for the problem to fix first.
    seen = {entry.name for entry in refused}
    refused.extend(
        RefusedEntry(key, "non-finite", NON_FINITE_DETAIL) for key, _ in non_finite_fields(data) if key not in seen
    )
    if refused:
        obj._refuse(refused, "add")  # pyright: ignore[reportPrivateUsage]

to_idf_name(python_name)

Convert Python name back to IDF-style name.

'direction_of_relative_north' -> 'Direction of Relative North'

Source code in idfkit/objects.py
def to_idf_name(python_name: str) -> str:
    """Convert Python name back to IDF-style name.

    'direction_of_relative_north' -> 'Direction of Relative North'
    """
    return " ".join(word.capitalize() for word in python_name.split("_"))

to_python_name(idf_name) cached

Convert IDF field name to Python-friendly name.

'Direction of Relative North' -> 'direction_of_relative_north' 'X Origin' -> 'x_origin'

Cached: this is on the hot path of every IDFObject.__getattr__ and __setattr__ call. The pure regex pipeline costs ~300-660 ns; a cached lookup costs ~30 ns. The unique-input set is bounded by the schema's field-name vocabulary (a few thousand strings), well within the cache's working set.

Source code in idfkit/objects.py
@lru_cache(maxsize=2048)
def to_python_name(idf_name: str) -> str:
    """Convert IDF field name to Python-friendly name.

    'Direction of Relative North' -> 'direction_of_relative_north'
    'X Origin' -> 'x_origin'

    Cached: this is on the hot path of every ``IDFObject.__getattr__`` and
    ``__setattr__`` call. The pure regex pipeline costs ~300-660 ns; a
    cached lookup costs ~30 ns. The unique-input set is bounded by the
    schema's field-name vocabulary (a few thousand strings), well within
    the cache's working set.
    """
    return _FIELD_NAME_PATTERN.sub("_", idf_name.lower()).strip("_")

without_blank_slots(group)

A copy of group without its unset slots, which are stored as absent (idfkit#182).

Source code in idfkit/objects.py
def without_blank_slots(group: Mapping[str, Any]) -> dict[str, Any]:
    """A copy of *group* without its unset slots, which are stored as absent (idfkit#182)."""
    return {name: value for name, value in group.items() if not is_blank_slot(value)}