3

imagine the following scenario:

class A:
    def __init__(self, arg1=3, arg2=5):
        pass

def createA(arg1=None, arg2=None):
    if arg1 is None:
        if arg2 is None:
            a = A()
        else:
            a = A(arg2=arg2)
    else:
        if arg2 is None:
            a = A(arg1=arg1)
        else:
            a = A(arg1=arg1, arg2=arg2)
    return a

Whats the best way to implement this behavior, with the followings in mind:

  • I can't/don't want to change class A
  • I don't want to explicitly add the default values of A's constructor's parameters to the createA function?

For example is there any value that indicates a not passed optional argument? Something like:

if arg1 is None:
    newArg1 = NotPassed
else:
    newArg1 = arg1

if arg2 is None:
    newArg2 = NotPassed
else:
    newArg2 = arg2
A(arg1=newArg1, arg2=newArg2)
0

1 Answer 1

8
def create_A(arg1=None, arg2=None):
    kwargs = {}
    if arg1 is not None: kwargs['arg1'] = arg1
    if arg1 is not None: kwargs['arg2'] = arg2
    return A(**kwargs)

or maybe even

def create_A(**kwargs):
    return A(**kwargs)
Sign up to request clarification or add additional context in comments.

1 Comment

Very nice, I'm just wondering why Python as a modern language does not provide a special value for this behaviour. Something like A(arg1=1, arg2=Empty) maybe...

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.