Reputation: 1484
I am creating a text adventure engine, the engine itself is working great but I am trying to implement custom events for game creators with callbacks. I have a main.py
file that implements all of the game objects and builds the game. The problem is that I seem to be having trouble accessing the objects after I have instantiated them. have a look at this pseudo example code,
import engine
def build():
# create new item objects
key = engine.Item()
door = engine.Item(a = 0)
# set state of door
door.locked(requirement = key)
# CALLBACK FUNCTION
def on_door_unlock():
# ACCESSING THE ATTRIBUTE `a` IN `door` WORKS FINE
door.a = 1
# ACCESSING THE `key` OBJECT THROWS UnboundLocalError
del key
# assign callback to unlock event
door.on_unlock(on_door_unlock)
build()
engine.run()
My file is obviously much larger than this but it is just as simple and this code isolates my problem. I am able to access the attributes of any object, but when I try to use del keyword on an object itself I get UnboundLocalError: local variable 'key' referenced before assignment
everything seems to be placed in order. So what is the problem? How can i write callback functions that can access instances of the objects I create?
Upvotes: 3
Views: 354
Reputation: 15349
del key
means no more or less than "remove the name key
from the local scope". But this symbol has never been brought into the local scope of on_door_unlock
and even if it had, removing it from there would not do anything to the scope of build
.
One of many better approaches would be to create an explicitly-named registry of objects, for example as a dict
called all_objects
. Create the key
inside it. Remove key
from it by referring to it by name in your function.
ALL_OBJECTS = {}
def build():
ALL_OBJECTS[ 'copperKey' ] = engine.Item()
...
def on_door_unlock():
del ALL_OBJECTS[ 'copperKey' ]
...
Upvotes: 2