简体   繁体   English

Python:检查变量是否为字典

[英]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? 我很好奇在检查python中的变量是否是字典时是否存在任何明显的问题? 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. 我意识到在python中进行类型检查不是很“ pythonic”,但是我不确定如何解决我的特定问题。

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. 这是一个示例,我正在尝试基于以下条件设置对象的属性:a。对象属性是否存在,以及b。)如果我要覆盖的值是字典。 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. 也许只是尝试通过[]访问它,捕获可能的异常更像Pythonic,但我个人并不这么认为。
  • 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 . 通过这种方式,该函数可以支持其他可能的映射类型,而不仅仅是dict

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

type(variable)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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