Search code examples
listsetsympylambdify

Keep the order of parameters fixed in sympy lambdify from free_symbols


When asking for a symbol .free_symbols I get something in curly braces (which is a set).

If I use this set as list of arguments for lambdify of sympy it seems it is converted into a list. This is hinted in the doc but I suggest a warning to be given here when this conversion is made. A good reason for this is that the ordering of the symbols may be altered in this conversion.

In my case _chiSquare.free_symbols gives {c_95_0, c_95_1} but list({'c_95_0', 'c_95_1'}) gives ['c_95_1', 'c_95_0']

I like to automate the making of numerical functions using .free_symbols but this is hard to work with if order of variable is changed without notice.

My question is how one is supposed to deal with free_symbols and lambdify in a way that arguments order is kept fixed.


Solution

  • I think it is better to keep track of the symbols explicitly rather than using free_symbols.

    If you must work from free_symbols then you can sort them to get a consistent ordering:

    In [3]: sorted((x*y).free_symbols, key=lambda s: s.name)
    Out[3]: [x, y]