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?

2
  • np.zeros((2,2)) returns an array which you can't use in a format call like this. Commented Sep 16, 2016 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(). Commented Sep 16, 2016 at 18:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.