Default value not set

advertisements

I'm using python 3.3

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 want to use default value so when I use, print(my_function()) a=10 and b=a so I tried def my_function(a=10,b=a) and I got "a not defined" I don't want to define "a" before with global I want to use something like this "def my_function(a=10,b=a)" is it possible? or something like this

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

This didn't work either when I used "print(my_function())" Thanks in advance David


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. A singleton 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.