Access to the class instance in the library from two separate scripts in the project

I searched everything and could not find a suitable search query for useful results. I will try to explain this with a simple example (which is tested).

Suppose I have a small Python user library that contains only the following private class and a public instance:

#!/usr/bin/env python

class _MyClass(object):
    def __init__(self):
        self.val = "Default"

my_instance = _MyClass()

Now I have two more python files ('file_a' and 'file_b') that will eventually import this instance from my library, as shown below.

Full code in the file 'file_a':

#!/usr/bin/env python

from my_lib import my_instance

my_instance.val = "File A was here!"
import file_b
file_b.check_val()

Full code in the file 'file_b':

#!/usr/bin/env python

from my_lib import my_instance

def check_val():
    print "From 'file_b', my_instance.val is: {}".format(my_instance.val)

The result, if I only execute 'file_a' in a directory that also contains 'file_b' and 'my_lib', is:

From 'file_b', my_instance.val is: File A was here!

- , "file_b" , "file_a" ? , , 'file_a', ?

, , "MyClass" , "file_a" "file_b", , , - .

+4
2

:

1.

Python , , from foo import bar. sys.modules.

, file_a file_b my_lib my_instance.

2.

Python , .

from my_lib import my_instance

import my_lib
my_instance = my_lib.my_instance
del my_lib

, file_a, my_lib, file_b .


file_a file_b, .

file_a:

#!/usr/bin/env python

from my_lib import my_instance

my_instance.val = "File A was here!"

print "Inside file_a"
import sys
print id(sys.modules['my_lib']), sys.modules['my_lib'].my_instance, my_instance

import file_b
file_b.check_val()

file_b:

#!/usr/bin/env python

from my_lib import my_instance

print "Inside file_b"
import sys
print id(sys.modules['my_lib']), sys.modules['my_lib'].my_instance, my_instance


def check_val():
    print "From 'file_b', my_instance.val is: {}".format(my_instance.val)

( ):

>>> %run file_a.py

Inside file_a
4396461816 <my_lib._MyClass object at 0x106158ad0> <my_lib._MyClass object at 0x106158ad0>
Inside file_b
4396461816 <my_lib._MyClass object at 0x106158ad0> <my_lib._MyClass object at 0x106158ad0>
From 'file_b', my_instance.val is: File A was here!
+1

import my_lib , print(id(my_lib)), , .

import python , . . :

, import, - sys.modules. , , . , foo.bar.baz , sys.modules foo, foo.bar foo.bar.baz. .

sys.modules, , , , .

+1

Source: https://habr.com/ru/post/1693495/


All Articles