Should I handle unexpected arguments of a function?

Is there a way to use a dictionary to build up arguments for a function?

  • I have a class whose constructor is something like: def __init__(self, arg1, arg2, arg3, arg4): assign_all_properties() The class has a lot of properties and hence the constructor has a lot of arguments. Then, where I need to instantiate the class, I already have all the property-value pairs in a dictionary. Is there a way to directly use that dictionary to instantiate the class? I tried to build a string and used eval just to see if that would work but not too surprisingly it didn't: args_string = "arg1 = 'value1', arg2 = 'value2'" some_instance = SomeObject(eval(args_string)) I'd hate to enumerate every single arguments. Is there a better way out? I guess, I could do something like: some_instance = SomeObject(**arguments) But I don't want my class to take just *any* parameters.

  • Answer:

    Edit : Didn't read your last sentence, also find a slightly better way 1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829class Base():     signature = {} # Accepted parameters     defaults = {} # Default values for instances     def __init__(self, **kwargs):         # Set the default values for instances         self.__dict__ = self.defaults         # Iterate through kwargs         for key in kwargs.keys():             if key not in self.signature:                 raise Exception("Cannot accept parameter " + key)             else:                 setattr(self, key, kwargs.get(key)) class Animal(Base):     signature = { 'species', 'age' }     defaults = {         'age' : 1     } if __name__ == "__main__":     myDog = Animal(species = 'Dog')     print(myDog.species) # Dog     print(myDog.age) # 1, use default     mySheep = Animal(species = 'Sheep', age = 10)     print(mySheep.species) # Sheep     print(mySheep.age) # 10     # This will fail     myFail = Animal(species = 'Sheep', cute = True)

Evan Sebastian at Quora Visit the source

Was this solution helpful to you?

Other answers

If you have a dictionary with the arguments: args = { 'arg1': 'value1', 'arg2': 'value2', ...} then you can instantiate the object with: obj = SomeObject(**args) The interpreter will check that the arguments in the dictionary match the parameters of the constructor.

Larry Rosenstein

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.