Reputation: 2111
I recently started looking into SDK for Azure and can't figure out why every single method (tested by me) returns an object rather then something more 'human' friendly i.e. list or dictionary.
i.e.:
list(compute_client.virtual_machines.list_all())
[<azure.mgmt.compute.compute.v2017_03_30.models.virtual_machine.VirtualMachine object at 0x7f637f93c190>, <azure.mgmt.compute.compute.v2017_03_30.models.virtual_machine.VirtualMachine object at 0x7f637f93c750>, <azure.mgmt.compute.compute.v2017_03_30.models.virtual_machine.VirtualMachine object at 0x7f637f93cad0>, <azure.mgmt.compute.compute.v2017_03_30.models.virtual_machine.VirtualMachine object at 0x7f637f93ced0>]
What is a benefit of returning objects which seem to be awkward to interact with i.e. I need to lookup every single method to find the return values and so on to process a list and then to build a dictionary it seems as more work then needed.
I have found this method in one of the Microsoft blogs / githubs:
def print_item(group):
"""Print a ResourceGroup instance."""
print("\tName: {}".format(group.name))
print("\tId: {}".format(group.id))
print("\tLocation: {}".format(group.location))
print("\tTags: {}".format(group.tags))
print_properties(group.properties)
This seems so inefficient IMO to be able to print a return value of another method.
Can some one advise why an "object list" is better then a "list" why not to return something like json.
Upvotes: 3
Views: 1892
Reputation: 3546
Short answer: from any instance just call as_dict()
to get a dict view of the object.
Long answer: the object you get is way more than a simple wrapper around the initial JSON. It's produced from an OpenAPI parsing that takes care of:
The object itself contains several methods that makes it more complex than a simple dict, like validate
to validate on building that your model is correct (i.e. building a web form with live validation).
However, as a consumer, Python users like dict as you do, and it's the purpose of the as_dict()
method. This method even takes a callback (Visitor pattern) to allow changing on the fly the dict serialization you would get from this method.
(I work at MS in the Azure SDK Python team)
Edit: In the case of the list
operation, you get a Python iterator that takes care of paging for you for free. You don't even know when you're fetching the second page. For memory consumption, when you wrap this into a list()
you load everything in memory at once. If you would use a for vm in compute_client.virtual_machines.list_all()
you would have only one page at a time in memory and not more. If you just need a few objects, if will go way faster if you have a lot of VMs to take advantage of the iterator (whatever using for
loop or next()
and StopIteration
exception)
Upvotes: 7