开发者

optional flag in a function

开发者 https://www.devze.com 2023-01-30 02:36 出处:网络
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,

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


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.


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)


def fextrao(x, y, a=3):
  print "Got a", a
  #do stuff

def fextrad(x, y, **args):
  # args is a dict here
  if args.has_key('a'):
    print "got a"
  # do stuff here

def fextrat(x, y, *args):
  # args is a tuple here
  if len(args) == 1:
    print "Got tuple", args[0]
  #do stuff

fextrao(1, 2)
fextrao(1, 2, 4)
fextrad(1, 2, a=3, b=4)
fextrat(1, 2, 3, 4)


you can have default values to you function arguments, akin to optional arguments. Something like this:

def myFunction(required, optionalFlag=True):
    if optionalFlag:
        # do default
    else:
        # do something with optionalFlag


# z is the optional flag
def sum(x,y,z = None):
    if z is not None:
        return x+y+z
    else:
        return x+y

# You can call the above function in the following ways
sum(3, 4, z=5)

sum(x=3, y=4, z=5)

# As z is optional, you can also call using only 2 function inputs
sum(2,3)


def somefunc(a,*opa): # opa Optional Positional Arguments
    if 'myflag' in opa:
        pass # do nothing
    else:
        print(a)

somefunc('hi') # prints hi
somefunc('hi','myflag') # prints nothing
0

精彩评论

暂无评论...
验证码 换一张
取 消