Open aoeftiger opened 4 years ago
Hi Adrian, the default values were originally lists, but this results in a the following unwanted behaviour:
class Test(object):
def __init__(self, a=[]):
self.a = a
t1 = Test()
t2 = Test()
print(t1.a, t2.a)
# gives: "[] []"
# I append something to the first object
t1.a.append(3)
print(t1.a, t2.a)
# gives: "[3] [3]!!!!"
In fact the .a members of the two objects point to the same list!!!
Ah I see.. Since the tuples also lead to unwanted behaviour, I propose a different approach to resolve both problems at once..
Instantiating the list at the time of Test
definition leads to the same list for all Test
instances. If instead we use None
as default value and instantiate a list at the time of the __init__
call, your mentioned problem will be gone. This also fixes the above issue I have reported.
class Test(object):
def __init__(self, a=None):
if a is None:
self.a = []
else:
self.a = a
t1 = Test()
t2 = Test()
print(t1.a, t2.a)
# gives: "[] []"
# I append something to the first object
t1.a.append(3)
print(t1.a, t2.a)
# gives: "[3] []"
This would force us to write explicit constructors for the pysixtrack elements, which we wanted to avoid.
The tuple was a way of telling the user that he can rebind line.elements
but not append to it.
Btw line is not the only case, the multipole behaves in the same way.
Probably the problem can be solved more elegantly modifying the baseclasses...
... otherwise
Line.append_element
does not work.... throws a
... while initialising the kwargs
elements
andelement_names
with emptyList
instances instead of the default emptyTuple
instances resolves the problem: