Execution, user properties and identity¶
Names on the top-level pme package that run Python code in PME’s standard
namespace, read and write user properties, and identify the running add-on.
Names available inside slot code (Command, Custom, Poll) are listed in
Scripting.
Name |
Purpose |
|---|---|
Runs code and returns |
|
Evaluates one expression and returns its value. |
|
Checks syntax without running the code. Returns
|
|
Reads or writes user properties stored in Addon Preferences. |
|
Module name of the running PME add-on. |
|
PME’s add-on preferences. |
|
Checks the format of a menu UID. |
|
|
PME1 execution context, kept for backward compatibility. |
Standard namespace¶
execute() and evaluate() run code in a dictionary built from
PME’s execution context on each call.
Names |
Value |
|---|---|
|
Every name in |
|
PME’s add-on preferences, the same object as |
|
|
|
The current values of |
|
The event PME is handling. Absent when PME is not handling an event. |
Names in |
Added last. A name in |
Each call builds a new dictionary. Names that the code assigns at top level are not kept for the next call. Objects reached through the namespace keep their changes, for example attributes set on
U.Neither function sets an event, a layout or a slot. Names that describe a menu invocation, such as
L,delta,drag_xanddrag_y, hold the values left in PME’s execution context, or are absent.While PME runs the startup scripts in
scripts/autorunandscripts/registerduring add-on loading, neither function runs code. PME records the call as a failure of the running startup script and does not run the remaining startup scripts.
Code execution¶
- pme.execute(code, *, extra_globals=None)¶
Run Python code in the standard namespace and report whether it completed.
An exception raised by the code is caught and returned as text. It is not printed, and no traceback is kept.
- Parameters:
- Returns:
The outcome of the run.
- Return type:
Example
result = pme.execute("bpy.ops.mesh.primitive_cube_add()") if not result.success: print(result.error_message)
Notes
error_messageisstr()of the exception and does not name its type:raise KeyError('a')gives"'a'",1/0gives"division by zero".A syntax error in
codeis returned the same way:"x = "gives"invalid syntax (<string>, line 1)".Only subclasses of
Exceptionare caught.SystemExitandKeyboardInterruptpropagate.During the startup scripts,
successisFalseanderror_messageis"Host operations are unavailable during boot script data phase". The code is not run. See Standard namespace.
- pme.evaluate(expr, *, extra_globals=None)¶
Evaluate one Python expression in the standard namespace and return its value.
Exceptions are not caught.
- Parameters:
- Returns:
The value of the expression.
- Return type:
- Raises:
SyntaxError –
expris not a single expression.NameError –
expruses a name that is not in the namespace.RuntimeError – Called during the startup scripts. The message is
"Host operations are unavailable during boot script data phase".Exception – Any other exception raised while evaluating
expr.
Example
count = pme.evaluate("len(C.selected_objects)")
- pme.check_syntax(code, *, mode='exec')¶
Check that
codeparses as Python, without running it.- Parameters:
code (str) – Python source. Empty or whitespace-only code is valid.
mode (str) –
"exec"for statements,"eval"for one expression. The value is passed toast.parse(), which also accepts"single"and"func_type".
- Returns:
The parse result.
- Return type:
- Raises:
ValueError –
modeis not a mode thatast.parse()accepts.
Example
>>> pme.check_syntax("x = ") SyntaxResult(valid=False, error='invalid syntax', line=1, column=5) >>> pme.check_syntax("2 + 2", mode="eval").valid True
Notes
Only syntax is checked. Undefined names and errors that occur when the code runs are not detected.
Result types¶
Both classes are dataclasses in pme.types.
- class pme.types.ExecuteResult¶
Outcome of
pme.execute().Attribute
Type
Value
successbool
Truewhen the code ran to the end without raising.error_messagestr or None
str()of the exception whensuccessisFalse;Noneotherwise.
- class pme.types.SyntaxResult¶
Outcome of
pme.check_syntax().Attribute
Type
Value
validbool
Truewhen the code parses.errorstr or None
The parser’s message, such as
"invalid syntax"or"'(' was never closed".Nonewhen valid.lineint or None
Line of the error, counted from 1.
Nonewhen valid.columnint or None
Column of the error, counted from 1.
Nonewhen valid.
User properties¶
- pme.props(name=None, value=None)¶
Read or write the user properties stored in Addon Preferences.
Only Properties whose storage is Addon Preferences, and Property Stacks, are reached. A Property stored on an ID type such as
Objectkeeps one value per data-block, as an attribute of that data-block;props()does not hold it. See Property.- Parameters:
name (str or None) – Property ID or menu name to resolve, converted with
str().Nonereturns the PropertyGroup.value – Value to write.
Nonereads instead of writing.
- Returns:
See Call forms.
- Raises:
RuntimeError – PME has not finished loading the Property Editor. The message is
"PME user properties are unavailable until the add-on finishes loading".TypeError – A write gives a value the property does not accept. Raised by Blender, for example
expected True/False or 0/1, not str.
Call forms
Call
Operation
Returns
props()none
The PropertyGroup that holds the values. Its attributes are the registered Property IDs; reading and assigning them reads and writes the values.
props(name),props(name, None)read
The value, or
Nonewhennamedoes not resolve.props(name, value)write
Truewhen the value was written.Falsewhennamedoes not resolve to a writable name.Name resolution
nameis compared with the rows in this order. The first match decides.nameRead
Write
The registered Property ID of a Property or Property Stack:
registered_property_idinread_pm()["property"]orread_pm()["property_stack"].The value
Writes, returns
TrueThe menu name of exactly one enabled Property stored in Addon Preferences or enabled Property Stack whose Property ID is registered.
The value under that ID
FalseThe menu name of several such menus.
NoneFalseAnything else.
NoneFalseExample
import pme # Get the PropertyGroup and access a property as an attribute pme.props().MyCounter = 10 value = pme.props().MyCounter # Read or write by registered Property ID value = pme.props("MyCounter") written = pme.props("MyCounter", 10)
Notes
Inside slot code, the same function is the global
props. User properties created with the Property Editor use the same call forms in both places.props(name, None)reads. It does not writeNone.A name that does not resolve is not created as scratch storage.
Attribute names of the PropertyGroup itself, such as
bl_rna,keysor__class__, are not Property IDs:props("bl_rna")returnsNoneandprops("bl_rna", 1)returnsFalse. Read them from the PropertyGroup,pme.props().bl_rna.A write by menu name returns
Falseeven when a read by the same name returns a value.Earlier Experimental builds exposed the PropertyGroup as
pme.props.MyCounter. The current form ispme.props().MyCounter.
Add-on identity¶
- pme.ADDON_ID: str¶
Module name of the running PME add-on:
"pie_menu_editor"for an add-on installed inscripts/addons,"bl_ext.<repository>.<package>"for a Blender Extension. It is the key of PME’s entry inbpy.context.preferences.addons.Reading it before PME’s
addonmodule is loaded raisesRuntimeErrorwith the message"PME add-on identity is unavailable until the add-on finishes loading". A hard-coded"pie_menu_editor"does not match a Blender Extension installation.import bpy import pme addon_preferences = bpy.context.preferences.addons[pme.ADDON_ID].preferences
- pme.preferences¶
PME’s add-on preferences (
PMEPreferences): the same object asbpy.context.preferences.addons[pme.ADDON_ID].preferences. Looked up on each access.Reading it raises
KeyErrorwhenADDON_IDis not inbpy.context.preferences.addons. It isNonewhile that entry exists but PME’s preferences class is not registered, for example while the add-on is being enabled, or afteraddon_utils.disable()withoutdefault_set=True.
- pme.validate_uid(uid)¶
Return whether
uidhas the format of a menu UID.The check covers the format only. It does not look for a saved menu.
- Parameters:
uid (str) – The string to check.
- Returns:
Truefor<prefix>_<id>, where<prefix>is a menu type’s prefix below and<id>is 8 characters froma-zand2-7.Falseotherwise, including for non-strings, upper case and slot UIDs (pmi_<id>).- Return type:
Prefix
Menu type
modepmPie Menu
PMENUvmVector Menu
VMENUrmRegular Menu
RMENUpdPop-up Dialog
DIALOGfpFloating Panel
FPANELsStack Key
SCRIPTpgPanel Group
PANELhpgHidden Panel Group
HPANELskSticky Key
STICKYmcMacro Operator
MACROmdModal Operator
MODALprProperty
PROPERTYcnProperty Stack
CONDITIONrtContext Router
ROUTER>>> pme.validate_uid("pm_a2b3c4d5") True >>> pme.validate_uid("pmi_a2b3c4d5") False
- pme.context
PME’s execution context (
PMEContext), kept for PME1 scripts.pme.context.globalsis the dictionary behind the standard namespace, andpme.context.add_global(name, value)adds a name to it. Described in Scripting.