Article
· Mar 15, 2023 10m read

InterSystems Embedded Python in glance

         

Hi Community,
In this article I will demonstrate the usage of InterSystems Embedded Python, We will cover below topics:

  • 1-Embedded Python Overview
  • 2-Usage of Embedded Python
    • 2.1- Using a Python Library from ObjectScript
    • 2.2- Calling the InterSystems APIs from Python
    • 2.3- Using ObjectScript and Python together
  • 3-Using python Built-in Functions
  • 4-Python Modules/Libraries 
  • 5-Embedded Python Use Cases
  • 6-Summary

So let's start with an overview

 

1-Embedded Python Overview

Embedded Python is a feature of InterSystems IRIS data platform that allows Python developers to gain full and direct access to the data and functionality in InterSystems IRIS.

InterSystems IRIS comes with a powerful built-in programming language called ObjectScript that is interpreted, compiled, and run inside the data platform.

Because ObjectScript executes within the context of InterSystems IRIS, it has direct access to the memory and procedure calls of the data platform.

Embedded Python is an extension of the Python programming language that allows for the execution of Python code inside the InterSystems IRIS process context.

Because both ObjectScript and Python operate on the same object memory, it can be said that Python objects do not just emulate ObjectScript objects, they are ObjectScript objects.

This co-equality of these languages means you can choose the language most appropriate for the job, or the language you are most comfortable using to write applications.

 

2-Usage of Embedded Python

When using Embedded Python, you can write your code in three different modalities.

2.1 - Using a Python Library from ObjectScript

First, you can write an ordinary .py file and call it from the InterSystems IRIS context. In this case, the data platform will launch the Python process and allow you to import a module called IRIS, which automatically attaches the Python process to the IRIS kernel and provides you access to all the functionality of ObjectScript from the context of your Python code.

2.2 - Calling the InterSystems APIs from Python

Second, you can write ordinary ObjectScript code and instantiate a Python object using the %SYS.Python package. This ObjectScript package allows you to import Python modules and libraries, then work with that code base using ObjectScript syntax.
The %SYS.Python package enables ObjectScript developers without any knowledge of Python to use the rich ecosystem of Python libraries in their ObjectScript code.

2.3 - Using ObjectScript and Python together

Third, you can create an InterSystems class definition and write methods in Python. Any call to that method will launch the Python interpreter. This method has the benefit of populating the self keyword of that block of Python code with a reference to the instance of the containing class. Additionally, by using Python to write class methods in InterSystems classes, you can easily implement methods that handle different data entry events in SQL such as a new row being added to a table.
It also allows for the rapid development of custom stored procedures in Python.

As you can see, Embedded Python allows you to choose the programming language best suited to the job without sacrificing performance.

3-Using Python Built-in Functions

The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.

Built-in Functions

A

abs()

aiter()

all()

any()

anext()

ascii()

 

B

bin()

bool()

breakpoint()

bytearray()

bytes()

 

C

callable()

chr()

classmethod()

compile()

complex()

 

D

delattr()

dict()

dir()

divmod()

 

E

enumerate()

eval()

exec()

 

F

filter()

float()

format()

frozenset()

 

G

getattr()

globals()

 

H

hasattr()

hash()

help()

hex()

 

I

id()

input()

int()

isinstance()

issubclass()

iter()

L

len()

list()

locals()

 

M

map()

max()

memoryview()

min()

 

N

next()

 

O

object()

oct()

open()

ord()

 

P

pow()

print()

property()

 

 

 

 

R

range()

repr()

reversed()

round()

 

S

set()

setattr()

slice()

sorted()

staticmethod()

str()

sum()

super()

 

T

tuple()

type()

 

V

vars()

 

Z

zip()

 

_

__import__()


Using python Built-in Functions

In order to use python built-in function we have to import "builtins" then we can invoke the function

set builtins = ##class(%SYS.Python).Import("builtins")

The Python print() function is actually a method of the built-in module, so you can now use this function from ObjectScript:

USER>do builtins.print("hello world!")
hello world!
USER>set list = builtins.list()
 
USER>zwrite list
list=5@%SYS.Python  ; []  ; <OREF>

Likewise, you can use the help() method to get help on the list object.

USER>do builtins.help(list)
Help on list object:
class list(object)
 |  list(iterable=(), /)
 |
 |  Built-in mutable sequence.
 |
 |  If no argument is given, the constructor creates a new empty list.
 |  The argument must be an iterable if specified.
 |
 |  Methods defined here:
 |
 |  __add__(self, value, /)
 |      Return self+value.
 |
 |  __contains__(self, key, /)
 |      Return key in self.
 |
 |  __delitem__(self, key, /)
 |      Delete self[key].

 

4-Python modules or libraries

Some python modules or libraries are installed by default and already available to use. By using the help("module" function we can view these modules:
Python libraries list output 1
 

Installing python module or library

Apart from these modules python has hundreds of modules or libraries, which can be viewed at pypi.org (The Python Package Index (PyPI) is a repository of software for the Python programming language)

If we need some other libraries, then we need to install the libraries using the intersystems irispip command

For example, Pandas is python Data Analysis Library. The following command uses the package installer irispip to install pandas on a Windows system:

C:\InterSystems\IRIS\bin>irispip install --target C:\InterSystems\IRIS\mgr\python pandas

Please note C:\InterSystems will be replaced by Intersystems installation directory
 

5-Embedded Python Use Cases


5.1-Printing PDF by using python Reportlab Library

We need to install Reportlab library by using irispip command, then just create objectscript function.

Given a file location, the following ObjectScript method, CreateSamplePDF(), creates a sample PDF file and saves it to that location.

Class Demo.PDF
{

ClassMethod CreateSamplePDF(fileloc As %String) As %Status
{
    set canvaslib = ##class(%SYS.Python).Import("reportlab.pdfgen.canvas")
    set canvas = canvaslib.Canvas(fileloc)
    do canvas.drawImage("C:\Sample\isc.png", 150, 600)
    do canvas.drawImage("C:\Sample\python.png", 150, 200)
    do canvas.setFont("Helvetica-Bold", 24)
    do canvas.drawString(25, 450, "InterSystems IRIS & Python. Perfect Together.")
    do canvas.save()
}

}

The first line of the method imports the canvas.py file from the pdfgen subpackage of ReportLab. The second line of code instantiates a Canvas object and then proceeds to call its methods, much the way it would call the methods of any InterSystems IRIS object.

You can then call the method in the usual way: 

do ##class(Demo.PDF).CreateSamplePDF("C:\Sample\hello.pdf")

The following PDF is generated and saved at the specified location:
One page PDF with the InterSystems logo, the Python logo, and the text: InterSystems IRIS and Python. Perfect Together.

 

5.2-Generating QR code by using Python Qrcode Library

In order to generate qrcode, we need to install Qrcode library by using irispip command, then by using the below code we can generate QR Code:

 

5.3-Get GEO location by using Python Folium library

In order to get geographic data, we need to install Folium library by using irispip command, then create below object script function:

Class dc.IrisGeoMap.Folium Extends %SwizzleObject
{

// Function to print Latitude, Longitude and address details 
ClassMethod GetGeoDetails(addr As %String) [ Language = python ]
{
    from geopy.geocoders import Nominatim
    geolocator = Nominatim(user_agent="IrisGeoApp")
    try:
    	location = geolocator.geocode(addr)
    	print("Location:",location.point)
    	print("Address:",location.address)
    	point = location.point
    	print("Latitude:", point.latitude)
    	print("Longitude:", point.longitude)
    except:
    	print("Not able to find location")
}
}

Connect to IRIS Terminal and run below code

do ##class(dc.IrisGeoMap.Folium).GetGeoDetails("Cambridge MA 02142")

Below will be the output:

image

  

5.4-Generate and mark locations on an interactive Map by using Python Folium library
 

We will use the same Python Folium library to generate and mark locations on an interactive Map, Below object script function will do the desired :

ClassMethod MarkGeoDetails(addr As %String, filepath As %String) As %Status [ Language = python ]
{
    import folium
    from geopy.geocoders import Nominatim
    
    geolocator = Nominatim(user_agent="IrisGeoMap")
    #split address in order to mark on the map
    locs = addr.split(",")
    if len(locs) == 0:
    	print("Please enter address")
    elif len(locs) == 1:
    	location = geolocator.geocode(locs[0])
    	point = location.point
    	m = folium.Map(location=[point.latitude,point.longitude], tiles="OpenStreetMap", zoom_start=10)
    else:
    	m = folium.Map(location=[20,0], tiles="OpenStreetMap", zoom_start=3)
    
    for loc in locs:
    	try:
    		location = geolocator.geocode(loc)
    		point = location.point
    		folium.Marker(
	    			location=[point.latitude,point.longitude],
	    	  		popup=addr,
	    		).add_to(m)    		
    	except:
    		print("Not able to find location : ",loc) 
    		  
    map_html = m._repr_html_()
    iframe = m.get_root()._repr_html_()
    fullHtml = """
      	     <!DOCTYPE html>
        	    <html>
        	        <head></head>
        	        <body> """
    fullHtml = fullHtml + iframe            
    fullHtml = fullHtml + """                                             
       	        </body>
        	    </html>
    """
    try:
    	f = open(filepath, "w")
    	f.write(fullHtml)
    	f.close()
    except:
    	print("Not able to write to a file")
}

Connect to IRIS Terminal and invoke MarkGeoDetails function

We will invoke MarkGeoDetails() function of dc.IrisGeoMap.Folium class.
The function requires two parameters:

  1. location/locations(We can pass multiple locations by adding "," in between)
  2. HTML file path

Let us run the below command to mark Cambridge MA 02142, NY, London, UAE, Jeddah, Lahore, and Glasgow on the Map and save it as "irisgeomap_locations.html" file

do ##class(dc.IrisGeoMap.Folium).MarkGeoDetails("Cambridge MA 02142,NY,London,UAE,Jeddah,Lahore,Glasgow","d:\irisgeomap_locations.html")

The above code will generate below interactive HTML file:

image

  

5.5-Data analytics by using Python Pandas library 

We need to install Pandas library by using irispip command, then we can use the below code to view the data
 

 

6-Summary

InterSystems Embedded Python (IEP) is a powerful feature that allows you to integrate Python code seamlessly with your InterSystems applications. With IEP, you can leverage the extensive libraries and frameworks available in Python to enhance the functionality of your InterSystems applications. In this article, we will explore the key features and benefits of IEP.

IEP is implemented as a set of libraries that enable you to interact with Python objects and execute Python code from within InterSystems applications. This provides a simple and effective way to integrate Python code into your InterSystems applications, allowing you to perform data analysis, machine learning, natural language processing, and other tasks that may be challenging to implement in InterSystems ObjectScript.

One of the primary advantages of using IEP is that it provides a way to bridge the gap between the worlds of Python and InterSystems. This makes it easy to use the strengths of both languages to create powerful applications that combine the best of both worlds.

IEP also provides a way to extend the functionality of your InterSystems applications by leveraging the capabilities of Python. This means that you can take advantage of the vast number of libraries and frameworks available in Python to perform tasks that may be challenging to implement in InterSystems ObjectScript.

InterSystems Embedded Python provides a powerful way to extend the functionality of your InterSystems applications by leveraging the capabilities of Python. By integrating Python code into your InterSystems applications, you can take advantage of the vast number of libraries and frameworks available in Python to perform complex tasks that may be challenging to implement in InterSystems ObjectScript.

Thanks

Discussion (3)2
Log in or sign up to continue