BLOG - Lazy Loading Modules - Python Corner

Here’s a blog post I’ve been working on:

It’s a little something that’s recently been made available in skulpt (:wink:) and a neat way to lazy load attributes to your anvil apps.

I have a few more article ideas like this one so it could turn into a mini series… hope you learn something new!

7 Likes

Very nice! That’s going straight into the ORM library…

2 Likes

That’s very timely, I had just started caching some rarely changing data on the client (also drop down list contents). I’m still at the point where integrating these techniques won’t be a huge refactoring project.

1 Like

This is great!

I hoped that defining __dir__ would affect the autocompletion, but… oh, well. (Maybe it’s a feature coming up soon? :slight_smile:)

Here is my slightly modified version of the Globals module, which solves the problem with parameters with value None and follows the “ask forgiveness not permission” pythonic mantra:

import anvil.server

__dir__ = ['param1', 'param2', 'param3']
parameters = {}

def __getattr__(name):
  try:
    return parameters[name]
  except KeyError:
    try:
      value = anvil.server.call('get_' + name)
      parameters[name] = value
      return value
    except anvil.server.NoServerFunctionError:
      raise NameError(f"name '{name}' is not defined")

It doesn’t cache the missing variables, which means that if the client code looks for a missing variable twice, there will be a second useless round trip, but I don’t think that’s a problem that I’m going to have.

EDIT
I added the __dir__ line because it works now (thanks Meredydd).

2 Likes

I hoped that defining __dir__ would affect the autocompletion, but… oh, well. (Maybe it’s a feature coming up soon? :slight_smile:)

What a good idea! That’s done (when __dir__ is a literal list). Expect to see it sometime this week.

edit (May 2021):
There’s a mistake in the article above which we’ve noticed and will be corrected
The protocol for overriding __dir__ is to to write a function that returns a list of strings.
The autocompleter will include attributes returned from a __dir__ function
(assuming the function returns a literal list)

5 Likes

Thanks for noticing and acting upon my veiled request :slight_smile:

I edited the code on my previous post to include the __dir__ line.

1 Like