Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optional flag in a function

Tags:

python

I would like to be able to pass extra arguments to a function and IF they are present then act accordingly (say print something out from the function), if those flags are not present, just execute the function normally without printing extra info, how would I approach this ?

Cheers

like image 962
Finger twist Avatar asked Nov 03 '25 20:11

Finger twist


2 Answers

Let's say x, y and z are the required argruments and opt is optional:

def f(x, y, z, opt=None):
  # do required stuff
  if opt is not None:
    # do optional stuff

This can be called with either three or four arguments. You get the idea.

like image 85
NPE Avatar answered Nov 06 '25 11:11

NPE


You could use also keyword arguments:

def f(x, y, **kwargs):
    if 'debug_output' in kwargs:
        print 'Debug output'

Then you can have as many as you like..

f(1,2, debug_output=True, file_output=True)
like image 33
Iacks Avatar answered Nov 06 '25 10:11

Iacks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!