traitlets icon indicating copy to clipboard operation
traitlets copied to clipboard

If the default value for Unicode is traitlets.Undefined, then why is it type string when tested? How can you enforce CLI definition of an attribute if it self-massages to ""?

Open metaperl opened this issue 3 years ago • 2 comments

The code below shows that even though x is never given a value, it is an empty string.

Why do the docs for Unicode state default_value=traitlets.Undefined yet the type is string when tested?

from traitlets.config import Application
from traitlets import List, Dict, Integer, Unicode

class App(Application):

    aliases = {"x": "App.x", "y": "App.y"}
    x = Unicode().tag(config=True)
    y = Unicode().tag(config=True)

    def start(self):
        print(f"typex = {type(self.x)} val={self.x}")
        print(f"y={self.y}")


if __name__ == "__main__":
    App.launch_instance()

Output

typex = <class 'str'> val=
y=

metaperl avatar May 27 '22 11:05 metaperl

Even if allow-none=True, an undefined value is not defaulted to None. I changed one of the attributes to have allow_none=True and got this:


from traitlets.config import Application
from traitlets import List, Dict, Integer, Unicode, validate, TraitError


class App(Application):

    aliases = {"x": "App.x", "y": "App.y"}
    x = Unicode().tag(config=True)
    y = Integer(allow_none=True).tag(config=True)

    def start(self):
        print(f"typex = {type(self.x)} val={self.x}")
        print(f"typey = {type(self.y)} val={self.y}")

        self.x = "hi"
c:\programming\traitlets-lab\required-cli-argument>python required_cli.py 
python required_cli.py 
typex = <class 'str'> val=
typey = <class 'int'> val=0

if name == "main": App.launch_instance()

metaperl avatar May 28 '22 04:05 metaperl

While Undefined is the default value for the default_value argument to the __init__ function, it is never actually used as a value for a trait. It is a placeholder to indicate that there was no override of the default value. When no such override is given, this value is used:

https://github.com/ipython/traitlets/blob/e2c731ef72dd41d4be527d4d93dd87ccc409830d/traitlets/traitlets.py#L2368

I agree that it would be good if the docs surfaced the actual default value in a better way!

vidartf avatar Jun 08 '22 14:06 vidartf