views:

90

answers:

1

I am writing a python extension to provide access to Solaris kstat data ( in the same spirit as the shipping perl library Sun::Solaris::Kstat ) and I have a question about conditionally returning a list or a single object. The python use case would look something like:

    cpu_stats = cKstats.lookup(module='cpu_stat')
    cpu_stat0 = cKstats.lookup('cpu_stat',0,'cpu_stat0')

As it's currently implemented, lookup() returns a list of all kstat objects which match. The first case would result in a list of objects ( as many as there are CPUs ) and the second call specifies a single kstat completely and would return a list containing one kstat.

My question is it poor form to return a single object when there is only one match, and a list when there are many?

Thank you for the thoughtful answer! My python-fu is weak but growing stronger due to folks like you.

+6  A: 

"My question is it poor form to return a single object when there is only one match, and a list when there are many?"

It's poor form to return inconsistent types.

Return a consistent type: List of kstat.

Most Pythonistas don't like using type(result) to determine if it's a kstat or a list of kstats.

We'd rather check the length of the list in a simple, consistent way.

Also, if the length depends on a piece of system information, perhaps an API method could provide this metadata.

Look at DB-API PEP for advice and ideas on how to handle query-like things.

S.Lott
I believe, then, that your answer should say "Yes.", not "No.", as you're arguing that it *is* bad form.
BJ Homer
+1 Totally right. And especially for the DB-API link.
Carl Meyer
Thanks for the cite as well!
Erik