Determine if Python variable is an instance of a built-in type

前端 未结 9 2336
难免孤独
难免孤独 2020-12-05 23:39

I need to determine if a given Python variable is an instance of native type: str, int, float, bool, list, <

9条回答
  •  一生所求
    2020-12-05 23:54

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

提交回复
热议问题