Array values in Python

Hi Mark,

You asked:

I am now beginning to implement some array values in Python. I want those values to make it into the mworks event stream. I could set a single value in sequence to throw off events with all the array values. I’d prefer to put them into an array. I know MWorks variables can be dictionaries. Can they be arrays as well and does the Python bridge support that?

Yes and yes. MWorks has a native “list” type, and list values can be assigned to variables. The Python bridges convert MWorks lists into Python lists. Going the other direction (Python->MWorks), any sequence type (excluding strings and mappings) is converted to an MWorks list.

I’ve attached an example experiment and Python script that lets you interactively send values from Python to MWorks and then see what the values look like when sent back to Python. To try it, load the experiment (you don’t have to run it), and then run the script interactively at the command line. For example:

$ python -i list_var.py 
>>> set_var(1)
var = 1
>>> set_var(1.2)
var = 1.2
>>> set_var('abcd')
var = 'abcd'
>>> set_var([1,2,3])
var = [1, 2, 3]
>>> import numpy
>>> set_var(numpy.arange(4))
var = [0, 1, 2, 3]
>>> set_var({'a':1, 'b':2})
var = {'a': 1, 'b': 2}

Cheers,
Chris

Attachments:

[Reply from Mark]

Chris, this is great, thank you.

One more suggestion to add to the queue – It would be nice if the Python bridges had a function that could query the current value of any/all MWorks variables. I currently register a callback for every variable on startup; the function writes each new value into a mirroring python variable. That’s fragile. Python interface something like:

val = client.variable_curr_value('var')

Hi Mark,

There’s now some support for list values in experiment XML, too.

First, the default value of a variable can now be a list. The list items are specified using the same syntax as a selection variable’s value list, i.e. as a comma-separated sequence of scalar values (of any type) and/or range expressions.

Second, you can now use subscripting expressions to extract items from a list. That is, if the value of variable var is a list, then the expression var[n] now returns the nth element of the list.

The attached example experiment demonstrates both of these features.

Cheers,
Chris

Attachment: list_demo.xml (1.41 KB)

This is great. Thanks!
The subscripting is especially nice and will be useful.
I’ll probably start using this within a few weeks and will let you know how well it works.
M