I want to create a function that accepts multiple arguments (kwargs) while calling, but I want to ensure it gets at least one argument with a key, How should I do it?
Is it supposed to be specific required keyword argument, or any keyword argument?
Any key word argument
Have you then tried checking if variable with keywords contains anything?
I am working on the free code camp python project that involves probability:
First, create a Hat class in prob_calculator.py. The class should take a variable number of arguments that specify the number of balls of each color that are in the hat. For example, a class object could be created in any of these ways:
hat1 = Hat(yellow=3, blue=2, green=6)
hat2 = Hat(red=5, orange=4)
hat3 = Hat(red=5, orange=4, black=1, blue=0, pink=2, striped=9)
hat1 = Hat(yellow=3, blue=2, green=6)
hat2 = Hat(red=5, orange=4)
hat3 = Hat(red=5, orange=4, black=1, blue=0, pink=2, striped=9)
A hat will always be created with at least one ball.
I want to make sure the caller includes at least one keyword argument.
In here, such check would be placed in the __init__
method of the class. How does it look like?
def __init__(self, **kwargs):
self.kwargs = kwargs
self.contents = []
for k, v in self.kwargs.items():
for i in range(v):
self.contents.append(k)
How could you check if kwargs
variable contains anything?
I would do it with the len( ) function:
if len(kwargs) > 0:
do something
And if it doesn’t satisfy this condition I would like the caller to enter inputs again. But I am also wondering if there is a way in which the instance itself is not to be created (python returns error) unless we pass some keyword argument.
You could raise
some exception when kwargs
is empty. That will stop execution with an error.
How could I do that?
Using the raise
keyword, ie.:
raise NameOfTheException
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.