Reputation:
I am trying to understand if it is a good idea or not to pass as parameter the python equivalent of null; which I believe is None.
Example: You have a function that accepts n parameters; in one case I need just the first and second parameters, so instead of writing a long function definition with args and kwargs, and manipulate them, I can just pass null to one of the parameters.
def myfunct(a, b, c[optional], d[optional], e, f....n):
[do something]
if d=="y":
[do something but use only a and b]
Execution:
myfunct(a, b, c, d, .....n) #OK!
myfunct(a, b, None, "y", None,....n) #OK?
This theoretically should not raise an error, since null is a value I believe (this is not C++), although I am not sure if this is a correct way to do things. The function knows that there is a condition when one of the parameters is a specific value, and in that case, it won't ask for any other parameter but 1; so the risk of using null should be practically 0.
Is this acceptable or am I potentially causing issues down the road, using this approach?
Upvotes: 41
Views: 113659
Reputation: 67779
There's nothing wrong with using None to mean "I am not supplying this argument".
You can check for None in your code:
if c is None:
# do something
if d is not None:
# do something else
One recommendation I would make is to have None be the default argument for any optional arguments:
def myfunct(a, b, e, f, c=None, d=None):
# do something
myfunct(A, B, E, F)
Upvotes: 62