Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in python, how do you denote required parameters and optional parameters in code?

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.

like image 618
eugene Avatar asked Jul 14 '16 01:07

eugene


2 Answers

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)
like image 105
John Gordon Avatar answered Oct 25 '22 09:10

John Gordon


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.

like image 36
GMarsh Avatar answered Oct 25 '22 10:10

GMarsh