[Baypiggies] Newbie-ish type questions...
Keith Dart
keith at dartworks.biz
Wed Apr 23 12:07:18 CEST 2008
On Tue, 22 Apr 2008, Charles Merriam wrote:
> Hello,
>
> I've been creating a growing number of type functions of the form:
>
> def is_list(l):
> return type(l) is list
>
> def is_string(s):
> return isinstance(s, basestring)
>
> def is_iter(i):
> return hasattr(i, "next") and hasattr(i, "__iter__")
>
> ...etc., etc.
>
> I feel like I must of missed something when I learned Python. Is
> there a simple call I'm missing for
> these? Does this get better in 3.0?
There is the "types" module, that has the types of most Python objects.
However, I really don't see much difference between these:
if is_list(l):
pass
if type(l) is list:
pass
And you also save a function call when using the latter.
However, it is probably preferrable to do this:
if isinstance(l, list):
pass
since that will also catch subclasses of list.
Even better, do type checking sparingly.
--
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Keith Dart <keith at dartworks.biz>
public key: ID: 19017044
<http://www.dartworks.biz/>
=====================================================================
More information about the Baypiggies
mailing list