0

I often have a set of symbols I'd like to define at the beginning of a chunk of sympy code. The 'boneheaded' approach is

from sympy import symbols
alpha, beta, delta, gamma = symbols("alpha,beta,delta,gamma")

but this feels terribly wasteful/redundant. I think the answers to this question get me most of the way there; ideally I'd like a function where I could say

foo(("alpha", "beta", "delta", "gamma"))

(or possibly foo("alpha", "beta", "delta", "gamma"), whichever seems to be more Pythonic) and have these symbols added to my environment.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • What about [`var()`](https://docs.sympy.org/latest/modules/core.html#var) ? See also [Difference between var and Symbol in sympy](https://stackoverflow.com/questions/42897901/difference-between-var-and-symbol-in-sympy) – JohanC Apr 26 '22 at 23:15
  • As explained in the link, `sympy.var` does what you want. But look at its code - it does `symbols`, followed by 'injecting' the Python variables into the `globals`. So there's nothing wasteful about your use of `symbols` - unless you are paying for keystrokes :) Generally we discourage creating python variables dynamically. Code is more readable, and debuggable if all variable assignments are explicit. – hpaulj Apr 26 '22 at 23:24
  • I take the general point about best practices (in the [r] tag we're constantly telling people not to dynamically generate variables but to use lists etc. instead). However, since I usually use `sympy` in very interactive mode, I think I like this version ... (dumb/newbie question: how do I view the code of `sympy.var` ? Do I need https://stackoverflow.com/questions/1562759/can-python-print-a-function-definition ? – Ben Bolker Apr 26 '22 at 23:29
  • @JohanC, if you want to post that as an answer I'll accept it ... – Ben Bolker Apr 26 '22 at 23:31
  • You may just use `isympy -I` with ipython / jupyter installed... – Arnie97 Dec 19 '22 at 17:19

1 Answers1

0

I think this (a slight modification of the examples given in the linked question) will do it:

def makesyms(s):
   globals().update(dict(zip(s, symbols(s))))
   return None

makesyms(("a", "b", "c"))

or

def makesyms2(*s):
   globals().update(dict(zip(s, symbols(s))))
   return None

makesyms2("A", "B", "C")
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453