Reputation: 13
I have a function that applies different data preprocessing based on a string argument and am confused on how that is usually done in python because of the lack of switch statements and want to avoid long elif chains.
One solution I found and used was something like:
def preprocessing_a(X,y):
...
return X
def preprocessing_b(X,y):
...
return X
...
def none(X,y):
return X
mode = {
"a" : preprocessing_a
"b" : preprocessing_b
...
"none": none
}
X = mode[input_mode_string](X,y)
I personally found this to seem really clean but got quite a bit of negative feedback for it because I capsuled functions so I wonder how big libraries or larger applications handle this type of input since it's used a lot.
Upvotes: 0
Views: 62
Reputation: 1333
inspect module must help you. getmembers(cls, pred)
gives us information of class.
class Foo(object):
@classmethod
def funcA(self, x, y):
...
@classmethod
def funcB(self, x, y):
...
and
>>> import inspect
...
>>> inspect.getmembers(Foo, ismethod)
>>> [('funcA', <bound method Foo.funcA of <class '__main__.Foo'>>),('funcB', <bound method Foo.funcB of <class '__main__.Foo'>>)]
You can get instances of class methods! Here I use class method, but normal member is enough. Most everything you want to know in Python is enable by inspect.
But remember that this is black magic. To use too much, you won't be able to get out here!
Upvotes: 0