Skip to content Skip to sidebar Skip to footer

Function Default Value Not Defined

I'm trying to use def my_function(a,b) If I try to print function like this print(my_function()), when values start from none, I get 'missing 2 required positional arguments' I w

Solution 1:

You can set the default to None:

def my_function(a=10, b=None):
    if b is None:
        b = a

Here the default for a is 10, and b is set to a if left to the default value.

If you need to accept None as well, pick a different, unique default to act as a sentinel. An instance of object() is an oft-used convention:

_sentinel = object()

def my_function(a=10, b=_sentinel):
    if b is _sentinel:
        b = a

Now you can call my_function(11, None) and b will be set to None, call it without specifying b (e.g. my_function() or my_function(42), and b will be set to whatever a was set to.

Unless a parameter has a default (e.g. is a keyword parameter), they are required.


Solution 2:

This function my_function(a,b) expected two positional arguments without default value so It can't be called without them passed

So the main question how can we pass two argument so that second is set to first if not passed

There are two way for this:

kwargs unpacking

def my_function(a=10, **kwargs):
    b = kwargs.get('b', a)

sentinel as default Value

_sentinel = object()
def my_function(a=10, b=_sentinel):
    if b is _sentinel:
        b = a

Solution 3:

Hum! I thing you can't define my_function like this. But you can use a decorator to hide the default values computation.

For example:

import functools


def my_decorator(f):
    @functools.wraps(f)
    def wrapper(a=10, b=None):
        if b is None:
            b = a
        return f(a, b)
    return wrapper

You can then define your function like this:

@my_decorator
def my_function(a, b):
    return (a, b)

You can use your function with zero, one or two parameters:

>>> print(my_function())
(10, 10)
>>> print(my_function(5))
(5, 5)
>>> print(my_function(5, 12))
(5, 12)

Post a Comment for "Function Default Value Not Defined"