Make an Argument Optional in Python

401 Views Asked by At

I'm making a Script with a GUI Box in a CAD program, and the User selects about 7 different surfaces in the viewport. I then pass those values onto another Function when the User hits "OK"

The function that it is passed to looks like this

def MeshingTools(od_idSurf, trgSurf, PipeBodySurf, sealSurf, threadSurf, BodySurf, cplgEndSurf):

The problem is: if the user does not need to select one of those surfaces, I get a error saying, MeshingTools() takes exactly 7 non-keyword arguments (2 given)

How can I get around this issue?

UPDATE:

I tried keyword arguments and am not quite getting what I need.

def MeshingTools(**kwargs): print kwargs

When I just select 1 surface, I get the following out

{'PipeBodySurf': (mdb.models['FullCAL4'].rootAssembly.instances['PinNew-1'].edges[151], mdb.models['FullCAL4'].rootAssembly.instances['PinNew-1'].edges[153])}

if I try to print PipeBodySurf , it says that global name is not defined.

Any ideas?

FINAL UPDATE (SOLVED)

Now I see that **kwargs creates a dictionary, so instead of using just the parameter name in the rest of the code, you have to use kwargs['parameter'] and then it will use the values

1

There are 1 best solutions below

4
On BEST ANSWER

You can use arbitrary argument passing with * operation :

def MeshingTools(*args):
  for i in args:
      #do stuff with i  

Functions can use special argument preceded with one or two * character to collect an arbitrary number of extra arguments. (* for positional arguments and ** for keyword arguments)