4

SymPy and Python newbie here.

I run a script that iterates over a number of test files. Each file defines a set of symbols to use. At the end of each loop iteration, I want to delete all the symbols created earlier using the symbols() statement and nothing more, since I have other non-symbol variables around I am using.

I can't do del(x) and del(y) since each iteration will load a different set of symbols.

I can put a list of the symbols used in a list, or tuple, then at end of each iteration, go over the list of symbols that was created, and delete them one at a time using del But I can't get this to work.

Here is an example.

 from sympy import *
 x,y = symbols('x y')
 symbolsToDelete = (x,y) #I also tried symbolsToDelete = ('x','y')

 x=y**3
 y=99

 #now I want to delete all symbols defined above. But I can't
 #use del(x) or del(y) explicitly. So I tried

 for z0 in symbolsToDelete:
     del(z0)

But the above does not work, x and y are still there, with x=y**3 and y=99.

Again, I know I can do del(x) and del(y) at the end, but I am reading the names of the variables from a file, and the names are in a list.

I could only put the symbols in one variable like I did above, but do not know how to iterate over this tuple and then use del() on each entry to remove the corresponding symbol defined above at end of iteration using symbols command.

I do not know what the correct syntax should be.

I am using Python 3.6.5.

Rodrigo de Azevedo
  • 1,097
  • 9
  • 17
Nasser
  • 12,849
  • 6
  • 52
  • 104
  • As an aside: after `y=99` the Python variable `y` is not a SymPy symbol anymore, it's just a Python integer 99. The previous assignment `y = symbols('y')` is completely forgotten. It is unadvisable to think of SymPy symbols as "variables" because they _do not vary_: they are immutable, they cannot be "assigned a value". –  Jun 19 '18 at 03:12

1 Answers1

3

The reason your attempt did not work is explained in Delete all objects in a list - when looping over [x, y] you are deleting additional references to the objects (created in the process of iteration), while the original references stay in place.

You can delete x and y by accessing them via globals() as follows

symbolsToDelete = ('x', 'y')

for z0 in symbolsToDelete:
    del globals()[z0]