开发者

How to get the contents of a field instead of `<bound method...` in a CSV output with Python (pytwist)

The snippet below is generating "weird" output:

for s in servers:
    vo = ss.getServerVO(s)
    values = []
    for f in voFields:
        attribValue = getattr(vo, f)
        values.append(attribValue)
    customValues = ss.getCustomFields(s)
    for f in customFields:
        values.append(customValues[f])
    # Co开发者_JS百科nvert all values to string before writing
    values = map(str, values)
    csvFile.writerow( values )

For some - not all - items in the customFields dictionary, I get the following output:

<bound method ServerVO.getCreatedDate of <pytwist.com.opsware.server.ServerVO instance at 0x3da8680>>

What do I need to do to get the bound method to execute / put its results into my values dictionary?

(Specific context is in writing a PyTwist script against the HP Server Automation API)


You could try calling the bound method if it is one:

for f, v in customFields.iteritems():
  try:
    v = v()
  except TypeError:
    pass
  values.append(v)

The problem, of course, is with the design choice (by HP or whoever) to mix "accessors" with other kinds of values -- accessors are not a good Pythonic choice and should be replaced with properties (where this "call" gets automated for you where needed). This suggestion is about a possible way to work around that bad design choice.

Just trying to call, and checking for the TypeError that can result if the value is not callable (or not callable without arguments) is better than using callable or checking for a __call__ special method, because those checks would never tell you if "calling without argument" is OK. So, as usual in Python, "it's better to ask forgiveness by permission": try the operation, catch possible errors ("ask forgiveness") -- rather than try to check if the operation is permissible before attempting it ("ask permission").

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜