3

I have a situation where I want to use class instance declared in one file in second file. As a small example, see the below code :

How I am solving it as of now?

File2 (To be executed):

# Prog2:
from prog1 import *

cls1.dict["name"] = "John"

File1

# Prog1:

class Myclass(object):
    def __init__(self):
        self.dict = {}

cls1 = Myclass()

import prog2
print cls1.dict["name"]

Is there a better way of doing it?

sarbjit
  • 3,262
  • 9
  • 30
  • 52
  • possible duplicate of [Import instance of class from a different module](http://stackoverflow.com/questions/10942831/import-instance-of-class-from-a-different-module) – simonzack Sep 17 '13 at 13:45

2 Answers2

5

Why the circular dependency?

File 1:

# file 1
class MyClass(object):
    def __init__(self):
        self.dict = {}

cls1 = MyClass()
cls1.dict["name"] = "John"

File 2:

# file 2
from prog1 import cls1

print cls1.dict["name"]
>> "John"
zenpoy
  • 17,674
  • 8
  • 51
  • 84
2

The primary purpose of import is to make functionality available. It generally shouldn't be used as a method of executing a procedure. Your "prog2" should contain a function with a parameter:

def execute(instance):
    instance.dict["name"] = "John"

"prog1" can then call this with the appropriate instance:

import prog2

class Myclass(object):
    def __init__(self):
        self.dict = {}

cls1 = Myclass()

prog2.execute(cls1)
print cls1.dict["name"]
nmclean
  • 7,266
  • 2
  • 24
  • 37