PyMEL: Unable to create new option variable


#1
import pymel.core as pm
pm.optionVar["test"] = []
print pm.optionVar["test"]

# Error: test
# Traceback (most recent call last):
#   File "<maya console>", line 3, in <module>
#   File "E:\Autodesk\Maya2016\Python\lib\site-packages\pymel\core\language.py", line 531, in __getitem__
#     raise KeyError, key
# KeyError: 'test' # 

I usually create my option variables in the init of my modules - but for some reason this will not execute:
if “test” not in pm.env.optionVars: pm.optionVar[“test”] = []

…which is odd because the row after it tries runs the same code, but with the key “test2”. So I tried to create it using the above code and then print the result to make sure it’s “there” - and then I get this weird KeyError saying it doesn’t exist!?!

Is there a cap or something on how many optionVars you can create?


#2

In line 3, I think you need to use

pm.env.optionVars.get(‘test’)

David


#3

I thought I should share my finding regarding this annoying problem
I checked with the syntax that you suggested and it wasn’t what caused the problem (Using pm.optionVar[“test”] for both retrieval and assignment works without issues).

The problem occurs when you store an empty list in an optionVar:
pm.optionVar[“test”] = []

Even if you populate this list with data further down the road you might experience problems.
So my workaround was just to assign an empty string to the optionVar initially, and later re-assign the proper data (ie: a list with stuff in it) further down the road. Problem gone!!


#4

or you could just not assign it till you have data to fill it with. you can exepct and check if it dosnt exist before accessing it via just using something like


 value = mydict["key"] if "key" in mydict else my_defualt_value
 

#5

I was showing you a solution to the key error problem. The dictionary get() method does not fail if the key doesnt exist, it simply returns None by default.

import pymel.core as pm
pm.optionVar["test"] = []
print pm.env.optionVars.get("test")

# result...
None
#

If you want you can specify any return you want. So if you want to return a list regardless, then use the 2nd arg of get() as shown here

import pymel.core as pm
pm.optionVar["test"] = []
print pm.env.optionVars.get("test", [])

# result...
[]
#

The dictionary get method saves you messing around with dummy assignments and other checks.

David