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.

Erik
  • 898
  • 8
  • 20
  • Even though you're asking this question in the context of writing an extension module, the answer is the same if you're writing pure Python functions. – Miles Jun 02 '09 at 17:28

1 Answers1

7

"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
  • 384,516
  • 81
  • 508
  • 779
  • 1
    I believe, then, that your answer should say "Yes.", not "No.", as you're arguing that it *is* bad form. – BJ Homer Jun 02 '09 at 17:14