especially when there are so many parameters (10+ 20+).
What are good ways of enforcing required/optional
parameters to a function?
What are some good books that deal with this kind of questions for python?
(like effective c++ for c++)
** EDIT **
I think it's very unpractical to list def foo(self, arg1, arg2, arg3, .. arg20, .....):
when there are so many required parameters.
Parameters can be required or optional depending on how they appear in the function definition:
def myfunction(p1, p2, p3=False, p4=5)
In this definition, parameters p1
and p2
are required. p3
is optional and will acquire the value False
if not provided by the caller. p4
is also optional and will acquire the value 5
if not provided.
If you really need to pass ten or more parameters into a function, it might be better to pass them as a dictionary:
args = {'a': something, 'b': something_else, 'c': 5, 'd': 99.99, ... }
myfunc(args)
If a function parameter is not required, you can set it equal to None.
def hello(first_name, last_name=None):
print "Hello " + first_name
Or as John Gordon said, you can set a parameter with a default value the same way.
Note that optional parameters need to be defined after the required parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With