@@ -265,7 +265,7 @@ the table.
265265.. index :: Directory(), Disallow, Either(), Enum()
266266.. index :: Event(), Expression(), false, File()
267267.. index :: Instance(), List(), Method(), Module()
268- .. index :: Password(), Property(), Python()
268+ .. index :: Optional(), Password(), Property(), Python()
269269.. index :: PythonValue(), Range(), ReadOnly(), Regex()
270270.. index :: Set() String(), This, Time()
271271.. index :: ToolbarButton(), true, Tuple(), Type()
@@ -355,6 +355,8 @@ the table.
355355+------------------+----------------------------------------------------------+
356356| Module | Module([\*\*\ *metadata *]) |
357357+------------------+----------------------------------------------------------+
358+ | Optional | Optional(*trait *\ [, \*\*\ *metadata *]) |
359+ +------------------+----------------------------------------------------------+
358360| Password | Password([*value * = '', *minlen * = 0, *maxlen * = |
359361| | sys.maxsize, *regex * = '', \*\*\ *metadata *]) |
360362+------------------+----------------------------------------------------------+
@@ -700,6 +702,45 @@ The following example illustrates the difference between `Either` and `Union`::
700702 ... primes = Union([2], None, {'3':6}, 5, 7, 11)
701703 ValueError: Union trait declaration expects a trait type or an instance of trait type or None, but got [2] instead
702704
705+ .. index :: Optional trait
706+
707+ .. _optional :
708+
709+ Optional
710+ ::::::::
711+ The Optional trait is a shorthand for ``Union(None, *trait*) ``. It allows
712+ the value of the trait to be either None or a specified type. The default
713+ value of the trait is None unless specified by ``default_value ``.
714+
715+ .. index ::
716+ pair: Optional trait; examples
717+
718+ The following is an example of using Optional::
719+
720+ # optional.py --- Example of Optional predefined trait
721+
722+ from traits.api import HasTraits, Optional, Str
723+
724+ class Person(HasTraits):
725+ name = Str
726+ nickname = Optional(Str)
727+
728+ This example defines a ``Person `` with a ``name `` and an optional ``nickname ``.
729+ Their ``nickname `` can be ``None `` or a string. For example::
730+
731+ >>> from traits.api import HasTraits, Optional, Str
732+ >>> class Person(HasTraits):
733+ ... name = Str
734+ ... nickname = Optional(Str)
735+ ...
736+ >>> joseph = Person(name="Joseph")
737+ >>> # Joseph has no nickname
738+ >>> joseph.nickname is None
739+ True
740+ >>> joseph.nickname = "Joe"
741+ >>> joseph.nickname
742+ 'Joe'
743+
703744.. index :: Either trait
704745
705746.. _either :
0 commit comments