P3trus
P3trus

Reputation: 7225

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?

Upvotes: 3

Views: 256

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

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.

Upvotes: 1

Ankit Ranjan
Ankit Ranjan

Reputation: 114

What you can do is this:

Given a.py as:

var = 123

You could do:

>>> import a
>>> b = a
>>> b.var = 1234
>>> a.var
1234

You can't, however, implement b as its own module.

Upvotes: 0

Related Questions