Issue
I'm migrating my Python based engine to Numpy in hopes of better performance. Previously I used my own vector3 class: With it I could use use conditional variable assignments in the following form, with settings["size"]
being the provided array if present in the settings dictionary otherwise 0,0,0
as the fallback.
self.size = "size" in settings and settings["size"] or vec3(0, 0, 0)
Now I am instead using:
self.size = "size" in settings and settings["size"] or np.array([0, 0, 0])
But this introduces a new error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
What is the correct way of doing inline conditional assignments with numpy arrays, where it's checked whether the value exists and a default is set is not?
Solution
There are two ways to do this. The and/or thing is dangerous because of the way Python handles the types, so this should work:
self.size = settings['size'] if "size" in settings else np.array([0,0,0])
Or:
self.size = settings.get('size',np.array([0,0,0])
Or even:
self.size = settings.get('size',np.zeros(3))
Answered By - Tim Roberts
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.