Get Icon Value
& Memoize
This next one isn’t mine, actually, but it is in my toolkit because when scripting Blender’s UI you sometimes just have to have an icon’s number, not its name.
However, even though Dzadik’s function works blindingly fast, it still strikes me as wrong to be scraping through all the icons every single time you want one when drawing your script’s UI panel. Better to look it up once.
So let’s also implement that singular lookup via some feel-good memoization.
import bpy
# Demeter Dzadik
# https://blender.stackexchange.com/a/299657/62918
def get_icon_value(icon_name: str) -> int:
icon_items = bpy.types.UILayout.bl_rna.functions["prop"].parameters["icon"].enum_items.items()
icon_dict = {tup[1].identifier : tup[1].value for tup in icon_items}
return icon_dict[icon_name]
# Memoize the only icon value(s) we need to look up ourselves
def memoize_icon(icon_name):
value = get_icon_value(icon_name)
globals()[icon_name] = lambda: value
return value
INFO = lambda: memoize_icon('INFO')
ERROR = lambda: memoize_icon('ERROR')
#etc