Call to Python lambda function without parenthesis

Question:

I have a dictionary that each value is a lambda function with a class getter function.

class test:
    def __init__(
        self,
        filename: str,        
    ):
        self.filename = filename        

    @property
    def read_file(self):
        return read_file(self.filename) # Return pandas dataframe
    

func_1 = test(filename_1)
func_2 = test(filename_2)
ret = {}
ret ["key_1"] = lambda: func_1.read_file
ret ["key_2"] = lambda: func_2.read_file

I want to call to ret with "key_1" without using ()
As I can do it if call to func.read_file (because of @property)
The main idea is to create the dictionary without actually calling to "read_file" function

And when I call the dictionary with a specific key, only one "read_file" call happens.

df = ret ["key_2"]

But now I have to use parenthesis

df = ret ["key_2"]()
Asked By: Eliya

||

Answers:

you can inherit python’s dict and make your own dict with custom getter.
it would be like:

class another_dict(dict):
    def __getitem__(self, key):
        _item = dict.__getitem__(self, key)
        if hasattr(_item, '__call__'):
            _item()
        return _item

d = another_dict()
d['func1'] = lambda: print('lambda called')
d['func1']
Answered By: AMIR

I used the AMIR solution as inspiration but I found a better way (for my problem :)) using functools.partial than lambda:

def read_file(filename):
    return pd.read_csv(filename)

class MyClass:
    def __init__(self):
        self._dict = {}



    def __setitem__(self, key, value):
        self._dict[key] = value

    def __getitem__(self, key):
        return self._dict[key]()
my_class = MyClass()
my_class[key] = partial(read_file, file_name)
df = my_class[key] # This is the first time when read_file happened with a unique filename.
Answered By: Eliya
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.