0

I have this class

class TestEvent(object)
    value = None

I want to get a duplicate of this class so it isn't referenced but when i try using the copy library the variables are always referenced:

>>> clsOne = TestEvent
>>> clsTwo = copy.deepcopy(TestEvent)
>>> clsOne.value = "hello motto"
>>> clsTwo.value
"hello motto"

This is also the case with copy.copy. Can someone show me how to get a duplicate of this class?

DavidG
  • 24,279
  • 14
  • 89
  • 82
Kirk Douglas Jr
  • 598
  • 5
  • 10
  • Could you expand on the context - *why* do you need to create a copy of the class? – jonrsharpe May 03 '18 at 21:42
  • For unit testing. I'm making a class inherited by `unittest.TestResult` to keep track of results in my own way. I want to be able to run multiple of these in using threads, but since this class is always referenced the results end up mixed up. – Kirk Douglas Jr May 03 '18 at 21:44
  • But why are you storing attributes on the _class_, and not on _instances_? – Aran-Fey May 03 '18 at 21:45
  • The example was just to the show the issue i'm having, unitttest create a new instance of the class but for some reason it's changes are being referenced back to the class itself. Something i'm not skilled enough to understand yet. – Kirk Douglas Jr May 03 '18 at 21:57

1 Answers1

2

copy.copy() and friends will return the value unchanged when you pass a class.

You can use type() instead:

# shallow copy of the namespace
new_cls = type(cls.__name__, cls.__bases__, dict(cls.__dict__))

or:

# deep copy of the namespace
new_cls = type(cls.__name__, cls.__bases__, copy.deepcopy(dict(cls.__dict__)))
Andrea Corbellini
  • 17,339
  • 3
  • 53
  • 69