简体   繁体   中英

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" }  })

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 .

实际上,在python中进行类型检查非常简单,并且非常有用(至少我认为如此)。

type(variable)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM