6

I'm trying to write a function right now, and its purpose is to go through an object's __dict__ and add an item to a dictionary if the item is not a function. Here is my code:

def dict_into_list(self):
    result = {}
    for each_key,each_item in self.__dict__.items():
        if inspect.isfunction(each_key):
            continue
        else:
            result[each_key] = each_item
    return result

If I'm not mistaken, inspect.isfunction is supposed to recognize lambdas as functions as well, correct? However, if I write

c = some_object(3)
c.whatever = lambda x : x*3

then my function still includes the lambda. Can somebody explain why this is?

For example, if I have a class like this:

class WhateverObject:
    def __init__(self,value):
        self._value = value
    def blahblah(self):
        print('hello')
a = WhateverObject(5)

So if I say print(a.__dict__), it should give back {_value:5}

Tyler
  • 365
  • 2
  • 4
  • 15

2 Answers2

4

You are actually checking if each_key is a function, which most likely is not. You actually have to check the value, like this

if inspect.isfunction(each_item):

You can confirm this, by including a print, like this

def dict_into_list(self):
    result = {}
    for each_key, each_item in self.__dict__.items():
        print(type(each_key), type(each_item))
        if inspect.isfunction(each_item) == False:
            result[each_key] = each_item
    return result

Also, you can write your code with dictionary comprehension, like this

def dict_into_list(self):
    return {key: value for key, value in self.__dict__.items()
            if not inspect.isfunction(value)}
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

I can think of an easy way to find the variables of an object through the dir and callable methods of python instead of inspect module.

{var:self.var for var in dir(self) if not callable(getattr(self, var))}

Please note that this indeed assumes that you have not overrided __getattr__ method of the class to do something other than getting the attributes.

thiruvenkadam
  • 4,170
  • 4
  • 27
  • 26