0

I wonder if there are any good practices in python how to handle cases if I want to pass optional argument to function.

I have this function in class:

def gen(self, arg1, arg2, optional):
    if optional exists do that:
        print(optional)
    else:
        print(arg1, arg2)

What I can do right now is just handle that by if, but I don't think this is the best way to do that.

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
pyton17
  • 55
  • 10
  • Based on your example, do you really ignore `arg1` and `arg2` if `optional` is present? – chepner May 17 '18 at 18:02
  • You can refer https://stackoverflow.com/questions/9539921/how-do-i-create-a-python-function-with-optional-arguments – Pushplata May 17 '18 at 18:06

1 Answers1

3

If you want to pass optional arguments to function consider using*args and **kwargs or just use default parameter.

e.g with *args and **kwargs

In [3]: def test(a, b, c, *args, **kwargs):
   ...:     print a, b, b
   ...:     if args:
   ...:         print args # do something, which is optional
   ...:     if kwargs:
   ...:         print kwargs # do something, which is optional
   ...:
   ...:

In [4]: test(1, 2, 3, 4, 5 ,6, 7, name='abc', place='xyz')
1 2 2
(4, 5, 6, 7)
{'place': 'xyz', 'name': 'abc'}

In [5]:

e.g. with default parameter.

def gen(self, arg1, arg2, optional=None):
    if optional:
        # do something
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81