Default parameter value for objects

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?

Upvotes: 3

Views: 156

Answers (1)

denisvm
denisvm

Reputation: 730

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))

Upvotes: 2

Related Questions