0

JavaScript style

Suppose I have a function takes two objects as optional parameters input, and some of the args in the objects has default value, in JavaScript, I may implement it like this:

function func(setting1, setting2){
    arga = setting1.a || 1;
    argb = setting2.b || 2;
    argc = setting2.c;
    ...
}

Python implementation

There's some ideas comes to my mind, but i think none of them is actually "good".


Here's the first one:

params = {"arga":2, "argb":3}
def func(argc, arga=1, argb=2):
    ...
func(**params)

The question is, this type of implementation cannot support the semantic i want, that is, the setting1 and setting2 need two be separated since they serve for different sub-procedures. Also, It need to manually choose the default parameters's position carefully.


Here's the second one:

def func(setting1, setting2):
    try:
        arga = setting1.a
    except KeyError:
        arga = 1
    ...

I think it's quite ugly.


Maybe this is the best one:

def func(setting1, setting2):
    arga = setting1.get("a") or 1
    argb = setting1.get("b") or 2
    ...

Is there any good way to implement this in python?

2 Answers 2

1

If settingN is a dict, you can do this:

argZ = settingN.get('z', default_value)

So, if settingN doesn't have the key 'z', default_value will be returned.

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

Comments

1

Not sure what you mean by ugly, but this is closest to what you want I think:

def func(setting1 = None, setting2 = None):
    setting1 = "a" if setting1 is None else setting1 
    setting2 = "b" if setting2 is None else setting2

Note there is no real point to this in Python, since it supports default parameters and keyed calls, so

def func(setting1 = "A", setting2 = "B"):

called with

func(setting2="C")

will set only the second setting, and use default for the first. Of course, if the default involves a function call then you have to use your solution.

3 Comments

Since the parameters could be long
@user8510613 I did not understand the comment. In any case, the first solution is the most JS similar solution I know of, requiring no changes on the caller side (like requiring a dictionary).
You're right, i think i could use the ** operator to unpack the two parameter dict to different sub-procedure.

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.