enthoughttraitsui

trait pickling with configure_traits


I use the first example code from traitsui documentation:

from traits.api import HasTraits, Str, Int
import traitsui

class SimpleEmployee(HasTraits):
    first_name = Str
    last_name = Str
    department = Str

    employee_number = Str
    salary = Int

sam = SimpleEmployee()
sam.configure_traits(filename='/Volumes/FAT/Python/Tests/test.dat')

The only change is a filename specification in configure_traits().

1 - When the file is nonexistent, a new file is not created. It would be nice to have such a behavior.

2 - How to create this file? Using

import pickle

pickle.dump( sam, open( '/Volumes/FAT/Python/Tests/test.dat', "wb" ) )

creates the file

ctraits.traits
__newobj__
p0
(c__main__
SimpleEmployee
p1
tp2
Rp3
(dp4
S'salary'
p5
I0
sS'__traits_version__'
p6
S'4.5.0'
p7
sS'first_name'
p8
S''
p9
sS'last_name'
p10
g9
sS'employee_number'
p11
g9
sS'department'
p12
VManagement
p13
sb.

with 'Management' as the department (I entered this value in the dialog, of course).

But running again

sam.configure_traits(filename='/Volumes/FAT/Python/Tests/test.dat')

changing the department field and clicking OK to close the dialog does not change the file content (as it is supposed to do from the doc).

(MacOS X)


Solution

  • I found what was going wrong: configure_traits() should be made to run in modal mode:

    from traits.api import HasTraits, Str, Int
    from traitsui.api import View, OKCancelButtons
    
    class SimpleEmployee(HasTraits):
        first_name = Str
        last_name = Str
        department = Str
    
        employee_number = Str
        salary = Int
    
    sam = SimpleEmployee()
    sam.configure_traits(filename='/Volumes/FAT/Python/Tests/test.dat',kind='modal')    
    

    now works OK.

    As for my question #1, yes, a new file is created if necessary