1

Is there way in python to set the default value of a parameter to a property of another parameter?

eg

I currently have a function in django which I would like to do

def supplier_default_product(region, supplier=region.default_supplier.id):
    default_product_instance = Product.objects.get(name=default_product, supplier=supplier)
    ....

so that I can call it with either no supplier where it just uses the regions default supplier:

supplier_default_product(region)

or with a specified supplier:

supplier_default_product(region, supplier)

1 Answer 1

2

Use None as the default argument and then check in the body of the function for None.

def supplier_default_product(region, supplier=None):
    if supplier is None:
        supplier = region.default_supplier.id
    default_product_instance = Product.objects.get(name=default_product, supplier=supplier)

You can't reference an attribute of another argument, because the default argument values are set at define time, which only happens once.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the explanation of why it doesn't work too.
@Yunti No problem. Glad I could help!

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.