Article
José Roberto Pereira · Jan 13 2m read

A practical example on using Python with ObjectScript

I'd like to share an example on how the new Embedded Python feature in IRIS helped me in my daily routines.

While I’m participating in the iris-kaggle-socrata-generator project with Henrique Dias, I got to unzip datasets from Kaggle in order to import them.

Such a task was easily achieved by using the zipfile lib in Python (this code was copied from this stackoverflow):

Method UnZip(pZipFileName As %String, pExtractToDir As %String) As %DynamicArray [ Language = python ]
{
    import zipfile
    import iris
    with zipfile.ZipFile(pZipFileName, 'r') as zip_ref:
        zip_ref.extractall(pExtractToDir)
        fileList = zip_ref.namelist()

    dynarray = iris.cls("%DynamicArray")._New()
    for file in fileList:
        dynarray._Push(file)
    return dynarray
}

Note the method modifier [Language = python]. This feature was tested in IRIS image intersystemsdc/iris-ml-community:2021.2.0.617.0-zpm. Check out the related OEX application for a working example.

You can see that is a Python code embedded in an ObjectScript method. So you can use it in every ObjectScript code. For example:

Method HttpDownloadZIP(pHttpParams As %DynamicObject) As %DynamicObject
{
    Set retorno = {
        "warnings": []
    }
    …
    Set fileName = ..SaveRequestToFile(request)
    …
    Set fileList = ..UnZip(fileName, zipTempDir)
    If (fileList.%Size() > 1) {
        Do retorno.warnings.%Push("There is more than 1 file in the zip file. Using the first one.")
    }
    …
    Return retorno
}

You can also access the full code here.

Note that the embedded Python method uses the zipfile Python lib and returns the method outcomes in a %DynamicArray, used in ObjectScript methods. This means that an object created in a Python context can be accessed by an ObjectScript context seamlessly.

You can check out more on how to use Embedded Python here.

And that is it! I hope this can be useful for your projects.
See you!

5
0 332
Discussion (2)2
Log in or sign up to continue

@José Roberto Pereira , thank you for sharing!!  Please note that you have a small typo in your title - pratical > practical (no worries, if I wrote a D.C. article in Spanish you would lose count of all of the typo's ;) ).  

Hi @Ben Spead!

Thank you for warning me! :)

Fixed! I usually double check my English writings in text editors like Google Docs, but I missed to check the title...

A little explanation here, I'm Brazilian, so a Portuguese native speaker. But it's OK, Portuguese is a kind of brother of Spanish! =)