Home > OS >  In Python3, is it possible to merge two objects into a new object so that references to the original
In Python3, is it possible to merge two objects into a new object so that references to the original

Time:08-29

Suppose I have a dictionary d = {1: A, 2: A, 3: B, 4: B} and then I have an operation that merges object A and object B into a new object say C = merge(A, B). Is it possible to make all the keys that referenced A and B to now reference C in constant time?

# pseudocode
d = {1: A, 2: A, 3: B, 4: B}
C = merge(A, B)
# At this point I want (d[1] is C) == True and (d[3] is C) == True

Is something like this possible in Python3?

enter image description here

CodePudding user response:

Ok so what I'm saying is super hacky and I would not recommend doing something like this at all. Use this at your own risk.

First of all, you should know that there are no real way of combing two objects with each other as the objects themselves are quite different from one another.
However, by defining your own merge function, there is a work around it. See the code below:

import sys
# define the merge function as merge

def merge_obj( obj_a , obj_b , new_object_name ):
    new_object = merge(obj_a , obj_b)
    flag_obj_a = True
    flag_obj_b = True

    for instance_name in dir(sys.modules[__name__]):

        if flag_obj_a and getattr(sys.modules[__name__] , instance_name) == obj_a:
            setattr(sys.modules[__name__] , instance_name , new_object)
            flag_obj_a = False
        if flag_obj_b and getattr(sys.modules[__name__] , instance_name) == obj_b:
            setattr(sys.modules[__name__] , instance_name , new_object)
            flag_obj_b = False

Now you can use the merge_obj to merge your objects and make sure that in the original module, both previous objects get updated.

Note that this only works for the objects that are defined inside a modeule.

CodePudding user response:

You have to do this manually, probably using a separate dict that represents the relation implied by the merge.

d = {1: A, 2: A, 3: B, 4: B}
C = merge(A, B)
merger = {A: C, B: C}
d = {k: merger[v] for k, v in d.items()}

The references to A and B don't "know" anything about the process that creates C.

In particular, merge itself doesn't know who else might have references to its arguments, and certainly wouldn't know how to update d if it did.

  • Related