Re: Copy/Deepcopy C# lists

Stéphane Lozier

copy/deepcopy for "unknown" types use pickling and it looks like pickling of strongly typed generic lists using custom Python classes doesn't work properly (it becomes List[Object_1$1] instead of List[MyClass]). Converting to a Python list is one option, otherwise, you can try using the slicing notation (e.g. l2 = l1[:]) or a .NET method (e.g. List constructor or the .ToList() method of Linq).


On Tue, Dec 17, 2019 at 8:24 PM <christoph.neyer@...> wrote:

Is there a way to copy C# typed lists that I'm missing? Currently, the builtin copy/deepcopy fails, but I can workaround it by moving the items to a python list, deepcopying it and casting it back. 



import copy
from System.Collections.Generic import List
class MyClass(object):
def __init__(self, my_attr=10):
self.x = my_attr

c_sharp_list = List[MyClass]([MyClass(my_attr=0), MyClass(my_attr=1)])
print('C#: {}'.format(c_sharp_list))
# this fails
copied_list = copy.deepcopy(c_sharp_list)
except Exception as e:
print("failed to deep copy: {}".format(e))

# workaround
# copy the List to a python list
python_list = [x for x in c_sharp_list]
print('Uncopied python list: {}'.format(python_list))
copied_python_list = copy.deepcopy(python_list)
print('Copied python list: {}'.format(copied_python_list))
# cast it back to a typed list
copied_list = List[MyClass](copied_python_list)
print('Copied C# list: {}'.format(copied_list))




C#: List[Object_1$1]([<MyClass object at 0x0000000000000290>, <MyClass object at 0x0000000000000291>])

failed to deep copy: Type 'IronPython.NewTypes.System.Object_1$1' in Assembly 'Snippets.scripting, Version=, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

Uncopied python list: [<MyClass object at 0x0000000000000290>, <MyClass object at 0x0000000000000291>]

Copied python list: [<MyClass object at 0x000000000000029D>, <MyClass object at 0x000000000000029E>]

Copied C# list: List[Object_1$1]([<MyClass object at 0x000000000000029D>, <MyClass object at 0x000000000000029E>])


Join to automatically receive all group messages.