0

I would like to write this:

x = 'something_{}'.format(1)
exec('{} = {}'.format(x,np.zeros((2,2))))

Problem: I get SyntaxError: invalid syntax and I don't know how to solve it.

Someone has an idea?

sisanared
  • 4,175
  • 2
  • 27
  • 42
JrCaspian
  • 297
  • 3
  • 15
  • np.zeros((2,2)) returns an array which you can't use in a `format` call like this. – elethan Sep 16 '16 at 16:52
  • Run `"{} = {}".format(x,np.zeros((2,2)))` first to see what its value is. You'll see there's an embedded `\n`, so you'll get an error passing it to `exec()`. – MattDMo Sep 16 '16 at 18:25

1 Answers1

1

String representation of numpy array is not a valid Python literal, therefore it cannot be evaled.

z = np.zeros((2,2))
str(z)  # [[ 0.  0.]\n [ 0.  0.]]  <-- invalid literal

Technically what you want may be achieved by using repr of object (but in general case it also won't work, e.g. when size of matrix is huge):

import numpy as np
x = 'something_{}'.format(1)
exec('{} = np.{!r}'.format(x, np.zeros((2,2))))

But what you really want to do is dynamic variable name, and that's a duplicate.

Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93