pythonclipsclipspy

clipspy: How to get slot dictionary of instance


The documentation contains this example code:

...
klass = env.find_class('MyClass')
instance = klass.new_instance('instance-name')
instance['One'] = 1
instance['Two'] = 2

Is there a built-in feature that gives me a dictionary of the slots and their values? Like the .Slots() method of pyclips.

Something like this:

def get_slot_dict(clips_instance):
    slot_dict = {}
    for s in clips_instance.instance_class.slots():
        slot_dict[s.name] = clips_instance[s.name]
    return slot_dict

Solution

  • Since clipspy 0.3.0 you can iterate over the objects metadata to construct your data structures.

    implied_fact = env.assert_string("(implied-fact 1 2 3)")
    list(implied_fact)
    
    [1, 2, 3]
    
    template_fact = env.assert_string("(template-fact (template-slot a-symbol))")
    
    list(template_fact)
    [('template-slot', 'a-symbol')]
    
    dict(template_fact)
    {'template-slot': 'a-symbol'}
    
    klass = env.find_class('MY-CLASS')
    instance = klass.new_instance('instance-name')
    instance['One'] = 1
    instance['Two'] = 2
    
    dict(instance)
    {'One': 1, 'Two': 2}