Difference between imports in server module vs server console

I thought that imports in the server console worked the same way as imports in a server module. However, I noticed a difference when I followed the steps below.

Does anyone understand why there is this inconsistency?

  1. Create App1
  2. Add a server module
  3. Add a function called hello
  4. Create App2
  5. Add App1 as dependency
  6. Create a server console
  7. The following works as expected - good!
    import App1
    App1.ServerModule1.hello()
    
  8. Add a server module
  9. Adding the same code to the server module says AttributeError: module 'App1' has no attribute 'ServerModule1 - bad!
4 Likes

Sorry for the long delay in replying. I’m just getting started researching Anvil’s Server Console tab/pane, and saw that this had no reply.

My best guess: after step 6, the console is still running the code as it was as of the point in time when the app began running.

This matches what happens when I run a Python app in Windows. The running App isn’t affected by changes to the App’s source code until the app is restarted. That’s when the new code gets recompiled (or fails to compile!), and loaded into memory for execution.

Interestingly, if in App2’s ServerModule1 you replace

import App1
App1.ServerModule1.hello()

with

from App1 import ServerModule1
ServerModule1.hello()

it works just fine!

It’s the order of imports
if you put

print(f"IMPORTING {__name__}")

At the top of your modules

You’ll see that the app server modules load
followed by the dependency server modules

IMPORTING App2.ServerModule1
IMPORTING App1.ServerModule1

So when you do (inside App2)

import App1
App1.ServerModule1.hello()

App1 does not yet have an attribute ServerModule1 because it has yet to be imported
You are using attribute access

whereas if you do

from App1 import ServerModule1
# or 
import App1.ServerModule1

We are using python’s import machinery to get the module


When you run the code in a server console
All modules have finished loading
so attribute access works

2 Likes