Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a module

Let's assume I've got two modules a.py and b.py. bshould be a copy of a. Let's assume this is the content of a:

#a.py
class Original(object):
    name = 'original'

The most obvious way to duplicate a would be something like this:

#b.py
from a import *

But this does not really copy a, e.g.

>>>import a, b
>>>#this changes a.Original.name as well
>>>b.Original.name = 'FOOBAR'
>>>a.Original.name == 'FOOBAR'
True

So my question is How do I make a real copy?

like image 944
P3trus Avatar asked Nov 22 '25 17:11

P3trus


1 Answers

I think you'll have to update the globals() dictionary of b.py with the deepcopy of globals() from a.py. And as we can't copy a class object using deepcopy, So, you'll create a new class using type() for all classes present inside a.py.

from copy import deepcopy
import types
import a

def class_c(c):
    #To create a copy of class object
    return type(c.__name__, c.__bases__, dict(c.__dict__))

filtered_a_dict = {k:v for k, v in a.__dict__.items()
                                   if not (k.startswith('__') and k.endswith('__'))}

globals().update({k:deepcopy(v) if not isinstance(v, types.TypeType) 
                               else class_c(v) for k, v in filtered_a_dict.items()})

del a

Demo:

>>> import a, b
>>> b.Original.name = 'bar'
>>> a.Original.name == 'bar'
False

Note that we don't use modules for such purposes, a class is the right tool for such things.

like image 76
Ashwini Chaudhary Avatar answered Nov 25 '25 06:11

Ashwini Chaudhary