Application#
import traitlets
from traitlets.config import Application
Application._instance = None
Command line#
The core feature of the Application
class is that it behaves like traitlets.config.Config
, but it can override class properties from the command line arguments. You just jave to pass arguments like <class name>.<attribute>=<value>
when calling the prograr, just in the configuration script for the traitlets.config.Config
.
The following cell defines pythhon script that defines the inheritor of the Application
, that has the parameter
trait in it - consider how to set the value of parameter
.
%%writefile /tmp/my_application.py
import traitlets
from traitlets.config import Application
from traitlets.utils import cast_unicode
class MyApplication(Application):
parameter = traitlets.Unicode(
default_value="default",
config=True
)
if __name__ == "__main__":
MyApplication.launch_instance()
my_application = MyApplication.instance()
print(my_application.parameter)
Writing /tmp/my_application.py
The following cell calls the previously created scriptip without any additional arguments.
!python3 /tmp/my_application.py
default
As a result, the MyApplication.instance().parameter
will have a default value. The following cell runs the same script, but passes the value as a CLI argument.
!python3 /tmp/my_application.py --MyApplication.parameter="new value"
new value
Sometimes it usefull to intialise Application
from python code. You can do this by passing argumets as a list[str]
to the initialize
method.
import os
os.chdir("/tmp")
from my_application import MyApplication
app = MyApplication()
app.initialize(["--MyApplication.parameter", "new value"])
app.parameter
'new value'