Can't access Py5Graphics screen from imported module

i’ve declared the ‘pg’ variable as global in all the modules.

then in my main module, i’ve begun with:

pg=None
def setup():
   global pg
   pg = py5.create_graphics(400,400)
   pg.begin_draw()
...

then in another imported module:

def translate(*args):
    global pg
    tx,ty,tz = args
    pg.translate(tx, ty, tz)
...

but when the “translate” function is called, the error is “pg is not defined”

How do I get “pg” to be recognized in the other modules?

thanks.

larry.c

1 Like

The reason a “.py” file is called a module is b/c everything defined inside a module isn’t automatically exported to other modules!

In order for a module to access stuff from other modules the former has to use the keyword import to get other modules’ global variables.

In your case, global variable pg is defined on your main module.
Seems like your other module is imported by the main module.

For such case, it’s better not risk circular-import, where 2 modules import stuff from each other!

As a workaround, you can change your 2nd module’s function translate() to accept a new parameter pg:

def translate(pg, *args): pg.translate(*args)

So, when your main module invoke translate() from the other module, pass its global pg as the 1st argument:

translate(pg, 100, -50, 0) # example
2 Likes

Thank you so much for your help.

Unfortunately, the workaround you suggest isn’t practical for me. I simplified the problem for the post. The module with the ‘translate’ function is actually called from a method of a class in another module and it gets quite convoluted among various modules. The global variable was the obvious solution. I don’t think I have circular imports. I’ve used imports and globals before w/o this problem. This just happens with the Py5Graphics screen. I was wondering if anyone else has run into this problem and if there’s a known solution.

If anyone is successfully accessing the Py5Graphics screen from several modules via a global variable, please let me know. That would indicate something else might be going wrong with my code. Thanks.

If a class requires an external-defined object, it should be passed to its constructor:

class CanvasDraw:
    def __init__(self, pg: Py5Graphics, *args):
        self.pg = pg

        # ...

    def translate(self, tx: float, ty: float, tz = 0.0):
        self.pg.translate(tx, ty, tz)

i agree that this covers getting pg into the object so the method can reference it, however, there’s still a problem with the instances of this class. When all the instances are defined, pg needs to be sent to the constructor. So i still have the problem of getting a reference to pg into that module where all the instances are declared.

After a little research, i discovered that global variables work just within modules not between them. (duh.) I put the global variables in a separate module and imported that into all the rest and that worked. so problem solved. thanks again.

1 Like