473,383 Members | 1,805 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

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

Hi All,

I have the nice little function (below) which used to work great
assuming the data[key] passed to it was a list. Well now I want to
update this a bit. I want this function to be smart enough to tell if
it's a list and do the funky concatonation otherwise don't.
def insert(self, table=None, data=None):
insert1=[]
insert2=[]

for key in data.keys():
insert1.append(key)
self.logger.debug("Key: %s Data: %s" % ( key,data[key]))
try:
an = []
for a in data[key]:
an.append(re.sub(",","", str(a)))
ans = string.join(an, ", ")
except:
ans = None
insert2.append(ans)

self.logger.info( "Insert command %s" % insert )
self.cursor.execute(insert)
The question is how do you tell that the data you were passed is a list
or not?
Thanks so much!

May 17 '06 #1
9 1759
In article <11**********************@i40g2000cwc.googlegroups .com>,
"rh0dium" <st**********@gmail.com> wrote:
The question is how do you tell that the data you were passed is a list
or not?

x = []
isinstance (x, list)

True
May 17 '06 #2
"rh0dium" <st**********@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

May 17 '06 #3
Ben Finney <bi****************@benfinney.id.au> wrote:
Currently there's no good duck-typing way to differentiate
strings from other sequences.


I suppose you could do something like:

try:
foo.isalpha
except AttributeError:
print "foo is not a string"

but other than proving that you don't *have* to use isinstance(), I don't
think that approach has much going for it.
May 17 '06 #4
>>> import types
type("") is types.ListType False type("") is types.StringType True type([]) is types.StringType False type([]) is types.ListType

True

May 17 '06 #5
Roy Smith <ro*@panix.com> writes:
Ben Finney <bi****************@benfinney.id.au> wrote:
Currently there's no good duck-typing way to differentiate strings
from other sequences.


I suppose you could do something like:

try:
foo.isalpha
except AttributeError:
print "foo is not a string"

but other than proving that you don't *have* to use isinstance(), I
don't think that approach has much going for it.


Duck typing preserves one very important feature of Python: a class
doesn't have to *inherit from* type 'foo' to be a *substitute for*
type 'foo'. An 'isinstance' check will fail on objects that don't
inherit from the string types, but do implement the interface
adequately.

In this example, if an object 'x' implements the behaviour you're
going to use, but doesn't inherit from 'basestring', refusing it just
because 'isinstance(x, basestring)' is False would be the wrong
choice.

--
\ "I planted some bird seed. A bird came up. Now I don't know |
`\ what to feed it." -- Steven Wright |
_o__) |
Ben Finney

May 17 '06 #6
tr*******@gmail.com writes:
import types
type("") is types.ListType False type("") is types.StringType True type([]) is types.StringType False type([]) is types.ListType

True


This is even worse than an 'isinstance' check; it refuses even
subclasses of the types you accept, breaking polymorphism *and*
inheritance.

--
\ "What you have become is the price you paid to get what you |
`\ used to want." -- Mignon McLaughlin |
_o__) |
Ben Finney

May 17 '06 #7
> > >>> import types
>> type("") is types.ListType

False
>> type("") is types.StringType

True
>> type([]) is types.StringType

False
>> type([]) is types.ListType

True


This is even worse than an 'isinstance' check; it refuses even
subclasses of the types you accept, breaking polymorphism *and*
inheritance.


And also note the following comment in the types module of the
standard library that was imported above:

# StringTypes is already outdated. Instead of writing "type(x) in
# types.StringTypes", you should use "isinstance(x, basestring)". But
# we keep around for compatibility with Python 2.2.
May 18 '06 #8
rh0dium <st**********@gmail.com> wrote:
[ ... ]
Since you have lots of answers to your real question:
an.append(re.sub(",","", str(a)))


an.append(str(a).replace(",", ""))

--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomež se bera eadward ofdun hlęddre heafdes bęce bump bump bump
May 18 '06 #9
Roy Smith wrote:
Ben Finney <bi****************@benfinney.id.au> wrote:
Currently there's no good duck-typing way to differentiate
strings from other sequences.


I suppose you could do something like:

try:
foo.isalpha
except AttributeError:
print "foo is not a string"


Another way:

if getattr (foo, 'isalpha', False):
print 'foo is a string'

Of course now string duck types must have an 'isalpha' and list ones can't,
but that shouldn't matter much.

--
Edward Elliott
UC Berkeley School of Law (Boalt Hall)
complangpython at eddeye dot net
May 21 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: EsC | last post by:
Hy! is it possible to pass function-arguments by reference? (for example in PHP you can use the "&" operator ... ) thx iolo
9
by: Derek Hart | last post by:
I wish to execute code from a string. The string will have a function name, which will return a string: Dim a as string a = "MyFunctionName(param1, param2)" I have seen a ton of people...
1
by: Ken Fine | last post by:
I have a menu system that has nodes that can be opened or closed. In an effort to make my code more manageable, I programmed a little widget tonight that keeps track of the open/active item and...
3
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) {...
17
by: Roland Hall | last post by:
Is there a way to return multiple values from a function without using an array? Would a dictionary object work better? -- Roland Hall /* This information is distributed in the hope that it...
58
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of...
39
by: Mike MacSween | last post by:
Just spent a happy 10 mins trying to understand a function I wrote sometime ago. Then remembered that arguments are passed by reference, by default. Does the fact that this slowed me down...
4
by: shachar | last post by:
hi all. i'm looking for a simple example of how to pass optionaly, an array to a function. if the array isn't there (it's optional) i want to know about it. thanks.
1
by: mayur_hirpara | last post by:
Hi, I am looking to call a javascript function using variable number of parameters. Suppose I have a function foo(param) { ..... } I want it to be called unpredictebly when certain action...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.