Refer to Data Table with square brackets notation in Uplink

Hi! Just starting to play around with Anvil. Finding it great so far!

From the documentation on interacting with Data Tables from Anvil Uplink, I noticed that the only means of refering to a table in the Data Table service is with the dot notation for object attributes:

from anvil.table import app_tables

app_tables.my_table.add_row(Foo='Bar')

It would be nicer if the same could be done using the dictionary-like square brackets notation, allowing greater flexibility to dynamically reference tables:

import anvil.server
from anvil.table import app_tables

my_dict1 = {'foo': 'bar'}
my_dict2 = {'fizz': 'buzz'}

def reusable_loader(table: str, things_to_add: dict):
    # do stuff, prepare export etc.
    app_tables[table].add_row(**things_to_add)  # doesn't work
    print('Done!')

anvil.server.connect('MY_TOKEN')
reusable_loader('foobar', my_dict1)
reusable_loader('fizzbuzz', my_dict2)

Playing with some introspection, I found the following (ugly) workaround:

# import app_tables, anvil.server, connect to app, etc.
import introspect
introspect.getmembers(app_table.cache)  # must be called first, don't know why
app_tables.cache['my_table'].add_row(Foo='Bar')

While that does work, I still find the app_tables['my_table'] notation would be cleaner and more intuitive.

Hi @bc.bernardo and welcome to the forum,

app_tables has a get method for just this kind of thing.
**(edit - this used to be a thing but was not public either and is no longer available)

app_tables.get('my_table')

I would also avoided using the cache since it’s not part of the public api as far as I’m aware.

You could use getattr(app_tables, 'my_table', None)

1 Like

Cool! I’ll try that.

Thanks for the fast response.

Interesting, @stucork. Where is that documented?

@joinlook - I take it back - it must have been a similar piece of interface that was not part of the public api that I’d found through introspection.

Rechecking it’s not available anymore (or never was and I imagined it)

Which is a good lesson - if it’s not documented then don’t rely on it :man_facepalming: !

getattr(app_tables, 'my_table', None)

Will work because it’s generic python and app_tables is a python object.
This would be the workaround for using table names as strings

1 Like