By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,908 Members | 1,945 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,908 IT Pros & Developers. It's quick & easy.

checking one's type

P: n/a
Hi,

I've been using the following hack to determine if a type is
acceptable and I suspect there is a better way to do it:

e.g.

if type(s) == type("") :
print "okay, i'm happy you're a string"

If anyone knows a better way, I'm all ears.

Thanks,

--b
Jan 5 '07 #1
Share this Question
Share on Google+
3 Replies


P: n/a
In article <ma***************************************@python. org>,
belinda thom <bt***@cs.hmc.eduwrote:
I've been using the following hack to determine if a type is
acceptable and I suspect there is a better way to do it:

e.g.

if type(s) == type("") :
print "okay, i'm happy you're a string"

If anyone knows a better way, I'm all ears.
If you want to know whether something is specifically a string, but not a
Unicode string, then you want isinstance(foo, str). If you want to check whether
something is a general string (including Unicode strings), you want
isinstance(foo, basestring).

hth

Ben

--
If this message helped you, consider buying an item
from my wish list: <http://artins.org/ben/wishlist>

I changed my name: <http://periodic-kingdom.org/People/NameChange.php>
Jan 5 '07 #2

P: n/a
belinda thom schrieb:
I've been using the following hack to determine if a type is acceptable
and I suspect there is a better way to do it:

e.g.

if type(s) == type("") :
print "okay, i'm happy you're a string"

If anyone knows a better way, I'm all ears.
There are several way to improve it. In order from smaller to larger
changes:
- don't use type(""), instead, use str:
if type(s) == str:
[notice: this works only from Python 2.2 or so]
- you can compare types by identity and don't need to compare for
equality:
if type(s) is str
- you can do instance tests with isinstance:
if isinstance(s, str):
- try avoiding instance tests altogether. Instead, just let callers
pass anything, and then let the operations fail if they can't handle
the types.

Regards,
Martin
Jan 5 '07 #3

P: n/a
belinda thom a écrit :
Hi,

I've been using the following hack to determine if a type is acceptable
and I suspect there is a better way to do it:

e.g.

if type(s) == type("") :
print "okay, i'm happy you're a string"
if isinstance(s, basestring):
print """
There are very few cases where it makes sens to do such a
test anyway...
"""
If anyone knows a better way, I'm all ears.
A few special cases excepted (ie your function can accept either a
string or a sequence of strings...), the best thing is usually to not
check types at all...
Jan 5 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.