0

In python, I'm trying to come up with a good way to add a variable that dynamically replicates the primary object every time it encounters a Variable class as one of the inputs. So if the variable class has 2 different input values, it will create 2 objects. For example:

objects = Object(arg1=10, arg2=Variable([10, 20]))

output:

objects = [Object(arg1=10, arg2=10), Object(arg1=10, arg2=20)]

The tricky part is that the Variable class could be any input for any sub-object, too. For example

objects = Object(subobject1=Subobject(arg1=Variable([10, 20]))

output:

objects = [Object(subobject1=Subobject(arg1=10)), Object(subobject1=Subobject(arg1=20))]

This is for a Blockly project, which is a visual programming language that generates python code from blocks. In that format, its sometimes more natural to use a variable as an input instead of wrapping all of the code in a loop. That's the reason why I'm trying to awkwardly inject a variable into the middle of a section of code instead of just doing a loop.

1 Answer 1

2

You're expecting far too much work to be done inside Object.__new__ or Object.__init__, as it would appear that arguments used to create one of its arguments should be taken into consideration.

Be explicit, and use a list comprehension to state what you mean.

objects = [Object(arg1=10, arg2=x) for x in [10, 20]]

or

objects = [Object(subobject=Subobject(arg1=x)) for x in [10, 20]]

If you want some other construct in Blockly, that's a problem to solve in Blockly, not in Python.

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

2 Comments

I wouldn't know ahead of time whether arg2=10, or arg2=Variable([10, 20]), or arg2=Variable([Object1, Object2]), so I couldn't just create the objects in a predefined loop. I won't know ahead of time what the users will want to enter as variables, or which inputs will be Variables. Also, the Variable could be any one of 20 or more different inputs, and I have to keep track of them all somehow, so having every input as a looped over list would be pretty messy, I think. I think I'm looking for something like a director or constructor class that finds Variable objects and then constructs.
That's part of your problem. Object doesn't and shouldn't know about what argument is being passed to Subobject. At best, it can get information from the subobject argument that the Subobject explicitly makes available, and maybe use that to make a decision about what to return, but you appear to be trying to have your code make decisions that the caller should be making.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.