Search code examples
pythonimportmodulebeeware

Use own modules in beeware


I have a beeware project and also want to use my own modules in it like Models and Controllers. Also, a module which creates some objects I can test with.

But when I want to import the module to create the test objects and use the method it just throws an error:

ImportError: attempted relative import beyond top-level package

After some research, I know that the path (directory) structures, where I put my modules in, and where the package is, are important. But where ever I put the modules it has the same (or kinda like this) errors. But I can import my Models to create objects of these classes. I also can't decide where the start point of the briefcase is.

Here my structure currently:

/Project_Dir (own created)
/briefcase_project (created from briefcase)
/src
  /Models (own created)
  /app_directory (created from briefcase)
      here is the __main__.py and the __init__.py (the start point I guess) and the app.py (where beeware code is, and also my module import from Test)
  /Test (own created, here is a file with a method I want to call)

Sadly there is not so much stuff to find about beeware so I could find a solution.

Please help. Thanks ^^


Solution

  • I did the following to workaround the issue. The example using the Beeware Tutorial 2 source code is on Github

    .
    ├── __init__.py
    ├── __main__.py
    ├── app.py
    ├── mylib               <--- # my lib.
    │   ├── __init__.py
    │   └── testlib.py
    └── resources
        ├── __init__.py
        ├── beewarecustomlibexample.icns
        ├── beewarecustomlibexample.ico
        └── beewarecustomlibexample.png
    
    2 directories, 9 files
    
    

    The mylib/testlib.py

    def test(text: str) -> str:
        return f"Hello: {text}"
    

    In the app.py:

    import toga
    from toga.style import Pack
    from toga.style.pack import COLUMN, ROW
    
    from beewarecustomlibexample.mylib.testlib import test  # Import custom lib
    
    
    class BeewareCustomLibExample(toga.App):
        def startup(self):
    
            ...
    
        def say_hello(self, widget):
            # Calling my test method
            result = test(self.name_input.value)
            self.main_window.info_dialog("Test Dialog", result)
    
    
    def main():
        return BeewareCustomLibExample()
    

    The above is how I got it working. I've built it on MacOS and works fine.