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
- my callback function is written after the creation of the key object
- my callback is assigned to an event after the function is written
- I can access object attributes but can't access object itself.
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?
keyis not local (anddelis not that idiomatic in Python because most people would ratter use a shared object or collection as a container instead of a function's namespace).doorbecause it is not local either.delis concerned only with the local scope.del keymeans no more or less than "remove the namekeyfrom the local scope". But this symbol has never been brought into the local scope ofon_door_unlockand even if it had, removing it from there would not do anything to the scope ofbuild.