ibm_db on HADR primary database?
Looks like, when the alternate server is configured, the CLI driver prefers its proper hostname over "localhost". If you specify the machine hostname or IP address in the connection string instead of "localhost" the script works as expected. 

The test script can be modified as:

[...]
import traceback
import socket
[...]

def f1(dbname, username, pwd):
    print "start"
    ip = socket.gethostbyname(socket.gethostname())
    cfg = (dbname, ip, username, pwd)
    conn_str = "DATABASE=%s;HOSTNAME=%s;PORT=50000;PROTOCOL=TCPIP;UID=%s;PWD=%s" % cfg
    [...]


It is recommended to explicitly bind Db2 to an IP address via nicbinding.cfg, in which case "localhost" wouldn't work anyway.