Detecting whether anvil is running in the browser (typing)

Hi, I am using PyCharm mostly, and it has a way to type-check your client code by writing something like:

catalog = dict()  # type: dict[str, Union[Car, Truck, Motorbike]]

Only problem is that client python has no typing module, so PyCharm type-checking will not work unless I have :

from typing import Union

Is there some way to check if I am testing my client_code on my laptop with a

if not RUNNING_ANVIL_CLIENT:
  from typing import Union

at the moment I do:

try:
  from typing import Union
except ImportError:
  pass
1 Like

I do this for the forms:

if anvil.server.context.type != 'browser':
    # running on server
    from typing import List, Optional, Union, Tuple, Dict

And this for the server modules:

if anvil.server.context.type == 'uplink':
    # running tests on pc
    from client_code.Status import Status
else:
    # running on Anvil server
    from .Status import Status

EDIT
I just realized that you use the comments for type hinting with PyCharm.

You don’t need to use comments, you can use the standard Python syntax.

Skulpt doesn’t import typing, but doesn’t do anything with the type hints, perhaps the parser just ignores them. I just checked one of my apps and these are two lines from a module imported both on the client and on the server side:

self._crates: Dict[str, Crate] = {}
self._truck_versions: Optional[List[Project]] = None
3 Likes

The typing module would be a nice addition client side.
As a workaround you can create a temporary solution for when your anvil code is running in the browser.

See this post:

1 Like

Pycharm has its own in-built type checker that can use Python 2 mypy conventions. This is perfect for type checking the client side code. See PyCharm type checking. I have been using this feature and it has helped a lot.

When client module has

anvil.server.context

does it make a server call?

No, that’s a very fast check.

Here is more detail on type checking client code locally.
PEP 484