6

I want to define a resize(h, w) method, and I want to be able to call it in one of two ways:

  1. resize(x,y)
  2. resize(x)

Where, in the second call, I want y to be equal to x. Can I do this in the method definition or should I do something like resize(x,y=None) and check inside:

if y is None:
    y = x
1
  • 2
    yes, your None code is the preferred way. Commented May 17, 2017 at 12:50

2 Answers 2

6

Can I do this in the method definition

No. During the method definition there's no way to know what value x might have at run-time. Default arguments are evaluated once at definition time, there's no way to save a dynamic value for y.

or should I do something like resize(x,y=None) and check inside

exactly. This is a common idiom in Python.

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

2 Comments

Thx! But cant I give the function an indication to look in other arguments passed, something like resize(x, y = argv[1]) in a way that somewhat resembles the main in C?
@CIsForCookies you could do something like that but it will only be evaluated once when the method is defined. It won't be re-evaluated for every invocation.
2

To complete Jim's answer, in the case that None is valid as a parameter value, you could use variable length arguments feature (positional, and/or keyword). Example of use for positional:

def resize(x,*args):
    if args:
        if len(args)>1:
           raise Exception("Too many arguments")
        y = args[0]
    else:
        y = x

in that example, you have to pass x, but you can pass 0 or more extra positional arguments. Of course you have to do the checking manually, and you lose the y keyword.

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.