What is ComponentTag?

This code on Form1.__init__():

print type(self.link_1.tag)
self.link_1.tag = 'yo'
print type(self.link_1.tag)

creates this output:

<class '__builtin__.staticmethod.ComponentTag'>
<type 'str'>

Why isn’t the default value of tag just None?
What is ComponentTag for?

It’s a general-purpose attribute on all components for storing useful information. It’s documented (rather briefly) here in the reference docs.

By default, it’s an object that lets to assign to any arbitrary attribute (even if that attribute doesn’t exist yet):

    self.label_1.tag.flavour = 'vanilla'
    self.label_1.tag.texture = 'fuzzy'
    self.label_1.tag.favourite_passtime = 'kayaking'

You can also assign another object to it, as you found by assigning a string to it:

    self.label_1.tag = 'yo'

So to answer your question “what is ComponentTag for?”, it’s a class that enables that magic ‘create attributes by assigning to them’ behaviour.

Here’s a quick example app that includes the code above:

https://anvil.works/build#clone:AMUHWEYKW2S4V7OS=LBQZ5WL5FQRHGLNE3RWGLU26

1 Like

Mmmh…

Did the behavior of ComponentTag change recently?

An app recently started crashing while reading component.tag.something before defining it.

I think that the app used to work and component.tag.something_never_defined == None.

Not to my knowledge! That’s always been the behaviour - component tags are standard Python objects, and their attributes do not exist before you create them.

This morning we have fixed the app that started crashing yesterday morning. We replaced all the instances of .tag.xxx with .tag['xxx'] and added the initialization .tag = {}.

I can’t test it now, but looking at the diff of the last check-in and looking at the app log, it looks like the line shown below was working until yesterday at 7:56 (but I don’t know if the user did hit any of the broken lines) and stopped working at 11:00. After 11 the app log has a bunch of crashes until the fix this morning.

The line causing the crash was this:

if ele.tag.name == 'machine_dd':

The error message from the app log is this:

AttributeError: 'ComponentTag' object has no attribute 'name_$rn$'at [Main, line 99](javascript:void(0))

I think it was crashing when ele.tag.name was undefined, while it wasn’t crashing until yesterday.

Bump. I also experienced undefined tags causing this AttributeError.