Make an Argument Optional in Python [duplicate] - python

This question already has answers here:
Is there a way to pass optional parameters to a function?
(5 answers)
Closed 7 years ago.
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

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)

Related

What does singular "*" as an argument in a python function definition do? [duplicate]

This question already has an answer here:
Keyword only parameter [duplicate]
(1 answer)
Closed 3 months ago.
I am trying to look through some code and don't know what the asterisk in the following code means.
def pylog(func=None, *, mode='cgen', path=WORKSPACE, backend='vhls', \
board='ultra96', freq=None):
What does the lonely asterisk signify in a function definition when not followed by the name of an argument?
I can only find results for *foo.
This syntax forces arguments after the * to be called with their keyword names when someone calls the function/method.
Example:
# This is allowed
pylog(math.log, mode='cgen')
# This is *NOT* allowed
pylog(math.log, 'cgen')

How to pass arguments to a function when called by an array? [duplicate]

This question already has answers here:
Pass a list to a function to act as multiple arguments [duplicate]
(3 answers)
Closed 1 year ago.
I have a function and I have an array of arguments that I want to pass to the function when calling it like this:
def function(arg):
pass
function(arg)#call
but I want:
target = function
args = list()
output = call(function,args)
I know, that I can do it with Thread, but I want get a return to main Thread
Thread(target=target,args=args).start() # without output :(
The only possible solution I have come up with is
output = exec('function_name('+','.join(args))
P.S. The functions that I call have a variable number of positional and optional arguments
P.P.S. I can't edit function's code
If those are positional arguments you can use function(*args).

Python: Nameless keyword argument list [duplicate]

This question already has answers here:
Bare asterisk in function parameters?
(6 answers)
Closed 2 years ago.
What is the meaning of a lone star '*' in the parameter list of a Python function?
I found it in the source of scikit-learn and haven't seen it before. I'm familiar with the concepts of positional and keyword arguments (*args, **vargs). I'm assuming, here it has something to do with the _deprecate_positional_args decorator, but the syntax of a lone star as a function parameter seems to be allowed in pure Python 3.7 even without the decorator.
My guess is, it makes it impossible to specify any keyword arguments after the star as positional arguments (as would actually make sense for a parameter called 'safe').
# Part of https://github.com/scikit-learn/scikit-learn.git
# commit 7117a6313791db6f8b737bac28c1f47277a68cfb
# Quoting from sklearn/base.py:
# ...
from .utils.validation import _deprecate_positional_args
# ...
#_deprecate_positional_args
def clone(estimator, *, safe=True):
"""Constructs a new estimator with the same parameters.
(rest omitted)
"""
# ...
My guess is, it makes it impossible to specify any keyword arguments after the star as positional arguments (as would actually make sense for a parameter called 'safe').
You are right, arguments following lone * are dubbed keyword-only arguments, this feature is defined by PEP 3102.

Generalizing my python function [duplicate]

This question already has answers here:
Can a variable number of arguments be passed to a function?
(6 answers)
Closed 4 years ago.
I am trying to make my function be able to accept as many inputs or as little inputs as needed.
Currently I have 3 inputs that are hard coded (loc1, loc2, loc3). Is there a way to keep the inputs variable so if I just had 1 input, or if I have 5 inputs, my function can be flexible?
def np_array(loc1, loc2, loc3):
loc_a = np.array(loc1)
loc_b = np.array(loc2)
loc_c = np.array(loc3)
pressure_vector1 = np.subtract(loc_a, loc_c)
pressure_vector2 = np.subtract(loc_a, loc_b)
movement_vector = np.add(pressure_vector1, pressure_vector2)
return movement_vector
You can use *args or **kwargs for this.
In Python, the single-asterisk form of *args can be used as a parameter to send a non-keyworded variable-length argument list to functions. It is worth noting that the asterisk (*) is the important element here, as the word args is the established conventional idiom, though it is not enforced by the language.
The double asterisk form of **kwargs is used to pass a keyworded, variable-length argument dictionary to a function. Again, the two asterisks (**) are the important element here, as the word kwargs is conventionally used, though not enforced by the language.
Like *args, **kwargs can take however many arguments you would like to supply to it. However, **kwargs differs from *args in that you will need to assign keywords.
To learn more about this I recommend this awesome post
You could use default arguments to make the function more flexible like:
def np_array(loc1=None, loc2=None, loc3=None):
# ensure you don't use None type variables
if loc1 is None:
loc1 = 'sensibleDefaultValueGoesHere'
# repeat as often as needed before you proceed with the
# actual calculation ...

Python tkinter binding a function with multiple parameters [duplicate]

This question already has answers here:
Tkinter binding a function with arguments to a widget
(2 answers)
Closed 8 months ago.
I have a general question that I can't really find an answer to so hopefully you guys can help. I have a function that takes 3 parameters, below is an example of what I have.
def someFunction(self, event, string):
do stuff ..
self.canvas.bind("<Button-1>", self.someFunction("Hello"))
When I run this, I get an error saying that I passed someFunction 2 arguments instead of 3. I'm not sure why ..
Here you're binding the result of someFunction (or trying to anyway). This fails because when python tries to get the result of someFunction, it calls it only passing 1 argument ("Hello") when someFunction really expects 2 explicit arguments. You probably want something like:
self.canvas.bind('<Button-1>',lambda event: self.someFunction(event,"Hello"))
This binds a new function (which is created by lambda and wraps around self.someFunction) which passes the correct arguments.
Or,
def someFunction(self, string):
def fn(*arg)
print string
return fn
self.canvas.bind("<Button-1>",self.someFunction("Hello!"))

Categories