Python: Nameless keyword argument list [duplicate] - python

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.

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')

What are practical use case of Positional only arguments and Keyword only arguments in python? [duplicate]

This question already has answers here:
Why use positional only arguments in python 3.8?
(1 answer)
Mandatory keywords arguments
(2 answers)
Closed 11 months ago.
Python has support for postional only and keyword only arguments
Positional only arguments
def postional_only_func(a,b,/):
...
Keyword only arguments
def keyword_only_func(*,a,b):
...
But, what are its practical use case when writing a function? Is it just to make code more readable?
Both of these features were added to make writing certain functions easier. IF you want to read the full rational and motivation, you should read the corresponding PEPs:
PEP 570 – Python Positional-Only Parameters
PEP 3102 – Keyword-Only Arguments
For positional only, here are concrete examples for use-cases, using examples from the built-in functions:
There are functions with other interesting semantics:
range(), an overloaded function, accepts an optional parameter to the left of its required parameter. [4]
dict(), whose mapping/iterator parameter is optional and semantically must be positional-only. Any externally visible name for
this parameter would occlude that name going into the **kwarg keyword
variadic parameter dict. [3]
One can emulate these semantics in Python code by accepting (*args,
**kwargs) and parsing the arguments manually. However, this results in a disconnect between the function definition and what the function
contractually accepts. The function definition does not match the
logic of the argument handling.
And for keyword-only arguments it says the following regarding motivation:
There are often cases where it is desirable for a function to take a
variable number of arguments. The Python language supports this using
the ‘varargs’ syntax (*name), which specifies that any ‘left over’
arguments be passed into the varargs parameter as a tuple.
One limitation on this is that currently, all of the regular argument
slots must be filled before the vararg slot can be.
This is not always desirable. One can easily envision a function which
takes a variable number of arguments, but also takes one or more
‘options’ in the form of keyword arguments. Currently, the only way to
do this is to define both a varargs argument, and a ‘keywords’
argument (**kwargs), and then manually extract the desired keywords
from the dictionary.

What is the problem in the Python code below? [duplicate]

This question already has answers here:
Bare asterisk in function parameters?
(6 answers)
Closed 2 years ago.
The Python code below throws an error.
def f(a,*, **c):
pass
The error says that SyntaxError: named arguments must follow bare *. I couldn't understand what this means in this case. I have specified a parameter after the bare *, yet I get an error.
A standalone * parameter is only necessary (and as you've seen, allowed) if you specify one or more named keyword-only parameters following it. Since you have no named keyword-only parameters, you need to omit it.
def f(a, **c):
pass
If you want a to be a positional-only argument, you need to use a standalone / parameter:
def f(a, /, **c):
pass

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 ...

Make an Argument Optional in Python [duplicate]

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)

Categories