1
$\begingroup$

I need a instance of a class that is shared among nodes (singleton). Problem is I can't call the methods of it. Here is the problem isolated:

import bpy
from ... base_types.node import AnimationNode


class Singleton:

    def __call__(self):
        return self

    def bar(self):
        print("bar")


class Foo(bpy.types.Node, AnimationNode):
    bl_idname = "an_Foo"
    bl_label = "Foo"

    singleton = None

    def create(self):
        self.singleton = Singleton()

    def execute(self):
        self.singleton.bar()

Traceback (most recent call last): File "C:\Users\clankill3r\AppData\Roaming\Blender Foundation\Blender\2.77\scripts\addons\animation_nodes\execution\main_execution_unit.py", line 38, in executeUnit exec(self.executeCodeObject, self.executionData, self.executionData) File "execution: 'NodeTree'", line 4, in File "C:\Users\clankill3r\AppData\Roaming\Blender Foundation\Blender\2.77\scripts\addons\animation_nodes\nodes\serial\foo.py", line 24, in execute self.singleton.bar() AttributeError: 'NoneType' object has no attribute 'bar'

$\endgroup$

1 Answer 1

2
$\begingroup$

You can only store some specific property types on the nodes directly. These here: https://www.blender.org/api/blender_python_api_2_77_release/bpy.props.html

If you want to access the same variable from multiple nodes you can simply create the instance outside of the node like in this example:

import bpy
from ... base_types.node import AnimationNode

class Singleton:

    def __call__(self):
        return self

    def bar(self):
        print("bar")

# store the instance in the module namespace
singleton = Singleton()

class Foo(bpy.types.Node, AnimationNode):
    bl_idname = "an_Foo"
    bl_label = "Foo"

    singleton = None

    def create(self):
        pass

    def execute(self):
        # don't use 'self' because the singleton is in the module namespace
        singleton.bar()
$\endgroup$
1
  • $\begingroup$ Thanks man, you're a huge help speeding up my development :) $\endgroup$
    – clankill3r
    Commented Apr 5, 2016 at 16:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .