3

Python provides a way to set a default value for function parameters. An example is:

def f(x=3):
    print(x)

This is for a primitive type, lets try with objects:

def f(x=list()):
    print(id(x))     
f()

44289920

f()

44289920

Same object! I was surprised of this being used to the C/C++ way. Done with that, I now understand the default value is not build at invoking time but at definition time.

So I came to a solution:

def f(x=list()):
    if len(x) == 0:
        x = list()
    print(id(x))

Solved! But at what price: In my opinion this doesn't seem to be a very clean solution. This solution rely in the use of len(x) == 0 as a way to identify the default value which is Ok for my function but not for others so the solution can be generalized as:

def f(x=None):
    if x is None:
        x = list()

This can be shortened to:

def f(x=None):
    x = x or list()  # a bit shorter version

My question is, is there any shorter or better way to solve this problem? Will it ever be?

11
  • x=list() is executed exactly once when the def is executed. So the default value for x of all calls to f refer to the same object. Commented Jun 27, 2014 at 9:00
  • 1
    @LutzHorn Read on; that isn't the question. Commented Jun 27, 2014 at 9:00
  • The question is: "is there any shorter or better way to solve this problem? Will it ever be?". The answer is: No, because (see above). Commented Jun 27, 2014 at 9:01
  • 1
    Related: Why the “mutable default argument fix” syntax is so ugly, asks python newbie Commented Jun 27, 2014 at 9:05
  • 1
    Only improvement you can do here is to use x is None instead of ==. Commented Jun 27, 2014 at 9:08

1 Answer 1

2

I still prefer the is None approach, but here is a new option to think about: If is defined only the type, you create a new instance of it.

def f(x=list):
    if isinstance(x, type): x = x()
    print(id(x))
Sign up to request clarification or add additional context in comments.

Comments

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.