Home > Back-end >  Scope of object in custom python package
Scope of object in custom python package

Time:12-21

I'm trying to make a 2d graphics package. I've made many attempts of finding the best structure for this, but I can't get it to work nicely. This is the current not working-setup:

I have the files init.py, scene.py and polygon.py

scene.py should init one single object, this object has an array where polygons are suppose to be stored in. A simple verison of this file looks like this:

class make_scene:
    def __init__(self,width,height,**kwargs):
        self.width = width
        self.height = height
        self.color = kwargs.get('color', '#ffffff')
        self.draw_elements = []

#init scene:
the_scene = make_scene(500, 250) 

polygon.py defines some objects to be drawn (circles, cubes etc):

class cube:
    def __init__(self,x,y,**kwargs):
        self.x = x
        self.y = y
        self.color = kwargs.get('color', '#000000') 
        the_scene.append(self)

init.py just imports the modules and some helper packages:

from .scene import *
from .polygon import *

However if I try to use this package the scene_file isn't scoped correctly:

cube(0,0,10,10)
>>> NameError: name 'the_scene' is not defined

I've been stuck, with multiple different architectures. I can get this to work If i keep it in one file which doesn't seem ideal.

Ideas to fix this or try a different architecture? I would LOVE your input.

CodePudding user response:

The issue seems to be that your polygon.py file doesn't know of the the_scene object. Python won't link the two together in a common file like your init.py.

Try importing the the_scene function from your polygon.py file like

from .polygon import the_scene
  • Related