1

I am converting a MATLAB script into python. The MATLAB script uses some kind of objects hierarchy for different input variables as in:

parameterA.subparameter1= A1;
parameterA.subparameter2= A2;

parameterB.subparameter1= B1;
parameterB.subparameter2= B2;

Where A1,A2,B1,B2 can all be strings and numbers. I wish to convert this to python and I have used

parameterA.subparameter1= A1
parameterA.subparameter2= A2

parameterB.subparameter1= B1
parameterB.subparameter2= B2

Now I am getting the error:

NameError: name 'parameterA' is not defined

I have tried to initialize them by using either parameterA,parameterB=[],[], which is not good because I want objects and not a list or parameterA,parameterB=set(),set() according to this post as well as some other solution.

Is this at all the correct approach? How do I initialize this structure? Is there a better way to do this?

havakok
  • 1,185
  • 2
  • 13
  • 45

2 Answers2

2

I would strongly suggest that you use dicts instead. These are efficient and versatile built-in objects in python.

parameterA  = {'subparameter1': A1} # definition
parameterA['subparameter2'] = A2 # update/assignment

parameterB = {'subparameter1': B1, 'subparameter2': B2}

As you can see you can access and modify values using square brackets. If you really insist on using attribute lookup, you could use types.SimpleNamespace:

from types import SimpleNamespace

parameterA = SimpleNamespace(subparameter1=A1)
parameterA.subparameter2 = A2

parameterB = SimpleNamespace(subparameter1=B1, subparameter2=B2)

The main reason I'd stick to dicts is the ease with which you can access keys dynamically. Only use a SimpleNamespace or something similar if you never access attributes programmatically, because your objects are more like a tool for grouping variables together. You can still access attributes programmatically, but it's uglier (and less idiomatic) than dict item lookup.

1

In the documentation for the Python Engine for MATLAB you can find a disambiguation of classes in MATLAB to classes in Python.

If you want to fit the documentation, you should replace structs in MATLAB with dictionaries in Python (like Andras Deak answered). If you want to keep the syntax for calling the structure fields with dot-operator you can also define classes in Python.

class parameterA: pass
class parameterB: pass

parameterA.subparameter1= A1
parameterA.subparameter2= A2

parameterB.subparameter1= B1
parameterB.subparameter2= B2

... But I also would recommend dictionaries.

Sven-Eric Krüger
  • 1,277
  • 12
  • 19