How to tell if function was passed a list or a string?

Ben Finney bignose+hates-spam at benfinney.id.au
Wed May 17 18:47:13 EDT 2006


"rh0dium" <steven.klass at gmail.com> writes:

> I want this function to be smart enough to tell if it's a list and
> do the funky concatonation otherwise don't.

Bad code smell. Don't try to be too clever with the data types passed
to you; instead, operate on them as though the caller has passed the
right thing.

Write unit tests and integration tests to ensure that the code is
behaving as expected, and to reduce the amount of clever code that
gets in the way of understanding the function.

> The question is how do you tell that the data you were passed is a
> list or not?

With difficulty, since strings are sequences. It's debatable whether
this is a wart.

Two options:

Use 'isinstance', which unfortunately breaks the rule of duck
typing. Currently there's no good duck-typing way to differentiate
strings from other sequences.

    if isinstance(x, basestring):
        # do string stuff
    else:
        # do sequence-of-string stuff

Or:

If you want to operate on sequences of strings, simply specify that's
all that can be passed and expect it inside your function. This is
more Pythonic, IMO.

-- 
 \     "First they came for the verbs, and I said nothing, for verbing |
  `\    weirds language. Then, they arrival for the nouns and I speech |
_o__)                        nothing, for I no verbs."  -- Peter Ellis |
Ben Finney




More information about the Python-list mailing list