· Apr 1

Python Class only works in %SYS namespace

After running many tests to kick the tires calling Python from COS (which worked fine) in any directory,  I encountered problems when trying to access Python libraries like Numpy from any OTHER namespace.   I saw some other posts about this but the resolution seems unclear.   When I run the test program method numpytest below in %SYS it works just fine.  If i run the Python method in any other namespace I get: 

PITT>do ##class(test.python).numpytest()
DO ##CLASS(test.python).numpytest()
<OBJECT DISPATCH> *python object not found

Here is the test program - i did the install with IRISPIP on pandas and numpy and they ran fine.

Class testnp.test Extends %Persistent
{ ClassMethod numpytest() As %String [ Language = python ]
# do ##class(testnp.test).numpytest()
 import numpy as np
 import math
 arr np.array([12345]) print(arr) x=np.random.randint(1151#generate a number between 1 and 15
 print("Random num=",x) y=math.pi
 print("This is pi:",y)
 x="hello world"

ClassMethod test() As %String [ Language = python ]
import pandas
print("In test python")
 #df = pandas.read_json(json, orient="index")

ClassMethod Getdata() As %String
   // do ##class(test.python).Getdata()
   // calling Python from COS
  set b=##class(%SYS.Python).Import("builtins")
  set d=##class(%SYS.Python).Import("datetime")
  write !,today.isoformat()
  set d=##class(%SYS.Python).Import("math")
  write !,d.pi
  set np=##class(%SYS.Python).Import("numpy")
  set = np.array([34])
  set x= np.exp(4)
  write !,b.float(x)
   set rand = np.random.randint(1, 15, 1)
Quit x

Any tips or help would be most welcome!

Product version: IRIS 2023.1
$ZV: IRIS for Windows (x86-64) 2023.1.1 (Build 380) Fri Jul 7 2023 23:56:43 EDT
Discussion (4)1
Log in or sign up to continue

This works for me (pay attention to the semicolons!)

ClassMethod numpytest() As %String [ Language = python ]
 import numpy as np
 import math
 arr = np.array([1, 2, 3, 4, 5]); print(arr); x=np.random.randint(1, 15, 1) # generate a number between 1 and 15
 print("Random num=",x)
 print("This is pi:",y)
 x="hello world"

an the output is

USER>d ##class(Py.Demo).numpytest()
[1 2 3 4 5]
Random num= [13]
This is pi: 3.141592653589793
hello world
a= 7

USER>w $zv
IRIS for UNIX (Ubuntu Server LTS for x86-64) 2021.2 (Build 649U) Thu Jan 20 2022 08:49:51 EST