What is the Synonym of $property for Embedded Python?
Hi folks!
I have a need to use symilar to $property function from Python. Here is the code:
obj=iris.cls('some.persistent.class')._New()
for property, value in data.items():
$property(obj.property)=value ; I invented thisHow could I do this? Any trick?
For now I plan to implement a helper function in iris that I will call, but I doubt also how can I transfer oref to IRIS.
Thoughts?
Comments
Hi Evgeny,
Not saying this is best way but this indirection can be achieved with python eval. For example:
$Classmethod equivalent
classname="%SYSTEM.SYS"
methodname="ProcessID"
eval(f"iris.cls(\"{classname}\").{methodname}()")$Property equivalent
Instantiating a Python exception and then iterate over properties printing out name and value:
myerror=iris.cls("%Exception.PythonException")._New("MyOops",123,"def+123^XYZ","SomeData")
for propertyname in ["Name","Code","Data","Location"]:
propvalue=eval(f"myerror.{propertyname}")
print(f"Property Name {propertyname} has value {propvalue}\n")output was:
Property Name Name has value MyOops Property Name Code has value 123 Property Name Data has value SomeData Property Name Location has value def+123^XYZ
Thank you, @Alex Woodhead ! This works for me!
Another solution is to use getattr
classname="%SYSTEM.SYS"
methodname="ProcessID"
pid = getattr(iris.cls(classname), 'ProcessID')()
myerror=iris.cls("%Exception.PythonException")._New("MyOops",123,"def+123^XYZ","SomeData")
for propertyname in ["Name","Code","Data","Location"]:
print(getattr(myerror, propertyname))And for completeness: setting a property with a name not known until runtime can be done with the counterpart of getattr, setattr:
USER>do ##class(%SYS.Python).Shell()
Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux
Type quit() or Ctrl-D to exit this shell.
>>> e=iris.cls("%Exception.PythonException")._New("MyOops",123,"def+123^XYZ","SomeData")
>>> e.Name
'MyOops'
>>> setattr(e,'Name','TheirOops')
>>> e.Name
'TheirOops'
Thank you both @Dmitry Maslennikov @Gertjan Klein !
This is what I'm looking for!