How to implicitly check method arguments in Python?

How do I avoid using eval() in python in this example?

  • I have objects that have a a bunch of methods.  I store the arguments to the method in a hash so that I have a function that can apply the different methods with their appropriate arguments when necessary, so the whole thing is abstracted like that.  I also store the name of the method that I call, and then retrieve it here: def attrs(objects, *attr): for a in attr: args = attrmethods[a]['args'] for o in objects.keys(): ORFs.__getattribute__(attrmethods[a]['fun'])(objects[o], eval(args)) its super convenient, but i'd like to know if there's a better way

  • Answer:

    I'm not really sure why you're looking to abstract method calls, so some context would certainly come in handy. Having said that, something important to keep in mind with regards to Python is that functions are first class objects. That means we can pass them around and treat them like literally any other kind of object. This also applies to methods, which after all are (not necessarily pure) functions attached to some object. This means we can store a list of functions or methods. It's also worth noting that the self parameter is not cosmetic. Assume we have some class "ClassName" and an instance of the class "obj." The following two lines of code are identical in functionality: ClassName.do_it(obj)obj.do_it() Last, we come to the star operator. In order to unpack an iterable into a list of arguments to pass into a function, we can use the star operator: def do_it(x, y): return x + yif __name__ == '__main__': do_it(*[3, 4])>>> 7 So combining all these lessons together, and here's a sample of what your code could look like: class TestObject(object): def first_method(self, x): return x def second_method(self, y, z): return x+z methods_and_args = [ (TestObject.first_method, [1]), (TestObject.second_method, [2, 3]),]def attrs(objs): for obj in objs: for method, args in methods_and_args: method(obj, *args)

Harold Kingsberg at Quora Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.