Skip to content

expand_dims(None) raises TypeError although None is its documented default #261

Open

Description

@petercorke

spatialmath.base.expand_dims declares dim with a default of None and documents it (":param dim: dimensions, defaults to None"), but calling it with that value raises:

>>> from spatialmath.base import expand_dims
>>> expand_dims()
TypeError: invalid input type
>>> expand_dims(None)
TypeError: invalid input type

Found while consolidating how RTB resolves a plot or world extent from several candidate sources, where "not given" is a normal state (RTB cannot rely on the default, so it special-cases None before every call).

Current callers already guard it

Every caller in SMTB tests for None before calling, which is the check the function could do itself:

# graphics.py, plotvol2
if dim is None:
    ax.autoscale(True)
else:
    dims = expand_dims(dim, 2)

The same is true of plotvol3, Animate and the dims argument handling in transforms2d.py.

Suggestion

Return None for None:

def expand_dims(dim: ArrayLike | None = None, nd: int = 2) -> NDArray | None:
    if dim is None:
        return None
    ...
  • None is passed through as "unspecified", and the caller decides what that means (autoscale, no limits, use the next candidate).
  • A default box such as [-1, 1, -1, 1] would be worse: it invents a value the caller did not give, and would make "not given" indistinguishable from "given as 1".
  • A wrong-length vector still raises ValueError, so malformed input still fails loudly.
  • The return type becomes NDArray | None, so strictly typed callers need a None check. The existing call sites already have one.

Alternatively, if raising is intended, the signature and docstring should drop the default so that the argument is required.

Tested

With this change SMTB's own suite is unchanged (342 passed before and after). All four SMTB call sites already guard None. One downstream use, in bdsim's GraphicsBlock handling of scale=, would see an invalid scale=None fail later rather than at construction.

Related: #255 (the getvector/getmatrix converters, same family of "accept the natural input" questions).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions