Author Topic: Return Custom Type (Pandas DataFrame) from Async Function  (Read 498 times)

cjstudios

  • Newbie
  • *
  • Posts: 1
  • Karma: +0/-0
    • View Profile
Return Custom Type (Pandas DataFrame) from Async Function
« on: October 06, 2015, 12:58:27 AM »
It's unclear to me from the documentation on asynchronous functions how I would return a custom datatype - in my case a dataframe from the pandastypes addin.

Example Code (modified from the documentation:
Code: [Select]
from pyxll import xl_func, xlAsyncReturn
from threading import Thread
import pandas as pd
import logging
import time


class MyThread(Thread):
    def __init__(self, async_handle, x):
        Thread.__init__(self)
        self.__async_handle = async_handle
        self.__x = x

    def run(self):
        # here would be your long running function or a call to a server
        # or something like that
        time.sleep(1)
        try:
            xlAsyncReturn(self.__async_handle, self.__x) #this doenst work
        except Exception as e:
            logging.error(e)

@xl_func("async_handle h, int x")
def async_df(h, x):
    '''
    THIS DOEST WORKS
    '''
    df = pd.DataFrame({'a':[x, 1, 2, 3]})
    t = MyThread(h, df)
    t.start()

@xl_func("async_handle h, int x")
def async_1d_np(h, x):
    '''
    THIS WORKS
    '''
    df = pd.DataFrame({'a':[x, 1, 2, 3]})   
    t = MyThread(h, df.values)
    t.start()


Tony

  • Administrator
  • Hero Member
  • *****
  • Posts: 574
  • Karma: +13/-1
    • View Profile
Re: Return Custom Type (Pandas DataFrame) from Async Function
« Reply #1 on: October 06, 2015, 07:56:31 AM »
Hi,

you need to use the function 'get_type_converter' to convert from the dataframe object to a type Excel can understand, e.g:

Code: [Select]
df_to_var = pyxll.get_type_converter("dataframe", "var")
xlAsyncReturn(self.__async_handle, df_to_var(self.__x))

The get_type_converter works with custom types as well as the pre-defined types. For more information see https://www.pyxll.com/docs/index.html#pyxll.get_type_converter.

Best regards.
Tony