Skip to content

Multiple alternatives validator #1214

@brunokim

Description

@brunokim

I'd like to validate that a field can be of several types, one of which is an iterator.

from attrs.validator import instance_of

@define
class C:
  x: A | B | tuple[int, ...] = field(validator=instance_of((A, B, tuple)))

I can use instance_of to check the outer type tuple, but I can't use deep_iterable to validate that they are indeed the element type int.

Since we already have validators and_ and not_, it may make sense to also add or_, so that I can represent this with

from attrs.validator import instance_of, deep_iterable, or_

@define
class C:
  x: A | B | tuple[int, ...] = field(
    validator=or_(
      instance_of((A, B)),
      deep_iterable(instance_of(int))))

For comparison, this is how I'm writing a custom validator

from attrs.validator import instance_of, deep_iterable

@define
class C:
  x: A | B | tuple[int, ...] = field()

  @x.validator
  def _validate_x(self, attr, value):
    v1 = instance_of((A, B))
    v2 = deep_iterable(instance_of(int))
    try:
      v1(self, attr, value)
    except TypeError:
      v2(self, attr, value)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions