Python Forum

Full Version: Access instance of a class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

In my project there is a lot of different classes, created in different .py files.
To implement some feature I need to dynamically change a property of an instance of some class.
To test how to proceed I've tried to reproduced the case in significantly simplified case.

Here is 2 files:
class_instances_test_v0.py:
import weakref

class MyClass:

    _instances = set()

    def __init__(self, name):
        self.name = name
        self._instances.add(weakref.ref(self))

    @classmethod
    def getinstances(cls):
        dead = set()
        for ref in cls._instances:
            obj = ref()
            if obj is not None:
                yield obj
            else:
                dead.add(ref)
        cls._instances -= dead

a = MyClass("a")
b = MyClass("b")
c = MyClass("c")
class_instances_test_v0_test.py:
import class_instances_test_v0.MyClass
for obj in MyClass.getinstances():
    print(obj.name)
Here is error message:
[Image: class-instances-issue.jpg]

Any comments.
Thanks.
resolved, it was typo ...
Should be ...
from class_instances_test_v0 import MyClass

Actually it's a little bit more complicated.
Due to hierarchy of files/classes I get such error (AAA and BBB names are alternate names - for ease of understanding):
Error:
ImportError: cannot import name 'AAA' from partially initialized module 'AAA.AAA' (most likely due to a circular import) ({path-to-AAA_class}/AAA/AAA.py)
In file BBB.py I use such import instruction:
form AAA.AAA import AAA
Please write sensible code! What is the meaning of
from AAA.AAA import AAA
The AAA is the name related to project.
Well ... talking in different terms, it looks like this: the class AAA is defined in the file AAA.py. The file AAA.py is located in the project sub-folder AAA.

Error:
ImportError: cannot import name 'AAA' from partially initialized module 'AAA.AAA' (most likely due to a circular import) ({path-to-project-folder}/AAA/AAA.py)
Resolved:
Instead of
from AAA.AAA import AAA
use
import AAA.AAA
Then in code when the object of class AAA is referenced, use
AAA.AAA.AAA
There was probably a circular import. It would be best to find it: determine which import statements are executed, in which order.
Another workaround could be
import AAA.AAA
from AAA.AAA import AAA