I started ~ two weeks ago with VisualComponents.
Maybe it helps, if you use a class to automatic add Properties
to a Component. This is what I have done:
from __future__ import print_function
from collections import OrderedDict
import sys
from vcScript import *
class GlobalVariables(object):
_variables = OrderedDict()
# def __init__(self, properties=None):
# if properties is not None:
# for name, property in properties.items():
# self[name] = property
def __getitem__(self, key):
return self._variables.get(key)
def __setitem__(self, key, variable):
if key in self._variables:
return
self._variables[key] = variable
def __len__(self):
return len(self._variables)
def __repr__(self):
return 'GlobalVariables({})'.format(
list(self._variables.keys())
)
def __iter__(self):
for item in self._variables.items():
yield item
__getattr__ = __getitem__
class GlobalVariable(object):
_register = GlobalVariables()
_type_mapping = {
str: VC_STRING,
int: VC_INTEGER,
float: VC_REAL,
bool: VC_BOOLEAN,
}
_inv_type_mapping = {v: k for k, v in _type_mapping.items()}
def __init__(self, name, type, component_name="GlobalVariables"):
self._app = getApplication()
self._prop_name = name
self._component_name = component_name
self._type = type
self._prop = self._find_prop()
self._validate(self._prop)
self._register[name] = self
def _validate(self, prop):
expected_prop_type = prop.Type
expected_python_type = self._inv_type_mapping[prop.Type]
given_python_type = self._type
if expected_python_type != given_python_type:
raise ValueError(
'The property is a type of {} and '
'the expected Python type is {}, '
'but got type {} instead.'.format(
expected_prop_type,
expected_python_type,
given_python_type,
)
)
def _get_component(self):
comp = self._app.findComponent(self._component_name)
if not comp:
comp = self._app.createComponent()
comp.Name = self._component_name
return comp
def _get_property(self, comp):
prop = comp.getProperty(self._prop_name)
if not prop:
prop = comp.createProperty(self._type_mapping[self._type], self._prop_name)
return prop
def _find_prop(self):
comp = self._get_component()
prop = self._get_property(comp)
return prop
def get(self):
return self._prop.Value
def set(self, value):
if not isinstance(value, self._type):
raise ValueError('Got wrong data type {}. Excpected type {}'.format(self._type, type(value)))
self._prop.Value = value
@property
def value(self):
return self.get()
@value.setter
def value(self, value):
self.set(value)
def __call__(self, value=None):
if value is None:
return self.get()
self.set(value)
return value
def __repr__(self):
return 'GlobalVariable(name="{}", type="{}", component_name="{}")'.format(
self._prop_name,
self._type,
self._component_name,
)
def __eq__(self, other):
cond1 = self._prop_name == other._prop_name
cond2 = self._component_name == other._component_name
return cond1 and cond2
def __bool__(self):
return bool(self.get())
__nonzero__ = __bool__
print('Getting or creating Properties and Component')
all_vars = GlobalVariables()
foo = GlobalVariable('foo', int)
bar = GlobalVariable('bar', bool)
baz = GlobalVariable('fizz', float)
faz = GlobalVariable('faz', str)
print('Trying an exception...')
try:
GlobalVariable('bar', float)
# bar exists already with the type bool
# this does not match
except ValueError as e:
print('Catching Error:', e, file=sys.stderr)
print()
print('Creating another bar instance')
# creating another instance for 'bar'
bar2 = GlobalVariable('bar', bool) # this time the right type
print('Get bool of bar', bool(bar), bool(bar2), sep=',')
print('Value of bar and bar2:', bar.value, bar2.value, sep=', ')
print('Modify bar2 -> True')
bar2.value = True
# bar2(True)
# bar2.set(True)
print('Get bool of bar', bool(bar), bool(bar2), sep=', ')
print('Testing equallity')
print(bar == bar2)
#print()
#print('Representation:', all_vars)
#print('Converted to a list', list(all_vars))
print(all_vars.bar)
print(all_vars.bar.value)
all_vars.bar.value = False
print(all_vars.bar.get())
By the way, it sucks, that there is still Python 2.7 syntax used.
I want format strings, I want typehints, I want asyncio, I want modern Python!