Should client_code be a formal Python package? Why [not]?

What I’m trying to do:
Run doctests in a module by running just that module. (Using a local copy of my source code, thanks to Anvil’s git integration.

What I’ve tried and what’s not working:
This usually works. Even in a sub-package. Until the subpackage module needs to import something from elsewhere in client_code. Then my local Python venv (v3.7) complains

builtins.ImportError: attempted relative import with no known parent package

Code Sample (from a subpackage):

# std lib
from datetime import date

# anvil labs
from ...anvil_labs.dataklasses import dataklass

...  # functions and classes with embedded docstrings here

# Run doctests in Wing IDE:
if __name__ == "__main__":  # We're running this module as a stand-alone program
    def _test():
        import doctest
        doctest.testmod()
    _test()

Clone link:
I’m seeking opinions, not debugging. Clone link not required.

Now, it seems that making client_code into an actual Python package, by giving it an actual __init__.py file, would probably solve the problem.

But if that was a good idea, wouldn’t Anvil have already put one there?

Instead, the parent folder of client_code is made a package, using its own __init__.py file, which reads as follows:

#
# This repository is an Anvil app. Learn more at https://anvil.works/
# To run the server-side code on your own machine, run:
# pip install anvil-uplink
# python -m anvil.run_app_via_uplink YourAppPackageName

__path__ = [__path__[0]+"/server_code", __path__[0]+"/client_code"]

So, my question is, what are the tradeoffs of giving client_code its own __init__.py file? Is it likely to break things for the Server or Client (or IDE)? It would be good to know before making an attempt, in case the consequences turn out to be really hard-to-handle.

1 Like

There have been no answers to this question, so I’ve started to experiment. I’m using Wing 9.1.2.1 as my desktop IDE, and have set my project’s Python Path to my Git workspace’s client_code folder. It’s able to import modules that are located within client_code.

But to get those modules to perform relative imports, I had to add a dummy __init__.py to my local client_code folder. This completely resolved the local (desktop) import error, as expected, and should allow me to run tests locally, on my desktop PC.

Update (2024-01-10): I did have to change some imports, where my own code was imported:

  • import Xfrom . import X
  • from X import Yfrom .X import Y

The new syntax seems to work just fine Anvil-side.

I am reluctant to commit and push this new __init__.py back to Anvil’s repository, since Anvil has worked perfectly well without it.

Does anyone else have experience in this matter, that they’d like to share, for me and other readers?