简体   繁体   中英

setdefault() on suds soap dict results

Given the following generic code:

def soapQuery():
    soapuser = "Base64String"
    soappass = "Base64String"
    soapurl = 'https://url/file.ext?wsdl'
    ntlm = WindowsHttpAuthenticated(username=soapuser, password=soappass)
    client = Client(soapurl, transport=ntlm)
    result = client.service.method(something='somethingtosearchfor')
    soapfiltered = []
    for record in result.SoapRecord:
        soapfiltered.extend((str(record.value1), str(record.value2), str(record.value3), str(record.value4)))
    return zip(*[iter(soapfiltered)]*4)

When ran I get the following error:

AttributeError: SoapRecord instance has no attribute 'value3'

MOST of result.SoapRecord 's returned will contain all 4 record.value 's but some do not have this. Is there a way to set a default value to be returned like None or Null ? I have tried throwing record.setdefault('value3', None) in there but it does not work. Any and all help would be appreciated. Thank you in advance.

Well, there is no Null in Python and the dict's setdefault 's default default is None . Btw, dictionaries cannot be accessed through the dot operator in Python (sadly, I miss the feature from JS) so basically...I don't think record is a dictionary, but rather an object instead. To check if an object has a property, you can do hasattr(record, 'value1') for example.

Now with that all in mind, to keep everything to a single expression, you could do something like this:

hasattr(record, 'value1') and str(record.value1) or None

This is a boolean expression and in Python, you can evaluate boolean expressions without fully casting the values to bools. So that expression will give you either the value of str(record.value1) or simply None .

Sorry if anything in this answer is wrong, I'm not familiar with the Soap library.

Edit: As @plaes has noted in the comments, getattr(record, 'value1', None) is a much shorter and easier way of doing it. Thank you plaes :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM