Let's say I have a function that takes two arguments, x and y. If y is not given, then I'll create a default based on x. Of course, I couldn't define the function with def myfunc(x, y=x+1), because the default would be evaluated at the definition of the function, not when it's called. Instead, therefore, I would define the function with def myfunc(x, y=None), and in my function body check if y is None and if it is, redefine y to x + 1. What if it was possible for y to be anything? What if even None was a possible value? Is there a way that I could tell a difference between myfunc(4) and myfunc(4, None) even though the default for y is None?
-
Your function can't possibly handle "anything" so set the default to something that will never be passed or that you know you will not handle.Fredrik– Fredrik2016-02-12 12:22:53 +00:00Commented Feb 12, 2016 at 12:22
-
@FredrikRosenqvist What if it were a new kind of sequence?zondo– zondo2016-02-12 12:24:13 +00:00Commented Feb 12, 2016 at 12:24
-
What do you mean by sequence? Give an exampleFredrik– Fredrik2016-02-12 12:25:31 +00:00Commented Feb 12, 2016 at 12:25
-
@FredrikRosenqvist I mean sequence such as a list or a string or a tuple.zondo– zondo2016-02-12 12:27:18 +00:00Commented Feb 12, 2016 at 12:27
-
Yes a list, string or tuple is not None? I don't see a problem, you can check the type with "if type(y) is list"Fredrik– Fredrik2016-02-12 12:28:37 +00:00Commented Feb 12, 2016 at 12:28
|
Show 1 more comment
1 Answer
If you really need to know it's not set, this is the way:
NOT_SET = object()
def f(x, y=NOT_SET):
if y is NOT_SET:
# y is not set
This works because of this:
>>> a = object()
>>> b = object()
>>> a is b
False
1 Comment
Georg Schölly
Could be even better using
if y is NOT_SET:, this checks object identity instead of equality.