Search code examples
pythonfunctionobjectbloomberg

deleting (killing) a python object from inside a function


Hi I'm using a bloomberg API (for learning purposes and not too relevant to the question - simply as context).

Part of the process is to create "requests" that are sent as queries to a server that responds.

Each query stays "alive" until the object is killed. I'm using a function to call down the data from each request since this is code I use very frequently and the shape of the request can change considerably with each call.

def calldata(req): # doesnt currently work. Dont know why
    session.sendRequest(req)
    while True:
        ev = session.nextEvent()
        tmp = []
        if ev.eventType() == blpapi.Event.RESPONSE or blpapi.Event.PARTIAL_RESPONSE:
            for msg in ev:
                if msg.hasElement('securityData'):
                    data = msg.getElement('securityData')
                    tmp.append(data)
        break
    del req
    return(tmp)

where the req could be for example

# Data for clean multiple data ::= cleanref
r = svc.createRequest('ReferenceDataRequest')
r.append('securities','MSFT US Equity')
r.append('fields','bid')
cleanref = calldata(r)


# Dirty reference for multiple data - both bad security and bad field 
# ::= errorref
req = svc.createRequest("ReferenceDataRequest")
req.append('securities','Rhubarb Curncy')
req.append('fields','PX_LAST')
req.append('securities','SGD Curncy')
req.append('fields','desc')
errorref= calldata(req) 

# Historical data request ::= histdata
request = svc.createRequest("HistoricalDataRequest")
request.getElement("securities").appendValue("IBM US Equity")
request.getElement("securities").appendValue("MSFT US Equity")
request.getElement("fields").appendValue("PX_LAST")
request.getElement("fields").appendValue("OPEN")
request.set("periodicityAdjustment", "ACTUAL")
request.set("periodicitySelection", "MONTHLY")
request.set("startDate", "20060101")
request.set("endDate", "20061231")
request.set("maxDataPoints", 100)

histdata = calldata(request)

# erroneous historical data request ::= histerr
requ = svc.createRequest("HistoricalDataRequest")
requ.getElement("securities").appendValue("IBM US Equity")
requ.getElement("securities").appendValue("MSFT US Equity")
requ.getElement("fields").appendValue("PX_LAST")
requ.getElement("fields").appendValue("Desc")
requ.set("periodicityAdjustment", "ACTUAL")
requ.set("periodicitySelection", "MONTHLY")
requ.set("startDate", "20060101")
requ.set("endDate", "20061231")
requ.set("maxDataPoints", 100)

histerr = calldata(requ)

So I need to kill each of the requests in the function to be able to reuse it and I cant figure it out. I suspect it may be something to do with locals() but any help would be gratefully recieved.


Solution

  • you have to call del r after each call of calldata(r), like this:

    cleanref = calldata(r)
    del r
    

    del ref inside your function only delete reference inside your function.