Struct wrapping Python object

Please excuse me if this is a really noobie question, I'm just picking up the language... I'm trying to port an old GUI application I wrote in Python using Pyglet. My plan is currently, assuming there are no Mojo GUI library, reimplement all of the data processing in Mojo with an interface to Python to draw the UI. The first pattern I imagined would be something like:
# window.mojo
struct Window:
var _window: _something_

def __init__(inout self):
self._window = self.get_window()

def get_window(self) -> _something_:
# ... import pywindow stuff here
return pywindow.Window()
# window.mojo
struct Window:
var _window: _something_

def __init__(inout self):
self._window = self.get_window()

def get_window(self) -> _something_:
# ... import pywindow stuff here
return pywindow.Window()
where I have a Python module which defines a window:
# py/window.py
import pyglet

class Window(pyglet.window.Window):
...
# py/window.py
import pyglet

class Window(pyglet.window.Window):
...
The glaringly obvious question is, should I do this? Second is, how should I type the struct? And lastly, if this is possible, what are the implications of referencing a PythonObject in my Mojo struct?
3 Replies
NixonInnes
NixonInnesOP4mo ago
This seems to work, although I would prefer to use fn over def so I can understand / use static typing here
from python import Python, PythonObject

struct Window:
var _window: PythonObject

fn __init__(inout self):
try:
self._window = Window.get_window()
except e:
print("Failed to create window:", str(e))
self._window = None


@staticmethod
def get_window() -> PythonObject:
var window_module = Python.import_module("window")
return window_module.Window()
from python import Python, PythonObject

struct Window:
var _window: PythonObject

fn __init__(inout self):
try:
self._window = Window.get_window()
except e:
print("Failed to create window:", str(e))
self._window = None


@staticmethod
def get_window() -> PythonObject:
var window_module = Python.import_module("window")
return window_module.Window()
Ghosteez
Ghosteez4mo ago
does it make difference in performance or something? pure python vs mojo-python-imports
ModularBot
ModularBot4mo ago
Congrats @Ghosteez, you just advanced to level 1!
Want results from more Discord servers?
Add your server