Reputation: 1926
I am having a little trouble checking if vars(object) is of type dictionary. If it's not of type dictionary, than it will throw an error for doing vars(object):
if type(vars(vars(self.j)['element'])) is dict: # exception gets thrown here if not a dictionary
'this is a dictionary'
you can't use type(vars(object)) if vars(object) not a dictionary. so how do you check if vars(object) is a dictonary?
edit: in response to the answer below:
print type(vars(self.j)['element'])
print isinstance(vars(vars(self.j)['element']), dict) # this is a dict
print type(vars(self.j)['beverage'])
print isinstance(vars(vars(self.j)['beverage']), dict) # exception thrown because its not a dictionary
output:
<class '__main__.Element2'>
True
<type 'str'>
print isinstance(vars(vars(self.j)['beverage']), dict)
TypeError: vars() argument must have __dict__ attribute
edit: in response to bruno, I want to do something like this:
def are_elements_equal(self, first_element, second_element, msg=None):
for i in vars(first_element).keys():
if type(vars(vars(first_element)[i])) is dict:
self.are_elements_equal(vars(first_element)[i], vars(second_element)[i])
else:
self.assertEqual(vars(first_element)[i], vars(second_element)[i])
Upvotes: 0
Views: 100
Reputation: 77912
assuming obj
as a __dict__
attribute, var(obj)
will return a dict
- or eventually a dict_proxy
if called on a class. BUT neither a dict
nor a dict_proxy
have a __dict__
, so vars(vars(obj))
WILL obviously raise a TypeError
- in the inner call if obj
as no __dict__
, else in the outer call.
You could of course handle the exception with a try/except block, but since this will ALWAYS raise, it would be quite pointless. So the real problem is: why do you think you want to use vars(vars(obj))
at all ?
Upvotes: 3