From bb0a4daddc23a7eb351fe2a6a8242d48cc21ddda Mon Sep 17 00:00:00 2001 From: Diederik van der Boor Date: Sun, 7 Apr 2013 22:26:31 +0200 Subject: [PATCH] Optimize transmogrify() function, assign __class__ instead. --- polymorphic/query.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/polymorphic/query.py b/polymorphic/query.py index 164402d..9f2cb58 100644 --- a/polymorphic/query.py +++ b/polymorphic/query.py @@ -19,13 +19,20 @@ Polymorphic_QuerySet_objects_per_request = CHUNK_SIZE def transmogrify(cls, obj): """ - Clone an object as a different class, by instantiating that class and copying the __dict__ + Upcast a class to a different type without asking questions. """ - new = cls() - for k,v in obj.__dict__.items(): - new.__dict__[k] = v + if not '__init__' in obj.__dict__: + # Just assign __class__ to a different value. + new = obj + new.__class__ = cls + else: + # Run constructor, reassign values + new = cls() + for k,v in obj.__dict__.items(): + new.__dict__[k] = v return new + ################################################################################### ### PolymorphicQuerySet