An instance of a Python list.
| 3586 | |
| 3587 | |
| 3588 | class List(Container[t.List[T]]): |
| 3589 | """An instance of a Python list.""" |
| 3590 | |
| 3591 | klass = list # type:ignore[assignment] |
| 3592 | _cast_types: t.Any = (tuple,) |
| 3593 | |
| 3594 | def __init__( |
| 3595 | self, |
| 3596 | trait: t.List[T] | t.Tuple[T] | t.Set[T] | Sentinel | TraitType[T, t.Any] | None = None, |
| 3597 | default_value: t.List[T] | t.Tuple[T] | t.Set[T] | Sentinel | None = Undefined, |
| 3598 | minlen: int = 0, |
| 3599 | maxlen: int = sys.maxsize, |
| 3600 | **kwargs: t.Any, |
| 3601 | ) -> None: |
| 3602 | """Create a List trait type from a list, set, or tuple. |
| 3603 | |
| 3604 | The default value is created by doing ``list(default_value)``, |
| 3605 | which creates a copy of the ``default_value``. |
| 3606 | |
| 3607 | ``trait`` can be specified, which restricts the type of elements |
| 3608 | in the container to that TraitType. |
| 3609 | |
| 3610 | If only one arg is given and it is not a Trait, it is taken as |
| 3611 | ``default_value``: |
| 3612 | |
| 3613 | ``c = List([1, 2, 3])`` |
| 3614 | |
| 3615 | Parameters |
| 3616 | ---------- |
| 3617 | trait : TraitType [ optional ] |
| 3618 | the type for restricting the contents of the Container. |
| 3619 | If unspecified, types are not checked. |
| 3620 | default_value : SequenceType [ optional ] |
| 3621 | The default value for the Trait. Must be list/tuple/set, and |
| 3622 | will be cast to the container type. |
| 3623 | minlen : Int [ default 0 ] |
| 3624 | The minimum length of the input list |
| 3625 | maxlen : Int [ default sys.maxsize ] |
| 3626 | The maximum length of the input list |
| 3627 | """ |
| 3628 | self._maxlen = maxlen |
| 3629 | self._minlen = minlen |
| 3630 | super().__init__(trait=trait, default_value=default_value, **kwargs) |
| 3631 | |
| 3632 | def length_error(self, obj: t.Any, value: t.Any) -> None: |
| 3633 | e = ( |
| 3634 | "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." |
| 3635 | % (self.name, class_of(obj), self._minlen, self._maxlen, value) |
| 3636 | ) |
| 3637 | raise TraitError(e) |
| 3638 | |
| 3639 | def validate_elements(self, obj: t.Any, value: t.Any) -> t.Any: |
| 3640 | length = len(value) |
| 3641 | if length < self._minlen or length > self._maxlen: |
| 3642 | self.length_error(obj, value) |
| 3643 | |
| 3644 | return super().validate_elements(obj, value) |
| 3645 |
no outgoing calls
searching dependent graphs…