0

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?

6
  • 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. Commented Feb 12, 2016 at 12:22
  • @FredrikRosenqvist What if it were a new kind of sequence? Commented Feb 12, 2016 at 12:24
  • What do you mean by sequence? Give an example Commented Feb 12, 2016 at 12:25
  • @FredrikRosenqvist I mean sequence such as a list or a string or a tuple. Commented 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" Commented Feb 12, 2016 at 12:28

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Could be even better using if y is NOT_SET:, this checks object identity instead of equality.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.