views:

362

answers:

6

I need to determinate is Python variable is instance of native type: str, int, float, bool, list, dict and so on. Is there elegant way to doing it? Or

if myvar in (str, int, float, bool):

are only way to do it?

A: 

Built in type function may be helpful:

>>> a = 5
>>> type(a)
<type 'int'>
kolistivra
+2  A: 

What is a "native type" in Python? Please don't base your code on types, use Duck Typing.

Thanks, I will think twice before do it =)
Aleksandr Motsjonov
+2  A: 

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:

type(theobject).__name__ in dir(__builtins__)

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:

def IntSerializer(theint):
    return str(theint)

def StringSerializer(thestring):
    return repr(thestring)

def MyOwnSerializer(value):
    return "whatever"

serializers = {
    int: IntSerializer,
    str: StringSerializer,
    mymodel.myclass: MyOwnSerializer,
}

def serialize(ob):
    try:
        return ob.serialize() #For objects that know they need to be serialized
    except AttributeError:
        # Look up the serializer amongst the serializer based on type.
        # Default to using "repr" (works for most builtins).
        return serializers.get(type(ob), repr)(ob)

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. :)

Lennart Regebro
it works, but you should not use it :/
NicDumZ
+1 "Changing the application so you don't need to know the difference." Some (extremely rare) times is necesary to know, but most likely isn't.
voyager
+3  A: 

The types module contains all types.

Just put all the ones you want in a list or tuple primitiveTypes and:

if type(myvar) in primitiveTypes:
    ...
Aaron Digulla
thx. it's maybe more elegant than I wrote initially.
Aleksandr Motsjonov
using types from 'types' is no different than using the more straightforward names (int, str, float, ...) directly!
kaizer.se
Yes, that's how types works. But it makes your intention more clean and if you use the predefined sets (StringTypes), you get additional portability between Python versions.
Aaron Digulla
It's also slightly faster ... ;)
Aaron Digulla
+4  A: 

You appear to be interested in assuring the simplejson will handle your types. This is done trivially by

try:
    json.dumps( object )
except TypeError:
    print "Can't convert", object

Which is more reliable than trying to guess which types your JSON implementation handles.

S.Lott
this is more pythonic 'cause if the object can be dumped (say perhaps simplejson adds more support) then it will be used first, and then in the except you should call your catchall functionality. +1
Terence Honles
A: 

building off of S.Lott's answer you should have something like this:


from simplejson import JSONEncoder

class JSONEncodeAll(JSONEncoder):
  def default(self, obj):
    try:
      return JSONEncoder.default(self, obj)
    except TypeError:
      ## optionally
      # try:
      #   # you'd have to add this per object, but if an object wants to do something
      #   # special then it can do whatever it wants
      #   return obj.__json__()
      # except AttributeError:
      ##

      # ...do whatever you are doing now...
      # (which should be creating an object simplejson understands)

to use:


>>> json = JSONEncodeAll()

>>> json.encode(myObject)
# whatever myObject looks like when it passes through your serialization code

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

Terence Honles