Development Gotchas - sympy/sympy GitHub Wiki

These are things to watch for when writing SymPy routines.

defaultdict

defaultdict provides a nice way to not have to worry about keys being in a dictionary. But when you call a defaultdict with a new key, the key you used becomes a key in the defauldict -- if you need to use that key later and didn't use a SymPy expressions, trying to use that key might cause problems as in #18138.

don't

d = defaultdict(int)
...
v = d[1]  # called with key `1`
...
for k in d:
    print(k.simplify())  # fails

do

d = defaultdict(int)
...
v = d[S.One]
...
...
for k in d:
    print(k.simplify())  # ok

An alternative is to use the get method with a default value provided as in d.get(1, 0) -- but that defeats the convenience of using the defaultdict. Another option is to use the get method but check to see if you got None or not since d.get(1) will return None if 1 is not in the defaultdict. But that is also self-defeating.

  • remember to access with SymPy types if you need to use keys as SymPy objects later.