checking one's type
"Martin v. Löwis"
martin at v.loewis.de
Fri Jan 5 04:30:11 EST 2007
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
More information about the Python-list
mailing list