bob.sacamento
bob.sacamento

Reputation: 6661

Disparate methods. Would like for class to be able to treat them all the same

This is a question about a clean, pythonic way to juggle some different instance methods.

I have a class that operates a little differently depending on certain inputs. The differences didn't seem big enough to justify producing entirely new classes. I have to interface the class with one of several data "providers". I thought I was being smart when I introduced a dictionary:

self.interface_tools={'TYPE_A':{ ... various ..., 'data_supplier':self.current_data},
                      'TYPE_B':{ ... various ..., 'data_supplier':self.predicted_data} }

Then, as part of the class initialization, I have an input "source_name" and I do ...

# ... various ....
self.data_supplier = self.interface_tools[source_name]['data_supplier']

self.current_data and self.predicted_data need the same input parameter, so when it comes time to call the method, I don't have to distinguish them. I can just call

new_data = self.data_supplier(param1)

But now I need to interface with a new data source -- call it "TYPE_C" -- and it needs more input parameters. There are ways to do this, but nothing I can think of is very clean. For instance, I could just add the new parameters to the old data_suppliers and never use them, so then the call would look like

new_data = self.data_supplier(param1,param2,param3)

But I don't like that. I could add an if block

if self.data_source != 'TYPE_C':
    new_data = self.data_supplie(param1)
else:
    new_data = self.data_c_supplier(param1,param2,param3)

but avoiding if blocks like this was exactly what I was trying to do in the first place with that dictionary I came up with.

So the upshot is: I have a few "data_supplier" routines. Now that my project has expanded, they have different input lists. But I want my class to be able to treat them all the same to the extent possible. Any ideas? Thanks.

Upvotes: 0

Views: 65

Answers (2)

sureshvv
sureshvv

Reputation: 4422

You could make all your data_suppliers accept a single argument and make it a dictionary or a list or even a NamedTuple.

Upvotes: 1

Amber
Amber

Reputation: 527538

Sounds like your functions could be making use of variable length argument lists.

That said, you could also just make subclasses. They're fairly cheap to make, and would solve your problem here. This is pretty much the case they were designed for.

Upvotes: 1

Related Questions