neurosnap
neurosnap

Reputation: 5798

Python: Checking if a variable is a dictionary

I'm curious if there are any glaring issues with checking if a variable in python is a dictionary? I realize it's not very "pythonic" to do type checking in python, but I'm not sure how else to solve my particular problem.

Here's an example, I'm trying to set attributes of an object based on whether or not a.) the object property exists, and b.) if the value that I'm overwriting is a dictionary. If it is a dictionary, recurse the function to set those child object attributes.

import six

class OtherObj(object):
    def __init__(self, name):
        self.name = name

class ExObj(object):
    def __init__(self, name, description, other_obj):
        self.name = name
        self.description = description
        self.other_obj = other_obj

def process_dict(obj, **kwargs):
        for key, value in six.iteritems(kwargs):
            if hasattr(obj, key):
                if isinstance(value, dict):
                    process_dict(getattr(obj, key), **value)
                else:
                    setattr(obj, key, value)

obj = ExObj("my name", "my desc", OtherObj("another name"))
process_dict(obj, **{ "name": "no this is my real name",
                      "description": "no this is my real desc",
                      "other_obj": { "name": "other object real name" }  })

Upvotes: 1

Views: 4213

Answers (2)

utdemir
utdemir

Reputation: 27216

Well, there is no glaring issues, but if you insist:

  • They usually say that it's better to ask for forgiveness then permission. Maybe just trying to access it via [], catching the possible exception is more Pythonic, but I personally don't think so.
  • But what I'd to is using Abstract Base Classes:

    import collections 
    isinstance(obj, collections.Mapping)  
    

    With this way, the function can support other possible mapping types instead of just dict.

Upvotes: 4

Jordan
Jordan

Reputation: 912

It is actually incredibly simple to do typechecking in python, and can be quite useful(at least I think so).

type(variable)

Upvotes: 0

Related Questions