@@ -265,7 +265,7 @@ the table.
265265.. index :: Directory(), Disallow, Either(), Enum()
266266.. index :: Event(), Expression(), false, File()
267267.. index :: Instance(), List(), 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()
@@ -351,6 +351,8 @@ the table.
351351+------------------+----------------------------------------------------------+
352352| Module | Module([\*\*\ *metadata *]) |
353353+------------------+----------------------------------------------------------+
354+ | Optional | Optional(*trait *\ [, \*\*\ *metadata *]) |
355+ +------------------+----------------------------------------------------------+
354356| Password | Password([*value * = '', *minlen * = 0, *maxlen * = |
355357| | sys.maxsize, *regex * = '', \*\*\ *metadata *]) |
356358+------------------+----------------------------------------------------------+
@@ -696,6 +698,45 @@ The following example illustrates the difference between `Either` and `Union`::
696698 ... primes = Union([2], None, {'3':6}, 5, 7, 11)
697699 ValueError: Union trait declaration expects a trait type or an instance of trait type or None, but got [2] instead
698700
701+ .. index :: Optional trait
702+
703+ .. _optional :
704+
705+ Optional
706+ ::::::::
707+ The Optional trait is a shorthand for ``Union(None, *trait*) ``. It allows
708+ the value of the trait to be either None or a specified type. The default
709+ value of the trait is None unless specified by ``default_value ``.
710+
711+ .. index ::
712+ pair: Optional trait; examples
713+
714+ The following is an example of using Optional::
715+
716+ # optional.py --- Example of Optional predefined trait
717+
718+ from traits.api import HasTraits, Optional, Str
719+
720+ class Person(HasTraits):
721+ name = Str
722+ nickname = Optional(Str)
723+
724+ This example defines a ``Person `` with a ``name `` and an optional ``nickname ``.
725+ Their ``nickname `` can be ``None `` or a string. For example::
726+
727+ >>> from traits.api import HasTraits, Optional, Str
728+ >>> class Person(HasTraits):
729+ ... name = Str
730+ ... nickname = Optional(Str)
731+ ...
732+ >>> joseph = Person(name="Joseph")
733+ >>> # Joseph has no nickname
734+ >>> joseph.nickname is None
735+ True
736+ >>> joseph.nickname = "Joe"
737+ >>> joseph.nickname
738+ 'Joe'
739+
699740.. index :: Either trait
700741
701742.. _either :
0 commit comments