I need to determine if a given Python variable is an instance of native type: str
, int
, float
, bool
, list
, dict
and so on. Is there elegant way to doing it?
Or is this the only way:
if myvar in (str, int, float, bool):
# do something
For me the best option is:
This fix when value is a module and
value.__class__.__module__ == '__builtin__'
will fail.This is an old question but it seems none of the answers actually answer the specific question: "(How-to) Determine if Python variable is an instance of a built-in type". Note that it's not "[...] of a specific/given built-in type" but of a.
The proper way to determine if a given object is an instance of a buil-in type/class is to check if the type of the object happens to be defined in the module
__builtin__
.Warning: if
obj
is a class and not an instance, no matter if that class is built-in or not, True will be returned since a class is also an object, an instance oftype
(i.e.AnyClass.__class__
istype
).You appear to be interested in assuring the simplejson will handle your types. This is done trivially by
Which is more reliable than trying to guess which types your JSON implementation handles.
building off of S.Lott's answer you should have something like this:
to use:
these calls will use your special class and if simplejson can take care of the object it will. Otherwise your catchall functionality will be triggered, and possibly (depending if you use the optional part) an object can define it's own serialization
Built in type function may be helpful:
Not that I know why you would want to do it, as there isn't any "simple" types in Python, it's all objects. But this works:
But explicitly listing the types is probably better as it's clearer. Or even better: Changing the application so you don't need to know the difference.
Update: The problem that needs solving is how to make a serializer for objects, even those built-in. The best way to do this is not to make a big phat serializer that treats builtins differently, but to look up serializers based on type.
Something like this:
This way you can easily add new serializers, and the code is easy to maintain and clear, as each type has its own serializer. Notice how the fact that some types are builtin became completely irrelevant. :)